blob: d66e5cedc3ef10edcf31ef5240142edb775abd9d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
57import android.content.pm.PackageStats;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
Kenny Root9f306d72010-09-26 11:19:47 -070094import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.FileReader;
101import java.io.FilenameFilter;
102import java.io.IOException;
103import java.io.InputStream;
104import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800105import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
108import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700109import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Collections;
111import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800112import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.Enumeration;
114import java.util.HashMap;
115import java.util.HashSet;
116import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700117import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.List;
119import java.util.Map;
120import java.util.Set;
121import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800122import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import java.util.zip.ZipFile;
124import java.util.zip.ZipOutputStream;
125
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700126/**
127 * Keep track of all those .apks everywhere.
128 *
129 * This is very central to the platform's security; please run the unit
130 * tests whenever making modifications here:
131 *
132mmm frameworks/base/tests/AndroidTests
133adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
134adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
135 *
136 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137class PackageManagerService extends IPackageManager.Stub {
138 private static final String TAG = "PackageManager";
139 private static final boolean DEBUG_SETTINGS = false;
140 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800141 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800142 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700143 private static final boolean DEBUG_NATIVE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
145 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
146 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400147 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private static final int FIRST_APPLICATION_UID =
149 Process.FIRST_APPLICATION_UID;
150 private static final int MAX_APPLICATION_UIDS = 1000;
151
152 private static final boolean SHOW_INFO = false;
153
154 private static final boolean GET_CERTIFICATES = true;
155
Oscar Montemayora8529f62009-11-18 10:14:20 -0800156 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private static final int REMOVE_EVENTS =
159 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
160 private static final int ADD_EVENTS =
161 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
162
163 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800164 // Suffix used during package installation when copying/moving
165 // package apks to install directory.
166 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800168 /**
169 * Indicates the state of installation. Used by PackageManager to
170 * figure out incomplete installations. Say a package is being installed
171 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
172 * the package installation is successful or unsuccesful lin which case
173 * the PackageManager will no longer maintain state information associated
174 * with the package. If some exception(like device freeze or battery being
175 * pulled out) occurs during installation of a package, the PackageManager
176 * needs this information to clean up the previously failed installation.
177 */
178 private static final int PKG_INSTALL_INCOMPLETE = 0;
179 private static final int PKG_INSTALL_COMPLETE = 1;
180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final int SCAN_MONITOR = 1<<0;
182 static final int SCAN_NO_DEX = 1<<1;
183 static final int SCAN_FORCE_DEX = 1<<2;
184 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800185 static final int SCAN_NEW_INSTALL = 1<<4;
186 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700188 static final int REMOVE_CHATTY = 1<<16;
189
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800190 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
191 "com.android.defcontainer",
192 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700193
Kenny Root85387d72010-08-26 10:13:11 -0700194 private static final String LIB_DIR_NAME = "lib";
195
Kenny Rootc78a8072010-07-27 15:18:38 -0700196 static final String mTempContainerPrefix = "smdl2tmp";
197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
199 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700200 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn851a5412009-05-08 12:06:44 -0700202 final int mSdkVersion = Build.VERSION.SDK_INT;
203 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
204 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 final Context mContext;
207 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700208 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 final DisplayMetrics mMetrics;
210 final int mDefParseFlags;
211 final String[] mSeparateProcesses;
212
213 // This is where all application persistent data goes.
214 final File mAppDataDir;
215
Oscar Montemayora8529f62009-11-18 10:14:20 -0800216 // If Encrypted File System feature is enabled, all application persistent data
217 // should go here instead.
218 final File mSecureAppDataDir;
219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 // This is the object monitoring the framework dir.
221 final FileObserver mFrameworkInstallObserver;
222
223 // This is the object monitoring the system app dir.
224 final FileObserver mSystemInstallObserver;
225
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700226 // This is the object monitoring the system app dir.
227 final FileObserver mVendorInstallObserver;
228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // This is the object monitoring mAppInstallDir.
230 final FileObserver mAppInstallObserver;
231
232 // This is the object monitoring mDrmAppPrivateInstallDir.
233 final FileObserver mDrmAppInstallObserver;
234
235 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
236 // LOCK HELD. Can be called with mInstallLock held.
237 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 final File mFrameworkDir;
240 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700241 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700243 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
245 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
246 // apps.
247 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // Lock for state used when installing and doing other long running
252 // operations. Methods that must be called with this lock held have
253 // the prefix "LI".
254 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 // These are the directories in the 3rd party applications installed dir
257 // that we have currently loaded packages from. Keys are the application's
258 // installed zip file (absolute codePath), and values are Package.
259 final HashMap<String, PackageParser.Package> mAppDirs =
260 new HashMap<String, PackageParser.Package>();
261
262 // Information for the parser to write more useful error messages.
263 File mScanningPath;
264 int mLastScanError;
265
266 final int[] mOutPermissions = new int[3];
267
268 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // Keys are String (package name), values are Package. This also serves
271 // as the lock for the global state. Methods that must be called with
272 // this lock held have the prefix "LP".
273 final HashMap<String, PackageParser.Package> mPackages =
274 new HashMap<String, PackageParser.Package>();
275
276 final Settings mSettings;
277 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278
279 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
280 int[] mGlobalGids;
281
282 // These are the built-in uid -> permission mappings that were read from the
283 // etc/permissions.xml file.
284 final SparseArray<HashSet<String>> mSystemPermissions =
285 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 // These are the built-in shared libraries that were read from the
288 // etc/permissions.xml file.
289 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800290
Dianne Hackborn49237342009-08-27 20:08:01 -0700291 // Temporary for building the final shared libraries for an .apk.
292 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
Dianne Hackborn49237342009-08-27 20:08:01 -0700294 // These are the features this devices supports that were read from the
295 // etc/permissions.xml file.
296 final HashMap<String, FeatureInfo> mAvailableFeatures =
297 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 // All available activities, for your resolving pleasure.
300 final ActivityIntentResolver mActivities =
301 new ActivityIntentResolver();
302
303 // All available receivers, for your resolving pleasure.
304 final ActivityIntentResolver mReceivers =
305 new ActivityIntentResolver();
306
307 // All available services, for your resolving pleasure.
308 final ServiceIntentResolver mServices = new ServiceIntentResolver();
309
310 // Keys are String (provider class name), values are Provider.
311 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
312 new HashMap<ComponentName, PackageParser.Provider>();
313
314 // Mapping from provider base names (first directory in content URI codePath)
315 // to the provider information.
316 final HashMap<String, PackageParser.Provider> mProviders =
317 new HashMap<String, PackageParser.Provider>();
318
319 // Mapping from instrumentation class names to info about them.
320 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
321 new HashMap<ComponentName, PackageParser.Instrumentation>();
322
323 // Mapping from permission names to info about them.
324 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
325 new HashMap<String, PackageParser.PermissionGroup>();
326
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800327 // Packages whose data we have transfered into another package, thus
328 // should no longer exist.
329 final HashSet<String> mTransferedPackages = new HashSet<String>();
330
Dianne Hackborn854060af2009-07-09 18:14:31 -0700331 // Broadcast actions that are only available to the system.
332 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 boolean mSystemReady;
335 boolean mSafeMode;
336 boolean mHasSystemUidErrors;
337
338 ApplicationInfo mAndroidApplication;
339 final ActivityInfo mResolveActivity = new ActivityInfo();
340 final ResolveInfo mResolveInfo = new ResolveInfo();
341 ComponentName mResolveComponentName;
342 PackageParser.Package mPlatformPackage;
343
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700344 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800345 final HashMap<String, ArrayList<String>> mPendingBroadcasts
346 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800347 // Service Connection to remote media container service to copy
348 // package uri's from external media onto secure containers
349 // or internal storage.
350 private IMediaContainerService mContainerService = null;
351
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700352 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800353 static final int MCS_BOUND = 3;
354 static final int END_COPY = 4;
355 static final int INIT_COPY = 5;
356 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800357 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800358 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800359 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800360 static final int MCS_RECONNECT = 10;
361 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700362 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700363 static final int WRITE_SETTINGS = 13;
364
365 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800366
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700367 // Delay time in millisecs
368 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369 final private DefaultContainerConnection mDefContainerConn =
370 new DefaultContainerConnection();
371 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800372 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800373 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800374 IMediaContainerService imcs =
375 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800376 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800377 }
378
379 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800380 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800381 }
382 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700383
Christopher Tate1bb69062010-02-19 17:02:12 -0800384 // Recordkeeping of restore-after-install operations that are currently in flight
385 // between the Package Manager and the Backup Manager
386 class PostInstallData {
387 public InstallArgs args;
388 public PackageInstalledInfo res;
389
390 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
391 args = _a;
392 res = _r;
393 }
394 };
395 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
396 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
397
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700398 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800399 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800400 final ArrayList<HandlerParams> mPendingInstalls =
401 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402
403 private boolean connectToService() {
404 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
405 " DefaultContainerService");
406 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700407 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800408 if (mContext.bindService(service, mDefContainerConn,
409 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800411 mBound = true;
412 return true;
413 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800415 return false;
416 }
417
418 private void disconnectService() {
419 mContainerService = null;
420 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700421 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800422 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700423 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800424 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800425
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700426 PackageHandler(Looper looper) {
427 super(looper);
428 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700429
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700430 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700431 try {
432 doHandleMessage(msg);
433 } finally {
434 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
435 }
436 }
437
438 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700439 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800440 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800441 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800442 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800443 int idx = mPendingInstalls.size();
444 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
445 // If a bind was already initiated we dont really
446 // need to do anything. The pending install
447 // will be processed later on.
448 if (!mBound) {
449 // If this is the only one pending we might
450 // have to bind to the service again.
451 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800452 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800453 params.serviceError();
454 return;
455 } else {
456 // Once we bind to the service, the first
457 // pending request will be processed.
458 mPendingInstalls.add(idx, params);
459 }
460 } else {
461 mPendingInstalls.add(idx, params);
462 // Already bound to the service. Just make
463 // sure we trigger off processing the first request.
464 if (idx == 0) {
465 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800466 }
467 }
468 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800469 }
470 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800471 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800472 if (msg.obj != null) {
473 mContainerService = (IMediaContainerService) msg.obj;
474 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800475 if (mContainerService == null) {
476 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800477 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 for (HandlerParams params : mPendingInstalls) {
479 mPendingInstalls.remove(0);
480 // Indicate service bind error
481 params.serviceError();
482 }
483 mPendingInstalls.clear();
484 } else if (mPendingInstalls.size() > 0) {
485 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800486 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 params.startCopy();
488 }
489 } else {
490 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800491 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800492 }
493 break;
494 }
495 case MCS_RECONNECT : {
496 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
497 if (mPendingInstalls.size() > 0) {
498 if (mBound) {
499 disconnectService();
500 }
501 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800502 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800503 for (HandlerParams params : mPendingInstalls) {
504 mPendingInstalls.remove(0);
505 // Indicate service bind error
506 params.serviceError();
507 }
508 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800509 }
510 }
511 break;
512 }
513 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800514 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
515 // Delete pending install
516 if (mPendingInstalls.size() > 0) {
517 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800518 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800519 if (mPendingInstalls.size() == 0) {
520 if (mBound) {
521 disconnectService();
522 }
523 } else {
524 // There are more pending requests in queue.
525 // Just post MCS_BOUND message to trigger processing
526 // of next pending install.
527 mHandler.sendEmptyMessage(MCS_BOUND);
528 }
529 break;
530 }
531 case MCS_GIVE_UP: {
532 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
533 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800534 break;
535 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700536 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800537 String packages[];
538 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700540 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700541 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800543 if (mPendingBroadcasts == null) {
544 return;
545 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700546 size = mPendingBroadcasts.size();
547 if (size <= 0) {
548 // Nothing to be done. Just return
549 return;
550 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800551 packages = new String[size];
552 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700553 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 Iterator<HashMap.Entry<String, ArrayList<String>>>
555 it = mPendingBroadcasts.entrySet().iterator();
556 int i = 0;
557 while (it.hasNext() && i < size) {
558 HashMap.Entry<String, ArrayList<String>> ent = it.next();
559 packages[i] = ent.getKey();
560 components[i] = ent.getValue();
561 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700562 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800563 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700564 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800565 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700566 mPendingBroadcasts.clear();
567 }
568 // Send broadcasts
569 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800570 sendPackageChangedBroadcast(packages[i], true,
571 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700572 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700573 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700574 break;
575 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800576 case START_CLEANING_PACKAGE: {
577 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700578 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800579 synchronized (mPackages) {
580 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
581 mSettings.mPackagesToBeCleaned.add(packageName);
582 }
583 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700584 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800585 startCleaningPackages();
586 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800587 case POST_INSTALL: {
588 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
589 PostInstallData data = mRunningInstalls.get(msg.arg1);
590 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700591 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800592
593 if (data != null) {
594 InstallArgs args = data.args;
595 PackageInstalledInfo res = data.res;
596
597 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700598 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800599 Bundle extras = new Bundle(1);
600 extras.putInt(Intent.EXTRA_UID, res.uid);
601 final boolean update = res.removedInfo.removedPackage != null;
602 if (update) {
603 extras.putBoolean(Intent.EXTRA_REPLACING, true);
604 }
605 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
606 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700607 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800608 if (update) {
609 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
610 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700611 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800612 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700613 if (res.removedInfo.args != null) {
614 // Remove the replaced package's older resources safely now
615 deleteOld = true;
616 }
617 }
618 // Force a gc to clear up things
619 Runtime.getRuntime().gc();
620 // We delete after a gc for applications on sdcard.
621 if (deleteOld) {
622 synchronized (mInstallLock) {
623 res.removedInfo.args.doPostDeleteLI(true);
624 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800625 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800626 if (args.observer != null) {
627 try {
628 args.observer.packageInstalled(res.name, res.returnCode);
629 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800630 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800631 }
632 }
633 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800634 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800635 }
636 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700637 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700638 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
639 boolean reportStatus = msg.arg1 == 1;
640 boolean doGc = msg.arg2 == 1;
641 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
642 if (doGc) {
643 // Force a gc to clear up stale containers.
644 Runtime.getRuntime().gc();
645 }
646 if (msg.obj != null) {
647 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
648 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
649 // Unload containers
650 unloadAllContainers(args);
651 }
652 if (reportStatus) {
653 try {
654 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
655 PackageHelper.getMountService().finishMediaUpdate();
656 } catch (RemoteException e) {
657 Log.e(TAG, "MountService not running?");
658 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700659 }
660 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700661 case WRITE_SETTINGS: {
662 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
663 synchronized (mPackages) {
664 removeMessages(WRITE_SETTINGS);
665 mSettings.writeLP();
666 }
667 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
668 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700669 }
670 }
671 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800672
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700673 void scheduleWriteSettingsLocked() {
674 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
675 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
676 }
677 }
678
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800679 static boolean installOnSd(int flags) {
680 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700681 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800682 return false;
683 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700684 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
685 return true;
686 }
687 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800688 }
689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 public static final IPackageManager main(Context context, boolean factoryTest) {
691 PackageManagerService m = new PackageManagerService(context, factoryTest);
692 ServiceManager.addService("package", m);
693 return m;
694 }
695
696 static String[] splitString(String str, char sep) {
697 int count = 1;
698 int i = 0;
699 while ((i=str.indexOf(sep, i)) >= 0) {
700 count++;
701 i++;
702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 String[] res = new String[count];
705 i=0;
706 count = 0;
707 int lastI=0;
708 while ((i=str.indexOf(sep, i)) >= 0) {
709 res[count] = str.substring(lastI, i);
710 count++;
711 i++;
712 lastI = i;
713 }
714 res[count] = str.substring(lastI, str.length());
715 return res;
716 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800723 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 mContext = context;
727 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700728 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 mMetrics = new DisplayMetrics();
730 mSettings = new Settings();
731 mSettings.addSharedUserLP("android.uid.system",
732 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
733 mSettings.addSharedUserLP("android.uid.phone",
734 MULTIPLE_APPLICATION_UIDS
735 ? RADIO_UID : FIRST_APPLICATION_UID,
736 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400737 mSettings.addSharedUserLP("android.uid.log",
738 MULTIPLE_APPLICATION_UIDS
739 ? LOG_UID : FIRST_APPLICATION_UID,
740 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741
742 String separateProcesses = SystemProperties.get("debug.separate_processes");
743 if (separateProcesses != null && separateProcesses.length() > 0) {
744 if ("*".equals(separateProcesses)) {
745 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
746 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800747 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 } else {
749 mDefParseFlags = 0;
750 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800751 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 + separateProcesses);
753 }
754 } else {
755 mDefParseFlags = 0;
756 mSeparateProcesses = null;
757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 Installer installer = new Installer();
760 // Little hacky thing to check if installd is here, to determine
761 // whether we are running on the simulator and thus need to take
762 // care of building the /data file structure ourself.
763 // (apparently the sim now has a working installer)
764 if (installer.ping() && Process.supportsProcesses()) {
765 mInstaller = installer;
766 } else {
767 mInstaller = null;
768 }
769
770 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
771 Display d = wm.getDefaultDisplay();
772 d.getMetrics(mMetrics);
773
774 synchronized (mInstallLock) {
775 synchronized (mPackages) {
776 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700777 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 File dataDir = Environment.getDataDirectory();
780 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800781 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
783
784 if (mInstaller == null) {
785 // Make sure these dirs exist, when we are running in
786 // the simulator.
787 // Make a wide-open directory for random misc stuff.
788 File miscDir = new File(dataDir, "misc");
789 miscDir.mkdirs();
790 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800791 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 mDrmAppPrivateInstallDir.mkdirs();
793 }
794
795 readPermissions();
796
797 mRestoredSettings = mSettings.readLP();
798 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800799
800 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800802
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800803 // Set flag to monitor and not change apk file paths when
804 // scanning install directories.
805 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700806 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800807 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800808 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700814 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700817 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 /**
820 * Out of paranoia, ensure that everything in the boot class
821 * path has been dexed.
822 */
823 String bootClassPath = System.getProperty("java.boot.class.path");
824 if (bootClassPath != null) {
825 String[] paths = splitString(bootClassPath, ':');
826 for (int i=0; i<paths.length; i++) {
827 try {
828 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
829 libFiles.add(paths[i]);
830 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700831 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800834 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800836 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 }
838 }
839 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800840 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 /**
844 * Also ensure all external libraries have had dexopt run on them.
845 */
846 if (mSharedLibraries.size() > 0) {
847 Iterator<String> libs = mSharedLibraries.values().iterator();
848 while (libs.hasNext()) {
849 String lib = libs.next();
850 try {
851 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
852 libFiles.add(lib);
853 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700854 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800857 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800859 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
861 }
862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 // Gross hack for now: we know this file doesn't contain any
865 // code, so don't dexopt it to avoid the resulting log spew.
866 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 /**
869 * And there are a number of commands implemented in Java, which
870 * we currently need to do the dexopt on so that they can be
871 * run from a non-root shell.
872 */
873 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700874 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 for (int i=0; i<frameworkFiles.length; i++) {
876 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
877 String path = libPath.getPath();
878 // Skip the file if we alrady did it.
879 if (libFiles.contains(path)) {
880 continue;
881 }
882 // Skip the file if it is not a type we want to dexopt.
883 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
884 continue;
885 }
886 try {
887 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
888 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700889 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
891 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800892 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800894 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
896 }
897 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800898
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700899 if (didDexOpt) {
900 // If we had to do a dexopt of one of the previous
901 // things, then something on the system has changed.
902 // Consider this significant, and wipe away all other
903 // existing dexopt files to ensure we don't leave any
904 // dangling around.
905 String[] files = mDalvikCacheDir.list();
906 if (files != null) {
907 for (int i=0; i<files.length; i++) {
908 String fn = files[i];
909 if (fn.startsWith("data@app@")
910 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800911 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700912 (new File(mDalvikCacheDir, fn)).delete();
913 }
914 }
915 }
916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800918
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800919 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 mFrameworkInstallObserver = new AppDirObserver(
921 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
922 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700923 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
924 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800925 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800926
927 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
929 mSystemInstallObserver = new AppDirObserver(
930 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
931 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700932 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
933 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800934
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700935 // Collect all vendor packages.
936 mVendorAppDir = new File("/vendor/app");
937 mVendorInstallObserver = new AppDirObserver(
938 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
939 mVendorInstallObserver.startWatching();
940 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
941 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
942
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800943 if (mInstaller != null) {
944 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
945 mInstaller.moveFiles();
946 }
947
948 // Prune any system packages that no longer exist.
949 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
950 while (psit.hasNext()) {
951 PackageSetting ps = psit.next();
952 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800953 && !mPackages.containsKey(ps.name)
954 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800955 psit.remove();
956 String msg = "System package " + ps.name
957 + " no longer exists; wiping its data";
958 reportSettingsProblem(Log.WARN, msg);
959 if (mInstaller != null) {
960 // XXX how to set useEncryptedFSDir for packages that
961 // are not encrypted?
962 mInstaller.remove(ps.name, true);
963 }
964 }
965 }
966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 mAppInstallDir = new File(dataDir, "app");
968 if (mInstaller == null) {
969 // Make sure these dirs exist, when we are running in
970 // the simulator.
971 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
972 }
973 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800974 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 //clean up list
976 for(int i = 0; i < deletePkgsList.size(); i++) {
977 //clean up here
978 cleanupInstallFailedPackage(deletePkgsList.get(i));
979 }
980 //delete tmp files
981 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982
983 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 SystemClock.uptimeMillis());
985 mAppInstallObserver = new AppDirObserver(
986 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
987 mAppInstallObserver.startWatching();
988 scanDirLI(mAppInstallDir, 0, scanMode);
989
990 mDrmAppInstallObserver = new AppDirObserver(
991 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
992 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800993 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800995 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800997 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 + ((SystemClock.uptimeMillis()-startTime)/1000f)
999 + " seconds");
1000
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001001 // If the platform SDK has changed since the last time we booted,
1002 // we need to re-grant app permission to catch any new ones that
1003 // appear. This is really a hack, and means that apps can in some
1004 // cases get permissions that the user didn't initially explicitly
1005 // allow... it would be nice to have some better way to handle
1006 // this situation.
1007 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1008 != mSdkVersion;
1009 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1010 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1011 + "; regranting permissions for internal storage");
1012 mSettings.mInternalSdkPlatform = mSdkVersion;
1013
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001014 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015
1016 mSettings.writeLP();
1017
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001018 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 // Now after opening every single application zip, make sure they
1022 // are all flushed. Not really needed, but keeps things nice and
1023 // tidy.
1024 Runtime.getRuntime().gc();
1025 } // synchronized (mPackages)
1026 } // synchronized (mInstallLock)
1027 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 @Override
1030 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1031 throws RemoteException {
1032 try {
1033 return super.onTransact(code, data, reply, flags);
1034 } catch (RuntimeException e) {
1035 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001036 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038 throw e;
1039 }
1040 }
1041
Dianne Hackborne6620b22010-01-22 14:46:21 -08001042 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001043 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001045 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1046 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001048 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001049 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051 } else {
1052 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001053 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 File dataDir = new File(pkg.applicationInfo.dataDir);
1055 dataDir.delete();
1056 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001057 if (ps.codePath != null) {
1058 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001059 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001060 }
1061 }
1062 if (ps.resourcePath != null) {
1063 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001064 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001065 }
1066 }
1067 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069
1070 void readPermissions() {
1071 // Read permissions from .../etc/permission directory.
1072 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1073 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001074 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 return;
1076 }
1077 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001078 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 return;
1080 }
1081
1082 // Iterate over the files in the directory and scan .xml files
1083 for (File f : libraryDir.listFiles()) {
1084 // We'll read platform.xml last
1085 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1086 continue;
1087 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001090 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 continue;
1092 }
1093 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001094 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 continue;
1096 }
1097
1098 readPermissionsFromXml(f);
1099 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1102 final File permFile = new File(Environment.getRootDirectory(),
1103 "etc/permissions/platform.xml");
1104 readPermissionsFromXml(permFile);
1105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001106
1107 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 FileReader permReader = null;
1109 try {
1110 permReader = new FileReader(permFile);
1111 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001112 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 return;
1114 }
1115
1116 try {
1117 XmlPullParser parser = Xml.newPullParser();
1118 parser.setInput(permReader);
1119
1120 XmlUtils.beginDocument(parser, "permissions");
1121
1122 while (true) {
1123 XmlUtils.nextElement(parser);
1124 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1125 break;
1126 }
1127
1128 String name = parser.getName();
1129 if ("group".equals(name)) {
1130 String gidStr = parser.getAttributeValue(null, "gid");
1131 if (gidStr != null) {
1132 int gid = Integer.parseInt(gidStr);
1133 mGlobalGids = appendInt(mGlobalGids, gid);
1134 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001135 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 + parser.getPositionDescription());
1137 }
1138
1139 XmlUtils.skipCurrentTag(parser);
1140 continue;
1141 } else if ("permission".equals(name)) {
1142 String perm = parser.getAttributeValue(null, "name");
1143 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001144 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 + parser.getPositionDescription());
1146 XmlUtils.skipCurrentTag(parser);
1147 continue;
1148 }
1149 perm = perm.intern();
1150 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 } else if ("assign-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, "<assign-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 String uidStr = parser.getAttributeValue(null, "uid");
1161 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001162 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 + parser.getPositionDescription());
1164 XmlUtils.skipCurrentTag(parser);
1165 continue;
1166 }
1167 int uid = Process.getUidForName(uidStr);
1168 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001169 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 + uidStr + "\" at "
1171 + parser.getPositionDescription());
1172 XmlUtils.skipCurrentTag(parser);
1173 continue;
1174 }
1175 perm = perm.intern();
1176 HashSet<String> perms = mSystemPermissions.get(uid);
1177 if (perms == null) {
1178 perms = new HashSet<String>();
1179 mSystemPermissions.put(uid, perms);
1180 }
1181 perms.add(perm);
1182 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 } else if ("library".equals(name)) {
1185 String lname = parser.getAttributeValue(null, "name");
1186 String lfile = parser.getAttributeValue(null, "file");
1187 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001188 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 + parser.getPositionDescription());
1190 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001191 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 + parser.getPositionDescription());
1193 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001194 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001195 mSharedLibraries.put(lname, lfile);
1196 }
1197 XmlUtils.skipCurrentTag(parser);
1198 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001199
Dianne Hackborn49237342009-08-27 20:08:01 -07001200 } else if ("feature".equals(name)) {
1201 String fname = parser.getAttributeValue(null, "name");
1202 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001203 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001204 + parser.getPositionDescription());
1205 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001206 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001207 FeatureInfo fi = new FeatureInfo();
1208 fi.name = fname;
1209 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211 XmlUtils.skipCurrentTag(parser);
1212 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 } else {
1215 XmlUtils.skipCurrentTag(parser);
1216 continue;
1217 }
1218
1219 }
1220 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001221 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001223 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
1225 }
1226
1227 void readPermission(XmlPullParser parser, String name)
1228 throws IOException, XmlPullParserException {
1229
1230 name = name.intern();
1231
1232 BasePermission bp = mSettings.mPermissions.get(name);
1233 if (bp == null) {
1234 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1235 mSettings.mPermissions.put(name, bp);
1236 }
1237 int outerDepth = parser.getDepth();
1238 int type;
1239 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1240 && (type != XmlPullParser.END_TAG
1241 || parser.getDepth() > outerDepth)) {
1242 if (type == XmlPullParser.END_TAG
1243 || type == XmlPullParser.TEXT) {
1244 continue;
1245 }
1246
1247 String tagName = parser.getName();
1248 if ("group".equals(tagName)) {
1249 String gidStr = parser.getAttributeValue(null, "gid");
1250 if (gidStr != null) {
1251 int gid = Process.getGidForName(gidStr);
1252 bp.gids = appendInt(bp.gids, gid);
1253 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001254 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 + parser.getPositionDescription());
1256 }
1257 }
1258 XmlUtils.skipCurrentTag(parser);
1259 }
1260 }
1261
1262 static int[] appendInt(int[] cur, int val) {
1263 if (cur == null) {
1264 return new int[] { val };
1265 }
1266 final int N = cur.length;
1267 for (int i=0; i<N; i++) {
1268 if (cur[i] == val) {
1269 return cur;
1270 }
1271 }
1272 int[] ret = new int[N+1];
1273 System.arraycopy(cur, 0, ret, 0, N);
1274 ret[N] = val;
1275 return ret;
1276 }
1277
1278 static int[] appendInts(int[] cur, int[] add) {
1279 if (add == null) return cur;
1280 if (cur == null) return add;
1281 final int N = add.length;
1282 for (int i=0; i<N; i++) {
1283 cur = appendInt(cur, add[i]);
1284 }
1285 return cur;
1286 }
1287
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001288 static int[] removeInt(int[] cur, int val) {
1289 if (cur == null) {
1290 return null;
1291 }
1292 final int N = cur.length;
1293 for (int i=0; i<N; i++) {
1294 if (cur[i] == val) {
1295 int[] ret = new int[N-1];
1296 if (i > 0) {
1297 System.arraycopy(cur, 0, ret, 0, i);
1298 }
1299 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001300 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001301 }
1302 return ret;
1303 }
1304 }
1305 return cur;
1306 }
1307
1308 static int[] removeInts(int[] cur, int[] rem) {
1309 if (rem == null) return cur;
1310 if (cur == null) return cur;
1311 final int N = rem.length;
1312 for (int i=0; i<N; i++) {
1313 cur = removeInt(cur, rem[i]);
1314 }
1315 return cur;
1316 }
1317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001319 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1320 // The package has been uninstalled but has retained data and resources.
1321 return PackageParser.generatePackageInfo(p, null, flags);
1322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 final PackageSetting ps = (PackageSetting)p.mExtras;
1324 if (ps == null) {
1325 return null;
1326 }
1327 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1328 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1329 }
1330
1331 public PackageInfo getPackageInfo(String packageName, int flags) {
1332 synchronized (mPackages) {
1333 PackageParser.Package p = mPackages.get(packageName);
1334 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001335 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 + ": " + p);
1337 if (p != null) {
1338 return generatePackageInfo(p, flags);
1339 }
1340 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1341 return generatePackageInfoFromSettingsLP(packageName, flags);
1342 }
1343 }
1344 return null;
1345 }
1346
Dianne Hackborn47096932010-02-11 15:57:09 -08001347 public String[] currentToCanonicalPackageNames(String[] names) {
1348 String[] out = new String[names.length];
1349 synchronized (mPackages) {
1350 for (int i=names.length-1; i>=0; i--) {
1351 PackageSetting ps = mSettings.mPackages.get(names[i]);
1352 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1353 }
1354 }
1355 return out;
1356 }
1357
1358 public String[] canonicalToCurrentPackageNames(String[] names) {
1359 String[] out = new String[names.length];
1360 synchronized (mPackages) {
1361 for (int i=names.length-1; i>=0; i--) {
1362 String cur = mSettings.mRenamedPackages.get(names[i]);
1363 out[i] = cur != null ? cur : names[i];
1364 }
1365 }
1366 return out;
1367 }
1368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 public int getPackageUid(String packageName) {
1370 synchronized (mPackages) {
1371 PackageParser.Package p = mPackages.get(packageName);
1372 if(p != null) {
1373 return p.applicationInfo.uid;
1374 }
1375 PackageSetting ps = mSettings.mPackages.get(packageName);
1376 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1377 return -1;
1378 }
1379 p = ps.pkg;
1380 return p != null ? p.applicationInfo.uid : -1;
1381 }
1382 }
1383
1384 public int[] getPackageGids(String packageName) {
1385 synchronized (mPackages) {
1386 PackageParser.Package p = mPackages.get(packageName);
1387 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001388 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 + ": " + p);
1390 if (p != null) {
1391 final PackageSetting ps = (PackageSetting)p.mExtras;
1392 final SharedUserSetting suid = ps.sharedUser;
1393 return suid != null ? suid.gids : ps.gids;
1394 }
1395 }
1396 // stupid thing to indicate an error.
1397 return new int[0];
1398 }
1399
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001400 static final PermissionInfo generatePermissionInfo(
1401 BasePermission bp, int flags) {
1402 if (bp.perm != null) {
1403 return PackageParser.generatePermissionInfo(bp.perm, flags);
1404 }
1405 PermissionInfo pi = new PermissionInfo();
1406 pi.name = bp.name;
1407 pi.packageName = bp.sourcePackage;
1408 pi.nonLocalizedLabel = bp.name;
1409 pi.protectionLevel = bp.protectionLevel;
1410 return pi;
1411 }
1412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 public PermissionInfo getPermissionInfo(String name, int flags) {
1414 synchronized (mPackages) {
1415 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001416 if (p != null) {
1417 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419 return null;
1420 }
1421 }
1422
1423 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1424 synchronized (mPackages) {
1425 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1426 for (BasePermission p : mSettings.mPermissions.values()) {
1427 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001428 if (p.perm == null || p.perm.info.group == null) {
1429 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 }
1431 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001432 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1434 }
1435 }
1436 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 if (out.size() > 0) {
1439 return out;
1440 }
1441 return mPermissionGroups.containsKey(group) ? out : null;
1442 }
1443 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1446 synchronized (mPackages) {
1447 return PackageParser.generatePermissionGroupInfo(
1448 mPermissionGroups.get(name), flags);
1449 }
1450 }
1451
1452 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1453 synchronized (mPackages) {
1454 final int N = mPermissionGroups.size();
1455 ArrayList<PermissionGroupInfo> out
1456 = new ArrayList<PermissionGroupInfo>(N);
1457 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1458 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1459 }
1460 return out;
1461 }
1462 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1465 PackageSetting ps = mSettings.mPackages.get(packageName);
1466 if(ps != null) {
1467 if(ps.pkg == null) {
1468 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1469 if(pInfo != null) {
1470 return pInfo.applicationInfo;
1471 }
1472 return null;
1473 }
1474 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1475 }
1476 return null;
1477 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1480 PackageSetting ps = mSettings.mPackages.get(packageName);
1481 if(ps != null) {
1482 if(ps.pkg == null) {
1483 ps.pkg = new PackageParser.Package(packageName);
1484 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001485 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1486 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1487 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1488 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001489 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001490 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492 return generatePackageInfo(ps.pkg, flags);
1493 }
1494 return null;
1495 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1498 synchronized (mPackages) {
1499 PackageParser.Package p = mPackages.get(packageName);
1500 if (Config.LOGV) Log.v(
1501 TAG, "getApplicationInfo " + packageName
1502 + ": " + p);
1503 if (p != null) {
1504 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001505 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507 if ("android".equals(packageName)||"system".equals(packageName)) {
1508 return mAndroidApplication;
1509 }
1510 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1511 return generateApplicationInfoFromSettingsLP(packageName, flags);
1512 }
1513 }
1514 return null;
1515 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001516
1517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1519 mContext.enforceCallingOrSelfPermission(
1520 android.Manifest.permission.CLEAR_APP_CACHE, null);
1521 // Queue up an async operation since clearing cache may take a little while.
1522 mHandler.post(new Runnable() {
1523 public void run() {
1524 mHandler.removeCallbacks(this);
1525 int retCode = -1;
1526 if (mInstaller != null) {
1527 retCode = mInstaller.freeCache(freeStorageSize);
1528 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001529 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
1531 } //end if mInstaller
1532 if (observer != null) {
1533 try {
1534 observer.onRemoveCompleted(null, (retCode >= 0));
1535 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001536 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538 }
1539 }
1540 });
1541 }
1542
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001543 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001544 mContext.enforceCallingOrSelfPermission(
1545 android.Manifest.permission.CLEAR_APP_CACHE, null);
1546 // Queue up an async operation since clearing cache may take a little while.
1547 mHandler.post(new Runnable() {
1548 public void run() {
1549 mHandler.removeCallbacks(this);
1550 int retCode = -1;
1551 if (mInstaller != null) {
1552 retCode = mInstaller.freeCache(freeStorageSize);
1553 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001554 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001555 }
1556 }
1557 if(pi != null) {
1558 try {
1559 // Callback via pending intent
1560 int code = (retCode >= 0) ? 1 : 0;
1561 pi.sendIntent(null, code, null,
1562 null, null);
1563 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001564 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001565 }
1566 }
1567 }
1568 });
1569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1572 synchronized (mPackages) {
1573 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001574
1575 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001577 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
1579 if (mResolveComponentName.equals(component)) {
1580 return mResolveActivity;
1581 }
1582 }
1583 return null;
1584 }
1585
1586 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1587 synchronized (mPackages) {
1588 PackageParser.Activity a = mReceivers.mActivities.get(component);
1589 if (Config.LOGV) Log.v(
1590 TAG, "getReceiverInfo " + component + ": " + a);
1591 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1592 return PackageParser.generateActivityInfo(a, flags);
1593 }
1594 }
1595 return null;
1596 }
1597
1598 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1599 synchronized (mPackages) {
1600 PackageParser.Service s = mServices.mServices.get(component);
1601 if (Config.LOGV) Log.v(
1602 TAG, "getServiceInfo " + component + ": " + s);
1603 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1604 return PackageParser.generateServiceInfo(s, flags);
1605 }
1606 }
1607 return null;
1608 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001609
Dianne Hackborn361199b2010-08-30 17:42:07 -07001610 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1611 synchronized (mPackages) {
1612 PackageParser.Provider p = mProvidersByComponent.get(component);
1613 if (Config.LOGV) Log.v(
1614 TAG, "getProviderInfo " + component + ": " + p);
1615 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1616 return PackageParser.generateProviderInfo(p, flags);
1617 }
1618 }
1619 return null;
1620 }
1621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 public String[] getSystemSharedLibraryNames() {
1623 Set<String> libSet;
1624 synchronized (mPackages) {
1625 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001626 int size = libSet.size();
1627 if (size > 0) {
1628 String[] libs = new String[size];
1629 libSet.toArray(libs);
1630 return libs;
1631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001633 return null;
1634 }
1635
1636 public FeatureInfo[] getSystemAvailableFeatures() {
1637 Collection<FeatureInfo> featSet;
1638 synchronized (mPackages) {
1639 featSet = mAvailableFeatures.values();
1640 int size = featSet.size();
1641 if (size > 0) {
1642 FeatureInfo[] features = new FeatureInfo[size+1];
1643 featSet.toArray(features);
1644 FeatureInfo fi = new FeatureInfo();
1645 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1646 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1647 features[size] = fi;
1648 return features;
1649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
1651 return null;
1652 }
1653
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001654 public boolean hasSystemFeature(String name) {
1655 synchronized (mPackages) {
1656 return mAvailableFeatures.containsKey(name);
1657 }
1658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 public int checkPermission(String permName, String pkgName) {
1661 synchronized (mPackages) {
1662 PackageParser.Package p = mPackages.get(pkgName);
1663 if (p != null && p.mExtras != null) {
1664 PackageSetting ps = (PackageSetting)p.mExtras;
1665 if (ps.sharedUser != null) {
1666 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1667 return PackageManager.PERMISSION_GRANTED;
1668 }
1669 } else if (ps.grantedPermissions.contains(permName)) {
1670 return PackageManager.PERMISSION_GRANTED;
1671 }
1672 }
1673 }
1674 return PackageManager.PERMISSION_DENIED;
1675 }
1676
1677 public int checkUidPermission(String permName, int uid) {
1678 synchronized (mPackages) {
1679 Object obj = mSettings.getUserIdLP(uid);
1680 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001681 GrantedPermissions gp = (GrantedPermissions)obj;
1682 if (gp.grantedPermissions.contains(permName)) {
1683 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
1685 } else {
1686 HashSet<String> perms = mSystemPermissions.get(uid);
1687 if (perms != null && perms.contains(permName)) {
1688 return PackageManager.PERMISSION_GRANTED;
1689 }
1690 }
1691 }
1692 return PackageManager.PERMISSION_DENIED;
1693 }
1694
1695 private BasePermission findPermissionTreeLP(String permName) {
1696 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1697 if (permName.startsWith(bp.name) &&
1698 permName.length() > bp.name.length() &&
1699 permName.charAt(bp.name.length()) == '.') {
1700 return bp;
1701 }
1702 }
1703 return null;
1704 }
1705
1706 private BasePermission checkPermissionTreeLP(String permName) {
1707 if (permName != null) {
1708 BasePermission bp = findPermissionTreeLP(permName);
1709 if (bp != null) {
1710 if (bp.uid == Binder.getCallingUid()) {
1711 return bp;
1712 }
1713 throw new SecurityException("Calling uid "
1714 + Binder.getCallingUid()
1715 + " is not allowed to add to permission tree "
1716 + bp.name + " owned by uid " + bp.uid);
1717 }
1718 }
1719 throw new SecurityException("No permission tree found for " + permName);
1720 }
1721
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001722 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1723 if (s1 == null) {
1724 return s2 == null;
1725 }
1726 if (s2 == null) {
1727 return false;
1728 }
1729 if (s1.getClass() != s2.getClass()) {
1730 return false;
1731 }
1732 return s1.equals(s2);
1733 }
1734
1735 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1736 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001737 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001738 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1739 if (!compareStrings(pi1.name, pi2.name)) return false;
1740 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1741 // We'll take care of setting this one.
1742 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1743 // These are not currently stored in settings.
1744 //if (!compareStrings(pi1.group, pi2.group)) return false;
1745 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1746 //if (pi1.labelRes != pi2.labelRes) return false;
1747 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1748 return true;
1749 }
1750
1751 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1752 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1753 throw new SecurityException("Label must be specified in permission");
1754 }
1755 BasePermission tree = checkPermissionTreeLP(info.name);
1756 BasePermission bp = mSettings.mPermissions.get(info.name);
1757 boolean added = bp == null;
1758 boolean changed = true;
1759 if (added) {
1760 bp = new BasePermission(info.name, tree.sourcePackage,
1761 BasePermission.TYPE_DYNAMIC);
1762 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1763 throw new SecurityException(
1764 "Not allowed to modify non-dynamic permission "
1765 + info.name);
1766 } else {
1767 if (bp.protectionLevel == info.protectionLevel
1768 && bp.perm.owner.equals(tree.perm.owner)
1769 && bp.uid == tree.uid
1770 && comparePermissionInfos(bp.perm.info, info)) {
1771 changed = false;
1772 }
1773 }
1774 bp.protectionLevel = info.protectionLevel;
1775 bp.perm = new PackageParser.Permission(tree.perm.owner,
1776 new PermissionInfo(info));
1777 bp.perm.info.packageName = tree.perm.info.packageName;
1778 bp.uid = tree.uid;
1779 if (added) {
1780 mSettings.mPermissions.put(info.name, bp);
1781 }
1782 if (changed) {
1783 if (!async) {
1784 mSettings.writeLP();
1785 } else {
1786 scheduleWriteSettingsLocked();
1787 }
1788 }
1789 return added;
1790 }
1791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 public boolean addPermission(PermissionInfo info) {
1793 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001794 return addPermissionLocked(info, false);
1795 }
1796 }
1797
1798 public boolean addPermissionAsync(PermissionInfo info) {
1799 synchronized (mPackages) {
1800 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 }
1802 }
1803
1804 public void removePermission(String name) {
1805 synchronized (mPackages) {
1806 checkPermissionTreeLP(name);
1807 BasePermission bp = mSettings.mPermissions.get(name);
1808 if (bp != null) {
1809 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1810 throw new SecurityException(
1811 "Not allowed to modify non-dynamic permission "
1812 + name);
1813 }
1814 mSettings.mPermissions.remove(name);
1815 mSettings.writeLP();
1816 }
1817 }
1818 }
1819
Dianne Hackborn854060af2009-07-09 18:14:31 -07001820 public boolean isProtectedBroadcast(String actionName) {
1821 synchronized (mPackages) {
1822 return mProtectedBroadcasts.contains(actionName);
1823 }
1824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 public int checkSignatures(String pkg1, String pkg2) {
1827 synchronized (mPackages) {
1828 PackageParser.Package p1 = mPackages.get(pkg1);
1829 PackageParser.Package p2 = mPackages.get(pkg2);
1830 if (p1 == null || p1.mExtras == null
1831 || p2 == null || p2.mExtras == null) {
1832 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1833 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001834 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836 }
1837
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001838 public int checkUidSignatures(int uid1, int uid2) {
1839 synchronized (mPackages) {
1840 Signature[] s1;
1841 Signature[] s2;
1842 Object obj = mSettings.getUserIdLP(uid1);
1843 if (obj != null) {
1844 if (obj instanceof SharedUserSetting) {
1845 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1846 } else if (obj instanceof PackageSetting) {
1847 s1 = ((PackageSetting)obj).signatures.mSignatures;
1848 } else {
1849 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1850 }
1851 } else {
1852 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1853 }
1854 obj = mSettings.getUserIdLP(uid2);
1855 if (obj != null) {
1856 if (obj instanceof SharedUserSetting) {
1857 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1858 } else if (obj instanceof PackageSetting) {
1859 s2 = ((PackageSetting)obj).signatures.mSignatures;
1860 } else {
1861 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1862 }
1863 } else {
1864 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1865 }
1866 return checkSignaturesLP(s1, s2);
1867 }
1868 }
1869
1870 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1871 if (s1 == null) {
1872 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1874 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1875 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001876 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1878 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001879 HashSet<Signature> set1 = new HashSet<Signature>();
1880 for (Signature sig : s1) {
1881 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001883 HashSet<Signature> set2 = new HashSet<Signature>();
1884 for (Signature sig : s2) {
1885 set2.add(sig);
1886 }
1887 // Make sure s2 contains all signatures in s1.
1888 if (set1.equals(set2)) {
1889 return PackageManager.SIGNATURE_MATCH;
1890 }
1891 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893
1894 public String[] getPackagesForUid(int uid) {
1895 synchronized (mPackages) {
1896 Object obj = mSettings.getUserIdLP(uid);
1897 if (obj instanceof SharedUserSetting) {
1898 SharedUserSetting sus = (SharedUserSetting)obj;
1899 final int N = sus.packages.size();
1900 String[] res = new String[N];
1901 Iterator<PackageSetting> it = sus.packages.iterator();
1902 int i=0;
1903 while (it.hasNext()) {
1904 res[i++] = it.next().name;
1905 }
1906 return res;
1907 } else if (obj instanceof PackageSetting) {
1908 PackageSetting ps = (PackageSetting)obj;
1909 return new String[] { ps.name };
1910 }
1911 }
1912 return null;
1913 }
1914
1915 public String getNameForUid(int uid) {
1916 synchronized (mPackages) {
1917 Object obj = mSettings.getUserIdLP(uid);
1918 if (obj instanceof SharedUserSetting) {
1919 SharedUserSetting sus = (SharedUserSetting)obj;
1920 return sus.name + ":" + sus.userId;
1921 } else if (obj instanceof PackageSetting) {
1922 PackageSetting ps = (PackageSetting)obj;
1923 return ps.name;
1924 }
1925 }
1926 return null;
1927 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 public int getUidForSharedUser(String sharedUserName) {
1930 if(sharedUserName == null) {
1931 return -1;
1932 }
1933 synchronized (mPackages) {
1934 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1935 if(suid == null) {
1936 return -1;
1937 }
1938 return suid.userId;
1939 }
1940 }
1941
1942 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1943 int flags) {
1944 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001945 return chooseBestActivity(intent, resolvedType, flags, query);
1946 }
1947
Mihai Predaeae850c2009-05-13 10:13:48 +02001948 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1949 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 if (query != null) {
1951 final int N = query.size();
1952 if (N == 1) {
1953 return query.get(0);
1954 } else if (N > 1) {
1955 // If there is more than one activity with the same priority,
1956 // then let the user decide between them.
1957 ResolveInfo r0 = query.get(0);
1958 ResolveInfo r1 = query.get(1);
1959 if (false) {
1960 System.out.println(r0.activityInfo.name +
1961 "=" + r0.priority + " vs " +
1962 r1.activityInfo.name +
1963 "=" + r1.priority);
1964 }
1965 // If the first activity has a higher priority, or a different
1966 // default, then it is always desireable to pick it.
1967 if (r0.priority != r1.priority
1968 || r0.preferredOrder != r1.preferredOrder
1969 || r0.isDefault != r1.isDefault) {
1970 return query.get(0);
1971 }
1972 // If we have saved a preference for a preferred activity for
1973 // this Intent, use that.
1974 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1975 flags, query, r0.priority);
1976 if (ri != null) {
1977 return ri;
1978 }
1979 return mResolveInfo;
1980 }
1981 }
1982 return null;
1983 }
1984
1985 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1986 int flags, List<ResolveInfo> query, int priority) {
1987 synchronized (mPackages) {
1988 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1989 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001990 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1992 if (prefs != null && prefs.size() > 0) {
1993 // First figure out how good the original match set is.
1994 // We will only allow preferred activities that came
1995 // from the same match quality.
1996 int match = 0;
1997 final int N = query.size();
1998 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1999 for (int j=0; j<N; j++) {
2000 ResolveInfo ri = query.get(j);
2001 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2002 + ": 0x" + Integer.toHexString(match));
2003 if (ri.match > match) match = ri.match;
2004 }
2005 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2006 + Integer.toHexString(match));
2007 match &= IntentFilter.MATCH_CATEGORY_MASK;
2008 final int M = prefs.size();
2009 for (int i=0; i<M; i++) {
2010 PreferredActivity pa = prefs.get(i);
2011 if (pa.mMatch != match) {
2012 continue;
2013 }
2014 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2015 if (DEBUG_PREFERRED) {
2016 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002017 if (ai != null) {
2018 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2019 } else {
2020 Log.v(TAG, " null");
2021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 }
2023 if (ai != null) {
2024 for (int j=0; j<N; j++) {
2025 ResolveInfo ri = query.get(j);
2026 if (!ri.activityInfo.applicationInfo.packageName
2027 .equals(ai.applicationInfo.packageName)) {
2028 continue;
2029 }
2030 if (!ri.activityInfo.name.equals(ai.name)) {
2031 continue;
2032 }
2033
2034 // Okay we found a previously set preferred app.
2035 // If the result set is different from when this
2036 // was created, we need to clear it and re-ask the
2037 // user their preference.
2038 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002039 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 + intent + " type " + resolvedType);
2041 mSettings.mPreferredActivities.removeFilter(pa);
2042 return null;
2043 }
2044
2045 // Yay!
2046 return ri;
2047 }
2048 }
2049 }
2050 }
2051 }
2052 return null;
2053 }
2054
2055 public List<ResolveInfo> queryIntentActivities(Intent intent,
2056 String resolvedType, int flags) {
2057 ComponentName comp = intent.getComponent();
2058 if (comp != null) {
2059 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2060 ActivityInfo ai = getActivityInfo(comp, flags);
2061 if (ai != null) {
2062 ResolveInfo ri = new ResolveInfo();
2063 ri.activityInfo = ai;
2064 list.add(ri);
2065 }
2066 return list;
2067 }
2068
2069 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002070 String pkgName = intent.getPackage();
2071 if (pkgName == null) {
2072 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2073 resolvedType, flags);
2074 }
2075 PackageParser.Package pkg = mPackages.get(pkgName);
2076 if (pkg != null) {
2077 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2078 resolvedType, flags, pkg.activities);
2079 }
2080 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 }
2082 }
2083
2084 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2085 Intent[] specifics, String[] specificTypes, Intent intent,
2086 String resolvedType, int flags) {
2087 final String resultsAction = intent.getAction();
2088
2089 List<ResolveInfo> results = queryIntentActivities(
2090 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2091 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2092
2093 int specificsPos = 0;
2094 int N;
2095
2096 // todo: note that the algorithm used here is O(N^2). This
2097 // isn't a problem in our current environment, but if we start running
2098 // into situations where we have more than 5 or 10 matches then this
2099 // should probably be changed to something smarter...
2100
2101 // First we go through and resolve each of the specific items
2102 // that were supplied, taking care of removing any corresponding
2103 // duplicate items in the generic resolve list.
2104 if (specifics != null) {
2105 for (int i=0; i<specifics.length; i++) {
2106 final Intent sintent = specifics[i];
2107 if (sintent == null) {
2108 continue;
2109 }
2110
2111 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2112 String action = sintent.getAction();
2113 if (resultsAction != null && resultsAction.equals(action)) {
2114 // If this action was explicitly requested, then don't
2115 // remove things that have it.
2116 action = null;
2117 }
2118 ComponentName comp = sintent.getComponent();
2119 ResolveInfo ri = null;
2120 ActivityInfo ai = null;
2121 if (comp == null) {
2122 ri = resolveIntent(
2123 sintent,
2124 specificTypes != null ? specificTypes[i] : null,
2125 flags);
2126 if (ri == null) {
2127 continue;
2128 }
2129 if (ri == mResolveInfo) {
2130 // ACK! Must do something better with this.
2131 }
2132 ai = ri.activityInfo;
2133 comp = new ComponentName(ai.applicationInfo.packageName,
2134 ai.name);
2135 } else {
2136 ai = getActivityInfo(comp, flags);
2137 if (ai == null) {
2138 continue;
2139 }
2140 }
2141
2142 // Look for any generic query activities that are duplicates
2143 // of this specific one, and remove them from the results.
2144 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2145 N = results.size();
2146 int j;
2147 for (j=specificsPos; j<N; j++) {
2148 ResolveInfo sri = results.get(j);
2149 if ((sri.activityInfo.name.equals(comp.getClassName())
2150 && sri.activityInfo.applicationInfo.packageName.equals(
2151 comp.getPackageName()))
2152 || (action != null && sri.filter.matchAction(action))) {
2153 results.remove(j);
2154 if (Config.LOGV) Log.v(
2155 TAG, "Removing duplicate item from " + j
2156 + " due to specific " + specificsPos);
2157 if (ri == null) {
2158 ri = sri;
2159 }
2160 j--;
2161 N--;
2162 }
2163 }
2164
2165 // Add this specific item to its proper place.
2166 if (ri == null) {
2167 ri = new ResolveInfo();
2168 ri.activityInfo = ai;
2169 }
2170 results.add(specificsPos, ri);
2171 ri.specificIndex = i;
2172 specificsPos++;
2173 }
2174 }
2175
2176 // Now we go through the remaining generic results and remove any
2177 // duplicate actions that are found here.
2178 N = results.size();
2179 for (int i=specificsPos; i<N-1; i++) {
2180 final ResolveInfo rii = results.get(i);
2181 if (rii.filter == null) {
2182 continue;
2183 }
2184
2185 // Iterate over all of the actions of this result's intent
2186 // filter... typically this should be just one.
2187 final Iterator<String> it = rii.filter.actionsIterator();
2188 if (it == null) {
2189 continue;
2190 }
2191 while (it.hasNext()) {
2192 final String action = it.next();
2193 if (resultsAction != null && resultsAction.equals(action)) {
2194 // If this action was explicitly requested, then don't
2195 // remove things that have it.
2196 continue;
2197 }
2198 for (int j=i+1; j<N; j++) {
2199 final ResolveInfo rij = results.get(j);
2200 if (rij.filter != null && rij.filter.hasAction(action)) {
2201 results.remove(j);
2202 if (Config.LOGV) Log.v(
2203 TAG, "Removing duplicate item from " + j
2204 + " due to action " + action + " at " + i);
2205 j--;
2206 N--;
2207 }
2208 }
2209 }
2210
2211 // If the caller didn't request filter information, drop it now
2212 // so we don't have to marshall/unmarshall it.
2213 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2214 rii.filter = null;
2215 }
2216 }
2217
2218 // Filter out the caller activity if so requested.
2219 if (caller != null) {
2220 N = results.size();
2221 for (int i=0; i<N; i++) {
2222 ActivityInfo ainfo = results.get(i).activityInfo;
2223 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2224 && caller.getClassName().equals(ainfo.name)) {
2225 results.remove(i);
2226 break;
2227 }
2228 }
2229 }
2230
2231 // If the caller didn't request filter information,
2232 // drop them now so we don't have to
2233 // marshall/unmarshall it.
2234 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2235 N = results.size();
2236 for (int i=0; i<N; i++) {
2237 results.get(i).filter = null;
2238 }
2239 }
2240
2241 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2242 return results;
2243 }
2244
2245 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2246 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002247 ComponentName comp = intent.getComponent();
2248 if (comp != null) {
2249 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2250 ActivityInfo ai = getReceiverInfo(comp, flags);
2251 if (ai != null) {
2252 ResolveInfo ri = new ResolveInfo();
2253 ri.activityInfo = ai;
2254 list.add(ri);
2255 }
2256 return list;
2257 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002260 String pkgName = intent.getPackage();
2261 if (pkgName == null) {
2262 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2263 resolvedType, flags);
2264 }
2265 PackageParser.Package pkg = mPackages.get(pkgName);
2266 if (pkg != null) {
2267 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2268 resolvedType, flags, pkg.receivers);
2269 }
2270 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 }
2272 }
2273
2274 public ResolveInfo resolveService(Intent intent, String resolvedType,
2275 int flags) {
2276 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2277 flags);
2278 if (query != null) {
2279 if (query.size() >= 1) {
2280 // If there is more than one service with the same priority,
2281 // just arbitrarily pick the first one.
2282 return query.get(0);
2283 }
2284 }
2285 return null;
2286 }
2287
2288 public List<ResolveInfo> queryIntentServices(Intent intent,
2289 String resolvedType, int flags) {
2290 ComponentName comp = intent.getComponent();
2291 if (comp != null) {
2292 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2293 ServiceInfo si = getServiceInfo(comp, flags);
2294 if (si != null) {
2295 ResolveInfo ri = new ResolveInfo();
2296 ri.serviceInfo = si;
2297 list.add(ri);
2298 }
2299 return list;
2300 }
2301
2302 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002303 String pkgName = intent.getPackage();
2304 if (pkgName == null) {
2305 return (List<ResolveInfo>)mServices.queryIntent(intent,
2306 resolvedType, flags);
2307 }
2308 PackageParser.Package pkg = mPackages.get(pkgName);
2309 if (pkg != null) {
2310 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2311 resolvedType, flags, pkg.services);
2312 }
2313 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 }
2315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 public List<PackageInfo> getInstalledPackages(int flags) {
2318 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2319
2320 synchronized (mPackages) {
2321 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2322 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2323 while (i.hasNext()) {
2324 final PackageSetting ps = i.next();
2325 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2326 if(psPkg != null) {
2327 finalList.add(psPkg);
2328 }
2329 }
2330 }
2331 else {
2332 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2333 while (i.hasNext()) {
2334 final PackageParser.Package p = i.next();
2335 if (p.applicationInfo != null) {
2336 PackageInfo pi = generatePackageInfo(p, flags);
2337 if(pi != null) {
2338 finalList.add(pi);
2339 }
2340 }
2341 }
2342 }
2343 }
2344 return finalList;
2345 }
2346
2347 public List<ApplicationInfo> getInstalledApplications(int flags) {
2348 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2349 synchronized(mPackages) {
2350 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2351 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2352 while (i.hasNext()) {
2353 final PackageSetting ps = i.next();
2354 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2355 if(ai != null) {
2356 finalList.add(ai);
2357 }
2358 }
2359 }
2360 else {
2361 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2362 while (i.hasNext()) {
2363 final PackageParser.Package p = i.next();
2364 if (p.applicationInfo != null) {
2365 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2366 if(ai != null) {
2367 finalList.add(ai);
2368 }
2369 }
2370 }
2371 }
2372 }
2373 return finalList;
2374 }
2375
2376 public List<ApplicationInfo> getPersistentApplications(int flags) {
2377 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2378
2379 synchronized (mPackages) {
2380 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2381 while (i.hasNext()) {
2382 PackageParser.Package p = i.next();
2383 if (p.applicationInfo != null
2384 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002385 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002386 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 }
2388 }
2389 }
2390
2391 return finalList;
2392 }
2393
2394 public ProviderInfo resolveContentProvider(String name, int flags) {
2395 synchronized (mPackages) {
2396 final PackageParser.Provider provider = mProviders.get(name);
2397 return provider != null
2398 && mSettings.isEnabledLP(provider.info, flags)
2399 && (!mSafeMode || (provider.info.applicationInfo.flags
2400 &ApplicationInfo.FLAG_SYSTEM) != 0)
2401 ? PackageParser.generateProviderInfo(provider, flags)
2402 : null;
2403 }
2404 }
2405
Fred Quintana718d8a22009-04-29 17:53:20 -07002406 /**
2407 * @deprecated
2408 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 public void querySyncProviders(List outNames, List outInfo) {
2410 synchronized (mPackages) {
2411 Iterator<Map.Entry<String, PackageParser.Provider>> i
2412 = mProviders.entrySet().iterator();
2413
2414 while (i.hasNext()) {
2415 Map.Entry<String, PackageParser.Provider> entry = i.next();
2416 PackageParser.Provider p = entry.getValue();
2417
2418 if (p.syncable
2419 && (!mSafeMode || (p.info.applicationInfo.flags
2420 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2421 outNames.add(entry.getKey());
2422 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2423 }
2424 }
2425 }
2426 }
2427
2428 public List<ProviderInfo> queryContentProviders(String processName,
2429 int uid, int flags) {
2430 ArrayList<ProviderInfo> finalList = null;
2431
2432 synchronized (mPackages) {
2433 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2434 while (i.hasNext()) {
2435 PackageParser.Provider p = i.next();
2436 if (p.info.authority != null
2437 && (processName == null ||
2438 (p.info.processName.equals(processName)
2439 && p.info.applicationInfo.uid == uid))
2440 && mSettings.isEnabledLP(p.info, flags)
2441 && (!mSafeMode || (p.info.applicationInfo.flags
2442 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2443 if (finalList == null) {
2444 finalList = new ArrayList<ProviderInfo>(3);
2445 }
2446 finalList.add(PackageParser.generateProviderInfo(p,
2447 flags));
2448 }
2449 }
2450 }
2451
2452 if (finalList != null) {
2453 Collections.sort(finalList, mProviderInitOrderSorter);
2454 }
2455
2456 return finalList;
2457 }
2458
2459 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2460 int flags) {
2461 synchronized (mPackages) {
2462 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2463 return PackageParser.generateInstrumentationInfo(i, flags);
2464 }
2465 }
2466
2467 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2468 int flags) {
2469 ArrayList<InstrumentationInfo> finalList =
2470 new ArrayList<InstrumentationInfo>();
2471
2472 synchronized (mPackages) {
2473 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2474 while (i.hasNext()) {
2475 PackageParser.Instrumentation p = i.next();
2476 if (targetPackage == null
2477 || targetPackage.equals(p.info.targetPackage)) {
2478 finalList.add(PackageParser.generateInstrumentationInfo(p,
2479 flags));
2480 }
2481 }
2482 }
2483
2484 return finalList;
2485 }
2486
2487 private void scanDirLI(File dir, int flags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002489 if (files == null) {
2490 Log.d(TAG, "No files in app dir " + dir);
2491 return;
2492 }
2493
2494 Log.d(TAG, "Scanning app dir " + dir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495
2496 int i;
2497 for (i=0; i<files.length; i++) {
2498 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002499 if (!isPackageFilename(files[i])) {
2500 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002501 continue;
2502 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002503 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002505 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002506 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2507 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002508 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002509 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002510 file.delete();
2511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 }
2513 }
2514
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002515 private static File getSettingsProblemFile() {
2516 File dataDir = Environment.getDataDirectory();
2517 File systemDir = new File(dataDir, "system");
2518 File fname = new File(systemDir, "uiderrors.txt");
2519 return fname;
2520 }
2521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 private static void reportSettingsProblem(int priority, String msg) {
2523 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002524 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 FileOutputStream out = new FileOutputStream(fname, true);
2526 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002527 SimpleDateFormat formatter = new SimpleDateFormat();
2528 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2529 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 pw.close();
2531 FileUtils.setPermissions(
2532 fname.toString(),
2533 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2534 -1, -1);
2535 } catch (java.io.IOException e) {
2536 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002537 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 }
2539
2540 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2541 PackageParser.Package pkg, File srcFile, int parseFlags) {
2542 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002543 if (ps != null
2544 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002545 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002546 if (ps.signatures.mSignatures != null
2547 && ps.signatures.mSignatures.length != 0) {
2548 // Optimization: reuse the existing cached certificates
2549 // if the package appears to be unchanged.
2550 pkg.mSignatures = ps.signatures.mSignatures;
2551 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 }
Jeff Browne7600722010-04-07 18:28:23 -07002553
2554 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002555 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002556 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2557 }
2558
2559 if (!pp.collectCertificates(pkg, parseFlags)) {
2560 mLastScanError = pp.getParseError();
2561 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 }
2563 }
2564 return true;
2565 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 /*
2568 * Scan a package and return the newly parsed package.
2569 * Returns null in case of errors and the error code is stored in mLastScanError
2570 */
2571 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002572 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002574 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002576 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002579 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 if (pkg == null) {
2581 mLastScanError = pp.getParseError();
2582 return null;
2583 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002584 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 PackageSetting updatedPkg;
2586 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002587 // Look to see if we already know about this package.
2588 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002589 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002590 // This package has been renamed to its original name. Let's
2591 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002592 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002593 }
2594 // If there was no original package, see one for the real package name.
2595 if (ps == null) {
2596 ps = mSettings.peekPackageLP(pkg.packageName);
2597 }
2598 // Check to see if this package could be hiding/updating a system
2599 // package. Must look for it either under the original or real
2600 // package name depending on our state.
2601 updatedPkg = mSettings.mDisabledSysPackages.get(
2602 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002604 // First check if this is a system package that may involve an update
2605 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002606 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002607 // The path has changed from what was last scanned... check the
2608 // version of the new path against what we have stored to determine
2609 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002610 if (pkg.mVersionCode < ps.versionCode) {
2611 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002612 // Ignore entry. Skip it.
2613 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002614 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002615 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002616 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2617 return null;
2618 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 // The current app on the system partion is better than
2620 // what we have updated to on the data partition; switch
2621 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002622 // At this point, its safely assumed that package installation for
2623 // apps in system partition will go through. If not there won't be a working
2624 // version of the app
2625 synchronized (mPackages) {
2626 // Just remove the loaded entries from package lists.
2627 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002628 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002629 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002630 + "reverting from " + ps.codePathString
2631 + ": new version " + pkg.mVersionCode
2632 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002633 InstallArgs args = new FileInstallArgs(ps.codePathString,
2634 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002635 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002636 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 }
2639 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002640 if (updatedPkg != null) {
2641 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2642 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2643 }
2644 // Verify certificates against what was last scanned
2645 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002646 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002647 return null;
2648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 // The apk is forward locked (not public) if its code and resources
2650 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002651 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002653 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002654 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002655
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002656 String codePath = null;
2657 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002658 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2659 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002660 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002661 } else {
2662 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002663 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002664 }
2665 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002666 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002667 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002668 codePath = pkg.mScanPath;
2669 // Set application objects path explicitly.
2670 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002672 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 }
2674
Kenny Root85387d72010-08-26 10:13:11 -07002675 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2676 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002677 pkg.mPath = pkg.mScanPath = destCodePath;
2678 pkg.applicationInfo.sourceDir = destCodePath;
2679 pkg.applicationInfo.publicSourceDir = destResPath;
2680 }
2681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 private static String fixProcessName(String defProcessName,
2683 String processName, int uid) {
2684 if (processName == null) {
2685 return defProcessName;
2686 }
2687 return processName;
2688 }
2689
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002690 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002691 PackageParser.Package pkg) {
2692 if (pkgSetting.signatures.mSignatures != null) {
2693 // Already existing package. Make sure signatures match
2694 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2695 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002696 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002697 + " signatures do not match the previously installed version; ignoring!");
2698 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 return false;
2700 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002701 }
2702 // Check for shared user signatures
2703 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2704 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2705 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2706 Slog.e(TAG, "Package " + pkg.packageName
2707 + " has no signatures that match those in shared user "
2708 + pkgSetting.sharedUser.name + "; ignoring!");
2709 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2710 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 }
2713 return true;
2714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002715
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002716 public boolean performDexOpt(String packageName) {
2717 if (!mNoDexOpt) {
2718 return false;
2719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002720
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002721 PackageParser.Package p;
2722 synchronized (mPackages) {
2723 p = mPackages.get(packageName);
2724 if (p == null || p.mDidDexOpt) {
2725 return false;
2726 }
2727 }
2728 synchronized (mInstallLock) {
2729 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2730 }
2731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002733 static final int DEX_OPT_SKIPPED = 0;
2734 static final int DEX_OPT_PERFORMED = 1;
2735 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2738 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002739 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002740 String path = pkg.mScanPath;
2741 int ret = 0;
2742 try {
2743 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002744 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002745 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002746 pkg.mDidDexOpt = true;
2747 performed = true;
2748 }
2749 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002750 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002751 ret = -1;
2752 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002753 Slog.w(TAG, "IOException reading apk: " + path, e);
2754 ret = -1;
2755 } catch (dalvik.system.StaleDexCacheError e) {
2756 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2757 ret = -1;
2758 } catch (Exception e) {
2759 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002760 ret = -1;
2761 }
2762 if (ret < 0) {
2763 //error from installer
2764 return DEX_OPT_FAILED;
2765 }
2766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002767
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002768 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2769 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002770
2771 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2772 return Environment.isEncryptedFilesystemEnabled() &&
2773 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2774 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002775
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002776 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2777 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002778 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002779 + " to " + newPkg.packageName
2780 + ": old package not in system partition");
2781 return false;
2782 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002783 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002784 + " to " + newPkg.packageName
2785 + ": old package still exists");
2786 return false;
2787 }
2788 return true;
2789 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002790
2791 private File getDataPathForPackage(PackageParser.Package pkg) {
2792 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2793 File dataPath;
2794 if (useEncryptedFSDir) {
2795 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2796 } else {
2797 dataPath = new File(mAppDataDir, pkg.packageName);
2798 }
2799 return dataPath;
2800 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002801
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002802 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2803 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002804 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002805 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2806 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002807 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002808 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002809 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2810 return null;
2811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 mScanningPath = scanFile;
2813 if (pkg == null) {
2814 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2815 return null;
2816 }
2817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2819 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2820 }
2821
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002822 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 synchronized (mPackages) {
2824 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002825 Slog.w(TAG, "*************************************************");
2826 Slog.w(TAG, "Core android package being redefined. Skipping.");
2827 Slog.w(TAG, " file=" + mScanningPath);
2828 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2830 return null;
2831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 // Set up information for our fall-back user intent resolution
2834 // activity.
2835 mPlatformPackage = pkg;
2836 pkg.mVersionCode = mSdkVersion;
2837 mAndroidApplication = pkg.applicationInfo;
2838 mResolveActivity.applicationInfo = mAndroidApplication;
2839 mResolveActivity.name = ResolverActivity.class.getName();
2840 mResolveActivity.packageName = mAndroidApplication.packageName;
2841 mResolveActivity.processName = mAndroidApplication.processName;
2842 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2843 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2844 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2845 mResolveActivity.exported = true;
2846 mResolveActivity.enabled = true;
2847 mResolveInfo.activityInfo = mResolveActivity;
2848 mResolveInfo.priority = 0;
2849 mResolveInfo.preferredOrder = 0;
2850 mResolveInfo.match = 0;
2851 mResolveComponentName = new ComponentName(
2852 mAndroidApplication.packageName, mResolveActivity.name);
2853 }
2854 }
2855
2856 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002857 TAG, "Scanning package " + pkg.packageName);
2858 if (mPackages.containsKey(pkg.packageName)
2859 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002860 Slog.w(TAG, "*************************************************");
2861 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002863 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2865 return null;
2866 }
2867
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002868 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002869 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2870 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 SharedUserSetting suid = null;
2873 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002874
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002875 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2876 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002877 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002878 pkg.mRealPackage = null;
2879 pkg.mAdoptPermissions = null;
2880 }
2881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 synchronized (mPackages) {
2883 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002884 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2885 if (mTmpSharedLibraries == null ||
2886 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2887 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2888 }
2889 int num = 0;
2890 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2891 for (int i=0; i<N; i++) {
2892 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002894 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002896 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2898 return null;
2899 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002900 mTmpSharedLibraries[num] = file;
2901 num++;
2902 }
2903 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2904 for (int i=0; i<N; i++) {
2905 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2906 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002907 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002908 + " desires unavailable shared library "
2909 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2910 } else {
2911 mTmpSharedLibraries[num] = file;
2912 num++;
2913 }
2914 }
2915 if (num > 0) {
2916 pkg.usesLibraryFiles = new String[num];
2917 System.arraycopy(mTmpSharedLibraries, 0,
2918 pkg.usesLibraryFiles, 0, num);
2919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002920
Dianne Hackborn49237342009-08-27 20:08:01 -07002921 if (pkg.reqFeatures != null) {
2922 N = pkg.reqFeatures.size();
2923 for (int i=0; i<N; i++) {
2924 FeatureInfo fi = pkg.reqFeatures.get(i);
2925 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2926 // Don't care.
2927 continue;
2928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002929
Dianne Hackborn49237342009-08-27 20:08:01 -07002930 if (fi.name != null) {
2931 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002932 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002933 + " requires unavailable feature "
2934 + fi.name + "; failing!");
2935 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2936 return null;
2937 }
2938 }
2939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 if (pkg.mSharedUserId != null) {
2944 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2945 pkg.applicationInfo.flags, true);
2946 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002947 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 + " for shared user failed");
2949 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2950 return null;
2951 }
2952 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2953 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2954 + suid.userId + "): packages=" + suid.packages);
2955 }
2956 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002957
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002958 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002959 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 Log.w(TAG, "WAITING FOR DEBUGGER");
2961 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002962 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2963 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002964 }
2965 }
2966
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002967 // Check if we are renaming from an original package name.
2968 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002969 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002970 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002971 // This package may need to be renamed to a previously
2972 // installed name. Let's check on that...
2973 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002974 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 // This package had originally been installed as the
2976 // original name, and we have already taken care of
2977 // transitioning to the new one. Just update the new
2978 // one to continue using the old name.
2979 realName = pkg.mRealPackage;
2980 if (!pkg.packageName.equals(renamed)) {
2981 // Callers into this function may have already taken
2982 // care of renaming the package; only do it here if
2983 // it is not already done.
2984 pkg.setPackageName(renamed);
2985 }
2986
Dianne Hackbornc1552392010-03-03 16:19:01 -08002987 } else {
2988 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2989 if ((origPackage=mSettings.peekPackageLP(
2990 pkg.mOriginalPackages.get(i))) != null) {
2991 // We do have the package already installed under its
2992 // original name... should we use it?
2993 if (!verifyPackageUpdate(origPackage, pkg)) {
2994 // New package is not compatible with original.
2995 origPackage = null;
2996 continue;
2997 } else if (origPackage.sharedUser != null) {
2998 // Make sure uid is compatible between packages.
2999 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003000 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003001 + " to " + pkg.packageName + ": old uid "
3002 + origPackage.sharedUser.name
3003 + " differs from " + pkg.mSharedUserId);
3004 origPackage = null;
3005 continue;
3006 }
3007 } else {
3008 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3009 + pkg.packageName + " to old name " + origPackage.name);
3010 }
3011 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003012 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003013 }
3014 }
3015 }
3016
3017 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003018 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003019 + " was transferred to another, but its .apk remains");
3020 }
3021
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003022 // Just create the setting, don't add it yet. For already existing packages
3023 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003024 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003025 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3026 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003028 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3030 return null;
3031 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003032
3033 if (pkgSetting.origPackage != null) {
3034 // If we are first transitioning from an original package,
3035 // fix up the new package's name now. We need to do this after
3036 // looking up the package under its new name, so getPackageLP
3037 // can take care of fiddling things correctly.
3038 pkg.setPackageName(origPackage.name);
3039
3040 // File a report about this.
3041 String msg = "New package " + pkgSetting.realName
3042 + " renamed to replace old package " + pkgSetting.name;
3043 reportSettingsProblem(Log.WARN, msg);
3044
3045 // Make a note of it.
3046 mTransferedPackages.add(origPackage.name);
3047
3048 // No longer need to retain this.
3049 pkgSetting.origPackage = null;
3050 }
3051
3052 if (realName != null) {
3053 // Make a note of it.
3054 mTransferedPackages.add(pkg.packageName);
3055 }
3056
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003057 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 pkg.applicationInfo.uid = pkgSetting.userId;
3062 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003063
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003064 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003065 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 return null;
3067 }
3068 // The signature has changed, but this package is in the system
3069 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003070 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 // However... if this package is part of a shared user, but it
3072 // doesn't match the signature of the shared user, let's fail.
3073 // What this means is that you can't change the signatures
3074 // associated with an overall shared user, which doesn't seem all
3075 // that unreasonable.
3076 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003077 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3078 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3079 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3081 return null;
3082 }
3083 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003084 // File a report about this.
3085 String msg = "System package " + pkg.packageName
3086 + " signature changed; retaining data.";
3087 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003089
The Android Open Source Project10592532009-03-18 17:39:46 -07003090 // Verify that this new package doesn't have any content providers
3091 // that conflict with existing packages. Only do this if the
3092 // package isn't already installed, since we don't want to break
3093 // things that are installed.
3094 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3095 int N = pkg.providers.size();
3096 int i;
3097 for (i=0; i<N; i++) {
3098 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003099 if (p.info.authority != null) {
3100 String names[] = p.info.authority.split(";");
3101 for (int j = 0; j < names.length; j++) {
3102 if (mProviders.containsKey(names[j])) {
3103 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003104 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003105 " (in package " + pkg.applicationInfo.packageName +
3106 ") is already used by "
3107 + ((other != null && other.getComponentName() != null)
3108 ? other.getComponentName().getPackageName() : "?"));
3109 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3110 return null;
3111 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003112 }
3113 }
3114 }
3115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 }
3117
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003118 final String pkgName = pkg.packageName;
3119
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003120 if (pkg.mAdoptPermissions != null) {
3121 // This package wants to adopt ownership of permissions from
3122 // another package.
3123 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3124 String origName = pkg.mAdoptPermissions.get(i);
3125 PackageSetting orig = mSettings.peekPackageLP(origName);
3126 if (orig != null) {
3127 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003128 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003129 + origName + " to " + pkg.packageName);
3130 mSettings.transferPermissions(origName, pkg.packageName);
3131 }
3132 }
3133 }
3134 }
3135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 long scanFileTime = scanFile.lastModified();
3137 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003138 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 pkg.applicationInfo.processName = fixProcessName(
3140 pkg.applicationInfo.packageName,
3141 pkg.applicationInfo.processName,
3142 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143
3144 File dataPath;
3145 if (mPlatformPackage == pkg) {
3146 // The system package is special.
3147 dataPath = new File (Environment.getDataDirectory(), "system");
3148 pkg.applicationInfo.dataDir = dataPath.getPath();
3149 } else {
3150 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003151 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003152 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003153
3154 boolean uidError = false;
3155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 if (dataPath.exists()) {
3157 mOutPermissions[1] = 0;
3158 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003159
3160 // If we have mismatched owners for the data path, we have a
3161 // problem (unless we're running in the simulator.)
3162 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 boolean recovered = false;
3164 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3165 // If this is a system app, we can at least delete its
3166 // current data so the application will still work.
3167 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003168 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003169 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 // Old data gone!
3171 String msg = "System package " + pkg.packageName
3172 + " has changed from uid: "
3173 + mOutPermissions[1] + " to "
3174 + pkg.applicationInfo.uid + "; old data erased";
3175 reportSettingsProblem(Log.WARN, msg);
3176 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003179 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 pkg.applicationInfo.uid);
3181 if (ret == -1) {
3182 // Ack should not happen!
3183 msg = "System package " + pkg.packageName
3184 + " could not have data directory re-created after delete.";
3185 reportSettingsProblem(Log.WARN, msg);
3186 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3187 return null;
3188 }
3189 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 if (!recovered) {
3192 mHasSystemUidErrors = true;
3193 }
3194 }
3195 if (!recovered) {
3196 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3197 + pkg.applicationInfo.uid + "/fs_"
3198 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003199 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 String msg = "Package " + pkg.packageName
3201 + " has mismatched uid: "
3202 + mOutPermissions[1] + " on disk, "
3203 + pkg.applicationInfo.uid + " in settings";
3204 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003205 mSettings.mReadMessages.append(msg);
3206 mSettings.mReadMessages.append('\n');
3207 uidError = true;
3208 if (!pkgSetting.uidError) {
3209 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 }
3212 }
3213 }
3214 pkg.applicationInfo.dataDir = dataPath.getPath();
3215 } else {
3216 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3217 Log.v(TAG, "Want this data dir: " + dataPath);
3218 //invoke installer to do the actual installation
3219 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003220 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 pkg.applicationInfo.uid);
3222 if(ret < 0) {
3223 // Error from installer
3224 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3225 return null;
3226 }
3227 } else {
3228 dataPath.mkdirs();
3229 if (dataPath.exists()) {
3230 FileUtils.setPermissions(
3231 dataPath.toString(),
3232 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3233 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3234 }
3235 }
3236 if (dataPath.exists()) {
3237 pkg.applicationInfo.dataDir = dataPath.getPath();
3238 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003239 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 pkg.applicationInfo.dataDir = null;
3241 }
3242 }
Kenny Root85387d72010-08-26 10:13:11 -07003243
Kenny Root806cc132010-09-12 08:34:19 -07003244 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3245
Kenny Root85387d72010-08-26 10:13:11 -07003246 /*
3247 * Set the data dir to the default "/data/data/<package name>/lib"
3248 * if we got here without anyone telling us different (e.g., apps
3249 * stored on SD card have their native libraries stored in the ASEC
3250 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003251 *
3252 * This happens during an upgrade from a package settings file that
3253 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003254 */
Kenny Root806cc132010-09-12 08:34:19 -07003255 if (pkgSetting.nativeLibraryPathString == null && pkg.applicationInfo.dataDir != null) {
3256 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3257 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3258 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
Kenny Root85387d72010-08-26 10:13:11 -07003259 }
3260
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003261 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 }
3263
Kenny Root85387d72010-08-26 10:13:11 -07003264 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 if (mInstaller != null) {
3266 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003267 /* Note: We don't want to unpack the native binaries for
3268 * system applications, unless they have been updated
3269 * (the binaries are already under /system/lib).
3270 * Also, don't unpack libs for apps on the external card
3271 * since they should have their libraries in the ASEC
3272 * container already.
3273 *
3274 * In other words, we're going to unpack the binaries
3275 * only for non-system apps and system app upgrades.
3276 */
3277 if ((!isSystemApp(pkg) || isUpdatedSystemApp(pkg)) && !isExternal(pkg)) {
3278 Log.i(TAG, path + " changed; unpacking");
3279 File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root85387d72010-08-26 10:13:11 -07003280 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003282 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003283
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003284 if ((scanMode&SCAN_NO_DEX) == 0) {
3285 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3287 return null;
3288 }
3289 }
3290 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 if (mFactoryTest && pkg.requestedPermissions.contains(
3293 android.Manifest.permission.FACTORY_TEST)) {
3294 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3295 }
3296
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003297 // Request the ActivityManager to kill the process(only for existing packages)
3298 // so that we do not end up in a confused state while the user is still using the older
3299 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003300 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003301 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003302 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003303 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003306 // We don't expect installation to fail beyond this point,
3307 if ((scanMode&SCAN_MONITOR) != 0) {
3308 mAppDirs.put(pkg.mPath, pkg);
3309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003311 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003313 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003314 // Make sure we don't accidentally delete its data.
3315 mSettings.mPackagesToBeCleaned.remove(pkgName);
3316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003317 int N = pkg.providers.size();
3318 StringBuilder r = null;
3319 int i;
3320 for (i=0; i<N; i++) {
3321 PackageParser.Provider p = pkg.providers.get(i);
3322 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3323 p.info.processName, pkg.applicationInfo.uid);
3324 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3325 p.info.name), p);
3326 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003327 if (p.info.authority != null) {
3328 String names[] = p.info.authority.split(";");
3329 p.info.authority = null;
3330 for (int j = 0; j < names.length; j++) {
3331 if (j == 1 && p.syncable) {
3332 // We only want the first authority for a provider to possibly be
3333 // syncable, so if we already added this provider using a different
3334 // authority clear the syncable flag. We copy the provider before
3335 // changing it because the mProviders object contains a reference
3336 // to a provider that we don't want to change.
3337 // Only do this for the second authority since the resulting provider
3338 // object can be the same for all future authorities for this provider.
3339 p = new PackageParser.Provider(p);
3340 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003341 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003342 if (!mProviders.containsKey(names[j])) {
3343 mProviders.put(names[j], p);
3344 if (p.info.authority == null) {
3345 p.info.authority = names[j];
3346 } else {
3347 p.info.authority = p.info.authority + ";" + names[j];
3348 }
3349 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3350 Log.d(TAG, "Registered content provider: " + names[j] +
3351 ", className = " + p.info.name +
3352 ", isSyncable = " + p.info.isSyncable);
3353 } else {
3354 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003355 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003356 " (in package " + pkg.applicationInfo.packageName +
3357 "): name already used by "
3358 + ((other != null && other.getComponentName() != null)
3359 ? other.getComponentName().getPackageName() : "?"));
3360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 }
3362 }
3363 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3364 if (r == null) {
3365 r = new StringBuilder(256);
3366 } else {
3367 r.append(' ');
3368 }
3369 r.append(p.info.name);
3370 }
3371 }
3372 if (r != null) {
3373 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3374 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 N = pkg.services.size();
3377 r = null;
3378 for (i=0; i<N; i++) {
3379 PackageParser.Service s = pkg.services.get(i);
3380 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3381 s.info.processName, pkg.applicationInfo.uid);
3382 mServices.addService(s);
3383 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3384 if (r == null) {
3385 r = new StringBuilder(256);
3386 } else {
3387 r.append(' ');
3388 }
3389 r.append(s.info.name);
3390 }
3391 }
3392 if (r != null) {
3393 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3394 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 N = pkg.receivers.size();
3397 r = null;
3398 for (i=0; i<N; i++) {
3399 PackageParser.Activity a = pkg.receivers.get(i);
3400 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3401 a.info.processName, pkg.applicationInfo.uid);
3402 mReceivers.addActivity(a, "receiver");
3403 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3404 if (r == null) {
3405 r = new StringBuilder(256);
3406 } else {
3407 r.append(' ');
3408 }
3409 r.append(a.info.name);
3410 }
3411 }
3412 if (r != null) {
3413 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3414 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 N = pkg.activities.size();
3417 r = null;
3418 for (i=0; i<N; i++) {
3419 PackageParser.Activity a = pkg.activities.get(i);
3420 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3421 a.info.processName, pkg.applicationInfo.uid);
3422 mActivities.addActivity(a, "activity");
3423 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3424 if (r == null) {
3425 r = new StringBuilder(256);
3426 } else {
3427 r.append(' ');
3428 }
3429 r.append(a.info.name);
3430 }
3431 }
3432 if (r != null) {
3433 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3434 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 N = pkg.permissionGroups.size();
3437 r = null;
3438 for (i=0; i<N; i++) {
3439 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3440 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3441 if (cur == null) {
3442 mPermissionGroups.put(pg.info.name, pg);
3443 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3444 if (r == null) {
3445 r = new StringBuilder(256);
3446 } else {
3447 r.append(' ');
3448 }
3449 r.append(pg.info.name);
3450 }
3451 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003452 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 + pg.info.packageName + " ignored: original from "
3454 + cur.info.packageName);
3455 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3456 if (r == null) {
3457 r = new StringBuilder(256);
3458 } else {
3459 r.append(' ');
3460 }
3461 r.append("DUP:");
3462 r.append(pg.info.name);
3463 }
3464 }
3465 }
3466 if (r != null) {
3467 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3468 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003469
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003470 N = pkg.permissions.size();
3471 r = null;
3472 for (i=0; i<N; i++) {
3473 PackageParser.Permission p = pkg.permissions.get(i);
3474 HashMap<String, BasePermission> permissionMap =
3475 p.tree ? mSettings.mPermissionTrees
3476 : mSettings.mPermissions;
3477 p.group = mPermissionGroups.get(p.info.group);
3478 if (p.info.group == null || p.group != null) {
3479 BasePermission bp = permissionMap.get(p.info.name);
3480 if (bp == null) {
3481 bp = new BasePermission(p.info.name, p.info.packageName,
3482 BasePermission.TYPE_NORMAL);
3483 permissionMap.put(p.info.name, bp);
3484 }
3485 if (bp.perm == null) {
3486 if (bp.sourcePackage == null
3487 || bp.sourcePackage.equals(p.info.packageName)) {
3488 BasePermission tree = findPermissionTreeLP(p.info.name);
3489 if (tree == null
3490 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003491 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 bp.perm = p;
3493 bp.uid = pkg.applicationInfo.uid;
3494 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3495 if (r == null) {
3496 r = new StringBuilder(256);
3497 } else {
3498 r.append(' ');
3499 }
3500 r.append(p.info.name);
3501 }
3502 } 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: base tree "
3505 + tree.name + " is from package "
3506 + tree.sourcePackage);
3507 }
3508 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003509 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 + p.info.packageName + " ignored: original from "
3511 + bp.sourcePackage);
3512 }
3513 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3514 if (r == null) {
3515 r = new StringBuilder(256);
3516 } else {
3517 r.append(' ');
3518 }
3519 r.append("DUP:");
3520 r.append(p.info.name);
3521 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003522 if (bp.perm == p) {
3523 bp.protectionLevel = p.info.protectionLevel;
3524 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003526 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 + p.info.packageName + " ignored: no group "
3528 + p.group);
3529 }
3530 }
3531 if (r != null) {
3532 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3533 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 N = pkg.instrumentation.size();
3536 r = null;
3537 for (i=0; i<N; i++) {
3538 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3539 a.info.packageName = pkg.applicationInfo.packageName;
3540 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3541 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3542 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003543 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003544 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3546 if (r == null) {
3547 r = new StringBuilder(256);
3548 } else {
3549 r.append(' ');
3550 }
3551 r.append(a.info.name);
3552 }
3553 }
3554 if (r != null) {
3555 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003557
Dianne Hackborn854060af2009-07-09 18:14:31 -07003558 if (pkg.protectedBroadcasts != null) {
3559 N = pkg.protectedBroadcasts.size();
3560 for (i=0; i<N; i++) {
3561 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3562 }
3563 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565 pkgSetting.setTimeStamp(scanFileTime);
3566 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 return pkg;
3569 }
3570
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003571 private void killApplication(String pkgName, int uid) {
3572 // Request the ActivityManager to kill the process(only for existing packages)
3573 // so that we do not end up in a confused state while the user is still using the older
3574 // version of the application while the new one gets installed.
3575 IActivityManager am = ActivityManagerNative.getDefault();
3576 if (am != null) {
3577 try {
3578 am.killApplicationWithUid(pkgName, uid);
3579 } catch (RemoteException e) {
3580 }
3581 }
3582 }
3583
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003584 // Return the path of the directory that will contain the native binaries
3585 // of a given installed package. This is relative to the data path.
3586 //
Kenny Root85387d72010-08-26 10:13:11 -07003587 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3588 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3589 if (nativeLibraryDir != null) {
3590 return new File(nativeLibraryDir);
3591 } else {
3592 // Fall back for old packages
3593 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3594 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003595 }
3596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003597 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3598 if (chatty && Config.LOGD) Log.d(
3599 TAG, "Removing package " + pkg.applicationInfo.packageName );
3600
3601 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 mPackages.remove(pkg.applicationInfo.packageName);
3605 if (pkg.mPath != null) {
3606 mAppDirs.remove(pkg.mPath);
3607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 PackageSetting ps = (PackageSetting)pkg.mExtras;
3610 if (ps != null && ps.sharedUser != null) {
3611 // XXX don't do this until the data is removed.
3612 if (false) {
3613 ps.sharedUser.packages.remove(ps);
3614 if (ps.sharedUser.packages.size() == 0) {
3615 // Remove.
3616 }
3617 }
3618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 int N = pkg.providers.size();
3621 StringBuilder r = null;
3622 int i;
3623 for (i=0; i<N; i++) {
3624 PackageParser.Provider p = pkg.providers.get(i);
3625 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3626 p.info.name));
3627 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 /* The is another ContentProvider with this authority when
3630 * this app was installed so this authority is null,
3631 * Ignore it as we don't have to unregister the provider.
3632 */
3633 continue;
3634 }
3635 String names[] = p.info.authority.split(";");
3636 for (int j = 0; j < names.length; j++) {
3637 if (mProviders.get(names[j]) == p) {
3638 mProviders.remove(names[j]);
3639 if (chatty && Config.LOGD) Log.d(
3640 TAG, "Unregistered content provider: " + names[j] +
3641 ", className = " + p.info.name +
3642 ", isSyncable = " + p.info.isSyncable);
3643 }
3644 }
3645 if (chatty) {
3646 if (r == null) {
3647 r = new StringBuilder(256);
3648 } else {
3649 r.append(' ');
3650 }
3651 r.append(p.info.name);
3652 }
3653 }
3654 if (r != null) {
3655 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 N = pkg.services.size();
3659 r = null;
3660 for (i=0; i<N; i++) {
3661 PackageParser.Service s = pkg.services.get(i);
3662 mServices.removeService(s);
3663 if (chatty) {
3664 if (r == null) {
3665 r = new StringBuilder(256);
3666 } else {
3667 r.append(' ');
3668 }
3669 r.append(s.info.name);
3670 }
3671 }
3672 if (r != null) {
3673 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 N = pkg.receivers.size();
3677 r = null;
3678 for (i=0; i<N; i++) {
3679 PackageParser.Activity a = pkg.receivers.get(i);
3680 mReceivers.removeActivity(a, "receiver");
3681 if (chatty) {
3682 if (r == null) {
3683 r = new StringBuilder(256);
3684 } else {
3685 r.append(' ');
3686 }
3687 r.append(a.info.name);
3688 }
3689 }
3690 if (r != null) {
3691 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 N = pkg.activities.size();
3695 r = null;
3696 for (i=0; i<N; i++) {
3697 PackageParser.Activity a = pkg.activities.get(i);
3698 mActivities.removeActivity(a, "activity");
3699 if (chatty) {
3700 if (r == null) {
3701 r = new StringBuilder(256);
3702 } else {
3703 r.append(' ');
3704 }
3705 r.append(a.info.name);
3706 }
3707 }
3708 if (r != null) {
3709 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003712 N = pkg.permissions.size();
3713 r = null;
3714 for (i=0; i<N; i++) {
3715 PackageParser.Permission p = pkg.permissions.get(i);
3716 boolean tree = false;
3717 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3718 if (bp == null) {
3719 tree = true;
3720 bp = mSettings.mPermissionTrees.get(p.info.name);
3721 }
3722 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003723 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 if (chatty) {
3725 if (r == null) {
3726 r = new StringBuilder(256);
3727 } else {
3728 r.append(' ');
3729 }
3730 r.append(p.info.name);
3731 }
3732 }
3733 }
3734 if (r != null) {
3735 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3736 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 N = pkg.instrumentation.size();
3739 r = null;
3740 for (i=0; i<N; i++) {
3741 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003742 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 if (chatty) {
3744 if (r == null) {
3745 r = new StringBuilder(256);
3746 } else {
3747 r.append(' ');
3748 }
3749 r.append(a.info.name);
3750 }
3751 }
3752 if (r != null) {
3753 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3754 }
3755 }
3756 }
3757
3758 private static final boolean isPackageFilename(String name) {
3759 return name != null && name.endsWith(".apk");
3760 }
3761
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003762 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3763 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3764 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3765 return true;
3766 }
3767 }
3768 return false;
3769 }
3770
3771 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003772 PackageParser.Package pkgInfo, boolean grantPermissions,
3773 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003774 // Make sure there are no dangling permission trees.
3775 Iterator<BasePermission> it = mSettings.mPermissionTrees
3776 .values().iterator();
3777 while (it.hasNext()) {
3778 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003779 if (bp.packageSetting == null) {
3780 // We may not yet have parsed the package, so just see if
3781 // we still know about its settings.
3782 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3783 }
3784 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003785 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 + " from package " + bp.sourcePackage);
3787 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003788 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3789 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3790 Slog.i(TAG, "Removing old permission tree: " + bp.name
3791 + " from package " + bp.sourcePackage);
3792 grantPermissions = true;
3793 it.remove();
3794 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 }
3796 }
3797
3798 // Make sure all dynamic permissions have been assigned to a package,
3799 // and make sure there are no dangling permissions.
3800 it = mSettings.mPermissions.values().iterator();
3801 while (it.hasNext()) {
3802 BasePermission bp = it.next();
3803 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3804 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3805 + bp.name + " pkg=" + bp.sourcePackage
3806 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003807 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 BasePermission tree = findPermissionTreeLP(bp.name);
3809 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003810 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 bp.perm = new PackageParser.Permission(tree.perm.owner,
3812 new PermissionInfo(bp.pendingInfo));
3813 bp.perm.info.packageName = tree.perm.info.packageName;
3814 bp.perm.info.name = bp.name;
3815 bp.uid = tree.uid;
3816 }
3817 }
3818 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003819 if (bp.packageSetting == null) {
3820 // We may not yet have parsed the package, so just see if
3821 // we still know about its settings.
3822 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3823 }
3824 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003825 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 + " from package " + bp.sourcePackage);
3827 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003828 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3829 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3830 Slog.i(TAG, "Removing old permission: " + bp.name
3831 + " from package " + bp.sourcePackage);
3832 grantPermissions = true;
3833 it.remove();
3834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 }
3836 }
3837
3838 // Now update the permissions for all packages, in particular
3839 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003840 if (grantPermissions) {
3841 for (PackageParser.Package pkg : mPackages.values()) {
3842 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003843 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003844 }
3845 }
3846 }
3847
3848 if (pkgInfo != null) {
3849 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 }
3851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3854 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3855 if (ps == null) {
3856 return;
3857 }
3858 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003859 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 if (replace) {
3862 ps.permissionsFixed = false;
3863 if (gp == ps) {
3864 gp.grantedPermissions.clear();
3865 gp.gids = mGlobalGids;
3866 }
3867 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 if (gp.gids == null) {
3870 gp.gids = mGlobalGids;
3871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 final int N = pkg.requestedPermissions.size();
3874 for (int i=0; i<N; i++) {
3875 String name = pkg.requestedPermissions.get(i);
3876 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 if (false) {
3878 if (gp != ps) {
3879 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003880 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 }
3882 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003883 if (bp != null && bp.packageSetting != null) {
3884 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003886 boolean allowedSig = false;
3887 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3888 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003890 } else if (bp.packageSetting == null) {
3891 // This permission is invalid; skip it.
3892 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003893 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3894 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3895 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003897 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003899 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003900 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 // For updated system applications, the signatureOrSystem permission
3902 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003903 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3905 if(sysPs.grantedPermissions.contains(perm)) {
3906 allowed = true;
3907 } else {
3908 allowed = false;
3909 }
3910 } else {
3911 allowed = true;
3912 }
3913 }
3914 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003915 if (allowed) {
3916 allowedSig = true;
3917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 } else {
3919 allowed = false;
3920 }
3921 if (false) {
3922 if (gp != ps) {
3923 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3924 }
3925 }
3926 if (allowed) {
3927 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3928 && ps.permissionsFixed) {
3929 // If this is an existing, non-system package, then
3930 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003931 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003933 // Except... if this is a permission that was added
3934 // to the platform (note: need to only do this when
3935 // updating the platform).
3936 final int NP = PackageParser.NEW_PERMISSIONS.length;
3937 for (int ip=0; ip<NP; ip++) {
3938 final PackageParser.NewPermissionInfo npi
3939 = PackageParser.NEW_PERMISSIONS[ip];
3940 if (npi.name.equals(perm)
3941 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3942 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003943 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003944 + pkg.packageName);
3945 break;
3946 }
3947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003948 }
3949 }
3950 if (allowed) {
3951 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003952 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 gp.grantedPermissions.add(perm);
3954 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003955 } else if (!ps.haveGids) {
3956 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 }
3958 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003959 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 + " to package " + pkg.packageName
3961 + " because it was previously installed without");
3962 }
3963 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003964 if (gp.grantedPermissions.remove(perm)) {
3965 changedPermission = true;
3966 gp.gids = removeInts(gp.gids, bp.gids);
3967 Slog.i(TAG, "Un-granting permission " + perm
3968 + " from package " + pkg.packageName
3969 + " (protectionLevel=" + bp.protectionLevel
3970 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3971 + ")");
3972 } else {
3973 Slog.w(TAG, "Not granting permission " + perm
3974 + " to package " + pkg.packageName
3975 + " (protectionLevel=" + bp.protectionLevel
3976 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3977 + ")");
3978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979 }
3980 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003981 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003982 + " in package " + pkg.packageName);
3983 }
3984 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003985
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003986 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003987 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3988 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003989 // This is the first that we have heard about this package, so the
3990 // permissions we have now selected are fixed until explicitly
3991 // changed.
3992 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003994 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003996
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 private final class ActivityIntentResolver
3998 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02003999 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004001 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 }
4003
Mihai Preda074edef2009-05-18 17:13:31 +02004004 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004005 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004006 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4008 }
4009
Mihai Predaeae850c2009-05-13 10:13:48 +02004010 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4011 ArrayList<PackageParser.Activity> packageActivities) {
4012 if (packageActivities == null) {
4013 return null;
4014 }
4015 mFlags = flags;
4016 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4017 int N = packageActivities.size();
4018 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4019 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004020
4021 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004022 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004023 intentFilters = packageActivities.get(i).intents;
4024 if (intentFilters != null && intentFilters.size() > 0) {
4025 listCut.add(intentFilters);
4026 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004027 }
4028 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4029 }
4030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004032 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 if (SHOW_INFO || Config.LOGV) Log.v(
4034 TAG, " " + type + " " +
4035 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4036 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4037 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004038 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4040 if (SHOW_INFO || Config.LOGV) {
4041 Log.v(TAG, " IntentFilter:");
4042 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4043 }
4044 if (!intent.debugCheck()) {
4045 Log.w(TAG, "==> For Activity " + a.info.name);
4046 }
4047 addFilter(intent);
4048 }
4049 }
4050
4051 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004052 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 if (SHOW_INFO || Config.LOGV) Log.v(
4054 TAG, " " + type + " " +
4055 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4056 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4057 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004058 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4060 if (SHOW_INFO || Config.LOGV) {
4061 Log.v(TAG, " IntentFilter:");
4062 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4063 }
4064 removeFilter(intent);
4065 }
4066 }
4067
4068 @Override
4069 protected boolean allowFilterResult(
4070 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4071 ActivityInfo filterAi = filter.activity.info;
4072 for (int i=dest.size()-1; i>=0; i--) {
4073 ActivityInfo destAi = dest.get(i).activityInfo;
4074 if (destAi.name == filterAi.name
4075 && destAi.packageName == filterAi.packageName) {
4076 return false;
4077 }
4078 }
4079 return true;
4080 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004083 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4084 return info.activity.owner.packageName;
4085 }
4086
4087 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4089 int match) {
4090 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4091 return null;
4092 }
4093 final PackageParser.Activity activity = info.activity;
4094 if (mSafeMode && (activity.info.applicationInfo.flags
4095 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4096 return null;
4097 }
4098 final ResolveInfo res = new ResolveInfo();
4099 res.activityInfo = PackageParser.generateActivityInfo(activity,
4100 mFlags);
4101 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4102 res.filter = info;
4103 }
4104 res.priority = info.getPriority();
4105 res.preferredOrder = activity.owner.mPreferredOrder;
4106 //System.out.println("Result: " + res.activityInfo.className +
4107 // " = " + res.priority);
4108 res.match = match;
4109 res.isDefault = info.hasDefault;
4110 res.labelRes = info.labelRes;
4111 res.nonLocalizedLabel = info.nonLocalizedLabel;
4112 res.icon = info.icon;
4113 return res;
4114 }
4115
4116 @Override
4117 protected void sortResults(List<ResolveInfo> results) {
4118 Collections.sort(results, mResolvePrioritySorter);
4119 }
4120
4121 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004122 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004123 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004124 out.print(prefix); out.print(
4125 Integer.toHexString(System.identityHashCode(filter.activity)));
4126 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004127 out.print(filter.activity.getComponentShortName());
4128 out.print(" filter ");
4129 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004130 }
4131
4132// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4133// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4134// final List<ResolveInfo> retList = Lists.newArrayList();
4135// while (i.hasNext()) {
4136// final ResolveInfo resolveInfo = i.next();
4137// if (isEnabledLP(resolveInfo.activityInfo)) {
4138// retList.add(resolveInfo);
4139// }
4140// }
4141// return retList;
4142// }
4143
4144 // Keys are String (activity class name), values are Activity.
4145 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4146 = new HashMap<ComponentName, PackageParser.Activity>();
4147 private int mFlags;
4148 }
4149
4150 private final class ServiceIntentResolver
4151 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004152 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004154 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 }
4156
Mihai Preda074edef2009-05-18 17:13:31 +02004157 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004158 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004159 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4161 }
4162
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004163 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4164 ArrayList<PackageParser.Service> packageServices) {
4165 if (packageServices == null) {
4166 return null;
4167 }
4168 mFlags = flags;
4169 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4170 int N = packageServices.size();
4171 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4172 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4173
4174 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4175 for (int i = 0; i < N; ++i) {
4176 intentFilters = packageServices.get(i).intents;
4177 if (intentFilters != null && intentFilters.size() > 0) {
4178 listCut.add(intentFilters);
4179 }
4180 }
4181 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4182 }
4183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004185 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 if (SHOW_INFO || Config.LOGV) Log.v(
4187 TAG, " " + (s.info.nonLocalizedLabel != null
4188 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4189 if (SHOW_INFO || Config.LOGV) Log.v(
4190 TAG, " Class=" + s.info.name);
4191 int NI = s.intents.size();
4192 int j;
4193 for (j=0; j<NI; j++) {
4194 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4195 if (SHOW_INFO || Config.LOGV) {
4196 Log.v(TAG, " IntentFilter:");
4197 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4198 }
4199 if (!intent.debugCheck()) {
4200 Log.w(TAG, "==> For Service " + s.info.name);
4201 }
4202 addFilter(intent);
4203 }
4204 }
4205
4206 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004207 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 if (SHOW_INFO || Config.LOGV) Log.v(
4209 TAG, " " + (s.info.nonLocalizedLabel != null
4210 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4211 if (SHOW_INFO || Config.LOGV) Log.v(
4212 TAG, " Class=" + s.info.name);
4213 int NI = s.intents.size();
4214 int j;
4215 for (j=0; j<NI; j++) {
4216 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4217 if (SHOW_INFO || Config.LOGV) {
4218 Log.v(TAG, " IntentFilter:");
4219 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4220 }
4221 removeFilter(intent);
4222 }
4223 }
4224
4225 @Override
4226 protected boolean allowFilterResult(
4227 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4228 ServiceInfo filterSi = filter.service.info;
4229 for (int i=dest.size()-1; i>=0; i--) {
4230 ServiceInfo destAi = dest.get(i).serviceInfo;
4231 if (destAi.name == filterSi.name
4232 && destAi.packageName == filterSi.packageName) {
4233 return false;
4234 }
4235 }
4236 return true;
4237 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004240 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4241 return info.service.owner.packageName;
4242 }
4243
4244 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4246 int match) {
4247 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4248 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4249 return null;
4250 }
4251 final PackageParser.Service service = info.service;
4252 if (mSafeMode && (service.info.applicationInfo.flags
4253 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4254 return null;
4255 }
4256 final ResolveInfo res = new ResolveInfo();
4257 res.serviceInfo = PackageParser.generateServiceInfo(service,
4258 mFlags);
4259 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4260 res.filter = filter;
4261 }
4262 res.priority = info.getPriority();
4263 res.preferredOrder = service.owner.mPreferredOrder;
4264 //System.out.println("Result: " + res.activityInfo.className +
4265 // " = " + res.priority);
4266 res.match = match;
4267 res.isDefault = info.hasDefault;
4268 res.labelRes = info.labelRes;
4269 res.nonLocalizedLabel = info.nonLocalizedLabel;
4270 res.icon = info.icon;
4271 return res;
4272 }
4273
4274 @Override
4275 protected void sortResults(List<ResolveInfo> results) {
4276 Collections.sort(results, mResolvePrioritySorter);
4277 }
4278
4279 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004280 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004282 out.print(prefix); out.print(
4283 Integer.toHexString(System.identityHashCode(filter.service)));
4284 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004285 out.print(filter.service.getComponentShortName());
4286 out.print(" filter ");
4287 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004288 }
4289
4290// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4291// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4292// final List<ResolveInfo> retList = Lists.newArrayList();
4293// while (i.hasNext()) {
4294// final ResolveInfo resolveInfo = (ResolveInfo) i;
4295// if (isEnabledLP(resolveInfo.serviceInfo)) {
4296// retList.add(resolveInfo);
4297// }
4298// }
4299// return retList;
4300// }
4301
4302 // Keys are String (activity class name), values are Activity.
4303 private final HashMap<ComponentName, PackageParser.Service> mServices
4304 = new HashMap<ComponentName, PackageParser.Service>();
4305 private int mFlags;
4306 };
4307
4308 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4309 new Comparator<ResolveInfo>() {
4310 public int compare(ResolveInfo r1, ResolveInfo r2) {
4311 int v1 = r1.priority;
4312 int v2 = r2.priority;
4313 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4314 if (v1 != v2) {
4315 return (v1 > v2) ? -1 : 1;
4316 }
4317 v1 = r1.preferredOrder;
4318 v2 = r2.preferredOrder;
4319 if (v1 != v2) {
4320 return (v1 > v2) ? -1 : 1;
4321 }
4322 if (r1.isDefault != r2.isDefault) {
4323 return r1.isDefault ? -1 : 1;
4324 }
4325 v1 = r1.match;
4326 v2 = r2.match;
4327 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4328 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4329 }
4330 };
4331
4332 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4333 new Comparator<ProviderInfo>() {
4334 public int compare(ProviderInfo p1, ProviderInfo p2) {
4335 final int v1 = p1.initOrder;
4336 final int v2 = p2.initOrder;
4337 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4338 }
4339 };
4340
Kenny Root93565c4b2010-06-18 15:46:06 -07004341 private static final boolean DEBUG_OBB = false;
4342
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004343 private static final void sendPackageBroadcast(String action, String pkg,
4344 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004345 IActivityManager am = ActivityManagerNative.getDefault();
4346 if (am != null) {
4347 try {
4348 final Intent intent = new Intent(action,
4349 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4350 if (extras != null) {
4351 intent.putExtras(extras);
4352 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004353 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004354 am.broadcastIntent(null, intent, null, finishedReceiver,
4355 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004356 } catch (RemoteException ex) {
4357 }
4358 }
4359 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004360
4361 public String nextPackageToClean(String lastPackage) {
4362 synchronized (mPackages) {
4363 if (!mMediaMounted) {
4364 // If the external storage is no longer mounted at this point,
4365 // the caller may not have been able to delete all of this
4366 // packages files and can not delete any more. Bail.
4367 return null;
4368 }
4369 if (lastPackage != null) {
4370 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4371 }
4372 return mSettings.mPackagesToBeCleaned.size() > 0
4373 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4374 }
4375 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004377 void schedulePackageCleaning(String packageName) {
4378 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4379 }
4380
4381 void startCleaningPackages() {
4382 synchronized (mPackages) {
4383 if (!mMediaMounted) {
4384 return;
4385 }
4386 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4387 return;
4388 }
4389 }
4390 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4391 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4392 IActivityManager am = ActivityManagerNative.getDefault();
4393 if (am != null) {
4394 try {
4395 am.startService(null, intent, null);
4396 } catch (RemoteException e) {
4397 }
4398 }
4399 }
4400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004401 private final class AppDirObserver extends FileObserver {
4402 public AppDirObserver(String path, int mask, boolean isrom) {
4403 super(path, mask);
4404 mRootDir = path;
4405 mIsRom = isrom;
4406 }
4407
4408 public void onEvent(int event, String path) {
4409 String removedPackage = null;
4410 int removedUid = -1;
4411 String addedPackage = null;
4412 int addedUid = -1;
4413
4414 synchronized (mInstallLock) {
4415 String fullPathStr = null;
4416 File fullPath = null;
4417 if (path != null) {
4418 fullPath = new File(mRootDir, path);
4419 fullPathStr = fullPath.getPath();
4420 }
4421
4422 if (Config.LOGV) Log.v(
4423 TAG, "File " + fullPathStr + " changed: "
4424 + Integer.toHexString(event));
4425
4426 if (!isPackageFilename(path)) {
4427 if (Config.LOGV) Log.v(
4428 TAG, "Ignoring change of non-package file: " + fullPathStr);
4429 return;
4430 }
4431
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004432 // Ignore packages that are being installed or
4433 // have just been installed.
4434 if (ignoreCodePath(fullPathStr)) {
4435 return;
4436 }
4437 PackageParser.Package p = null;
4438 synchronized (mPackages) {
4439 p = mAppDirs.get(fullPathStr);
4440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004441 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004442 if (p != null) {
4443 removePackageLI(p, true);
4444 removedPackage = p.applicationInfo.packageName;
4445 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004446 }
4447 }
4448
4449 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004451 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004452 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4453 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004454 PackageParser.PARSE_CHATTY |
4455 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004456 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004457 if (p != null) {
4458 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004459 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004460 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 }
4462 addedPackage = p.applicationInfo.packageName;
4463 addedUid = p.applicationInfo.uid;
4464 }
4465 }
4466 }
4467
4468 synchronized (mPackages) {
4469 mSettings.writeLP();
4470 }
4471 }
4472
4473 if (removedPackage != null) {
4474 Bundle extras = new Bundle(1);
4475 extras.putInt(Intent.EXTRA_UID, removedUid);
4476 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004477 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4478 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004479 }
4480 if (addedPackage != null) {
4481 Bundle extras = new Bundle(1);
4482 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004483 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4484 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 }
4486 }
4487
4488 private final String mRootDir;
4489 private final boolean mIsRom;
4490 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004491
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 /* Called when a downloaded package installation has been confirmed by the user */
4493 public void installPackage(
4494 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004495 installPackage(packageURI, observer, flags, null);
4496 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004497
Jacek Surazski65e13172009-04-28 15:26:38 +02004498 /* Called when a downloaded package installation has been confirmed by the user */
4499 public void installPackage(
4500 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4501 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 mContext.enforceCallingOrSelfPermission(
4503 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004504
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004505 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004506 msg.obj = new InstallParams(packageURI, observer, flags,
4507 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004508 mHandler.sendMessage(msg);
4509 }
4510
Christopher Tate1bb69062010-02-19 17:02:12 -08004511 public void finishPackageInstall(int token) {
4512 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4513 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4514 mHandler.sendMessage(msg);
4515 }
4516
Kenny Root93565c4b2010-06-18 15:46:06 -07004517 public void setPackageObbPath(String packageName, String path) {
4518 if (DEBUG_OBB)
4519 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4520 PackageSetting pkgSetting;
4521 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004522 final int permission = mContext.checkCallingPermission(
4523 android.Manifest.permission.INSTALL_PACKAGES);
4524 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004525 synchronized (mPackages) {
4526 pkgSetting = mSettings.mPackages.get(packageName);
4527 if (pkgSetting == null) {
4528 throw new IllegalArgumentException("Unknown package: " + packageName);
4529 }
4530 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4531 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4532 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4533 + pkgSetting.userId);
4534 }
4535 pkgSetting.obbPathString = path;
4536 mSettings.writeLP();
4537 }
4538 }
4539
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004540 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004541 // Queue up an async operation since the package installation may take a little while.
4542 mHandler.post(new Runnable() {
4543 public void run() {
4544 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004545 // Result object to be returned
4546 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004547 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004548 res.uid = -1;
4549 res.pkg = null;
4550 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004551 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004552 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004553 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004554 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004555 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004556 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004557 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004558
4559 // A restore should be performed at this point if (a) the install
4560 // succeeded, (b) the operation is not an update, and (c) the new
4561 // package has a backupAgent defined.
4562 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004563 boolean doRestore = (!update
4564 && res.pkg != null
4565 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004566
4567 // Set up the post-install work request bookkeeping. This will be used
4568 // and cleaned up by the post-install event handling regardless of whether
4569 // there's a restore pass performed. Token values are >= 1.
4570 int token;
4571 if (mNextInstallToken < 0) mNextInstallToken = 1;
4572 token = mNextInstallToken++;
4573
4574 PostInstallData data = new PostInstallData(args, res);
4575 mRunningInstalls.put(token, data);
4576 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4577
4578 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4579 // Pass responsibility to the Backup Manager. It will perform a
4580 // restore if appropriate, then pass responsibility back to the
4581 // Package Manager to run the post-install observer callbacks
4582 // and broadcasts.
4583 IBackupManager bm = IBackupManager.Stub.asInterface(
4584 ServiceManager.getService(Context.BACKUP_SERVICE));
4585 if (bm != null) {
4586 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4587 + " to BM for possible restore");
4588 try {
4589 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4590 } catch (RemoteException e) {
4591 // can't happen; the backup manager is local
4592 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004593 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004594 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004595 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004596 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004597 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004598 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004599 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004600 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004601
4602 if (!doRestore) {
4603 // No restore possible, or the Backup Manager was mysteriously not
4604 // available -- just fire the post-install work request directly.
4605 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4606 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4607 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004609 }
4610 });
4611 }
4612
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004613 abstract class HandlerParams {
4614 final static int MAX_RETRIES = 4;
4615 int retry = 0;
4616 final void startCopy() {
4617 try {
4618 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4619 retry++;
4620 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004621 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004622 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4623 handleServiceError();
4624 return;
4625 } else {
4626 handleStartCopy();
4627 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4628 mHandler.sendEmptyMessage(MCS_UNBIND);
4629 }
4630 } catch (RemoteException e) {
4631 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4632 mHandler.sendEmptyMessage(MCS_RECONNECT);
4633 }
4634 handleReturnCode();
4635 }
4636
4637 final void serviceError() {
4638 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4639 handleServiceError();
4640 handleReturnCode();
4641 }
4642 abstract void handleStartCopy() throws RemoteException;
4643 abstract void handleServiceError();
4644 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004645 }
4646
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004647 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004648 final IPackageInstallObserver observer;
4649 int flags;
4650 final Uri packageURI;
4651 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004652 private InstallArgs mArgs;
4653 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004654 InstallParams(Uri packageURI,
4655 IPackageInstallObserver observer, int flags,
4656 String installerPackageName) {
4657 this.packageURI = packageURI;
4658 this.flags = flags;
4659 this.observer = observer;
4660 this.installerPackageName = installerPackageName;
4661 }
4662
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004663 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4664 String packageName = pkgLite.packageName;
4665 int installLocation = pkgLite.installLocation;
4666 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4667 synchronized (mPackages) {
4668 PackageParser.Package pkg = mPackages.get(packageName);
4669 if (pkg != null) {
4670 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4671 // Check for updated system application.
4672 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4673 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004674 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004675 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4676 }
4677 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4678 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004679 if (onSd) {
4680 // Install flag overrides everything.
4681 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4682 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004683 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004684 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4685 // Application explicitly specified internal.
4686 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4687 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4688 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004689 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004690 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004691 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004692 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4693 }
4694 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004695 }
4696 }
4697 } else {
4698 // Invalid install. Return error code
4699 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4700 }
4701 }
4702 }
4703 // All the special cases have been taken care of.
4704 // Return result based on recommended install location.
4705 if (onSd) {
4706 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4707 }
4708 return pkgLite.recommendedInstallLocation;
4709 }
4710
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004711 /*
4712 * Invoke remote method to get package information and install
4713 * location values. Override install location based on default
4714 * policy if needed and then create install arguments based
4715 * on the install location.
4716 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004717 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004718 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004719 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4720 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004721 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4722 if (onInt && onSd) {
4723 // Check if both bits are set.
4724 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4725 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4726 } else if (fwdLocked && onSd) {
4727 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004728 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004729 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004730 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004731 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004732 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004733 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004734 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4735 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4736 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4737 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4738 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004739 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4740 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4741 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004742 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4743 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004744 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004745 // Override with defaults if needed.
4746 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004747 if (!onSd && !onInt) {
4748 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004749 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4750 // Set the flag to install on external media.
4751 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004752 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004753 } else {
4754 // Make sure the flag for installing on external
4755 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004756 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004757 flags &= ~PackageManager.INSTALL_EXTERNAL;
4758 }
4759 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004760 }
4761 }
4762 // Create the file args now.
4763 mArgs = createInstallArgs(this);
4764 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4765 // Create copy only if we are not in an erroneous state.
4766 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004767 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004768 }
4769 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004770 }
4771
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004772 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004773 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004774 // If mArgs is null, then MCS couldn't be reached. When it
4775 // reconnects, it will try again to install. At that point, this
4776 // will succeed.
4777 if (mArgs != null) {
4778 processPendingInstall(mArgs, mRet);
4779 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004780 }
4781
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004782 @Override
4783 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004784 mArgs = createInstallArgs(this);
4785 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004786 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004787 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004788
4789 /*
4790 * Utility class used in movePackage api.
4791 * srcArgs and targetArgs are not set for invalid flags and make
4792 * sure to do null checks when invoking methods on them.
4793 * We probably want to return ErrorPrams for both failed installs
4794 * and moves.
4795 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004796 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004797 final IPackageMoveObserver observer;
4798 final int flags;
4799 final String packageName;
4800 final InstallArgs srcArgs;
4801 final InstallArgs targetArgs;
4802 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004803
4804 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4805 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004806 this.srcArgs = srcArgs;
4807 this.observer = observer;
4808 this.flags = flags;
4809 this.packageName = packageName;
4810 if (srcArgs != null) {
4811 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004812 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004813 } else {
4814 targetArgs = null;
4815 }
4816 }
4817
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004818 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004819 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4820 // Check for storage space on target medium
4821 if (!targetArgs.checkFreeStorage(mContainerService)) {
4822 Log.w(TAG, "Insufficient storage to install");
4823 return;
4824 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004825 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004826 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004827 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004828 if (DEBUG_SD_INSTALL) {
4829 StringBuilder builder = new StringBuilder();
4830 if (srcArgs != null) {
4831 builder.append("src: ");
4832 builder.append(srcArgs.getCodePath());
4833 }
4834 if (targetArgs != null) {
4835 builder.append(" target : ");
4836 builder.append(targetArgs.getCodePath());
4837 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004838 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004839 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004840 }
4841
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004842 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004843 void handleReturnCode() {
4844 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004845 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4846 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4847 currentStatus = PackageManager.MOVE_SUCCEEDED;
4848 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4849 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4850 }
4851 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004852 }
4853
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004854 @Override
4855 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004856 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004857 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004858 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004859
4860 private InstallArgs createInstallArgs(InstallParams params) {
4861 if (installOnSd(params.flags)) {
4862 return new SdInstallArgs(params);
4863 } else {
4864 return new FileInstallArgs(params);
4865 }
4866 }
4867
Kenny Root85387d72010-08-26 10:13:11 -07004868 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4869 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004870 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004871 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004872 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004873 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004874 }
4875 }
4876
Kenny Root85387d72010-08-26 10:13:11 -07004877 // Used by package mover
4878 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004879 if (installOnSd(flags)) {
4880 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4881 return new SdInstallArgs(packageURI, cid);
4882 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004883 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004884 }
4885 }
4886
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004887 static abstract class InstallArgs {
4888 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004889 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004890 final int flags;
4891 final Uri packageURI;
4892 final String installerPackageName;
4893
4894 InstallArgs(Uri packageURI,
4895 IPackageInstallObserver observer, int flags,
4896 String installerPackageName) {
4897 this.packageURI = packageURI;
4898 this.flags = flags;
4899 this.observer = observer;
4900 this.installerPackageName = installerPackageName;
4901 }
4902
4903 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004904 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004905 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004906 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004907 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004908 abstract String getCodePath();
4909 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004910 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004911 // Need installer lock especially for dex file removal.
4912 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004913 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004914 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004915 }
4916
4917 class FileInstallArgs extends InstallArgs {
4918 File installDir;
4919 String codeFileName;
4920 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004921 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004922 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004923
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004924 FileInstallArgs(InstallParams params) {
4925 super(params.packageURI, params.observer,
4926 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004927 }
4928
Kenny Root85387d72010-08-26 10:13:11 -07004929 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004930 super(null, null, 0, null);
4931 File codeFile = new File(fullCodePath);
4932 installDir = codeFile.getParentFile();
4933 codeFileName = fullCodePath;
4934 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004935 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004936 }
4937
Kenny Root85387d72010-08-26 10:13:11 -07004938 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004939 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004940 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004941 String apkName = getNextCodePath(null, pkgName, ".apk");
4942 codeFileName = new File(installDir, apkName + ".apk").getPath();
4943 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004944 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004945 }
4946
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004947 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4948 return imcs.checkFreeStorage(false, packageURI);
4949 }
4950
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004951 String getCodePath() {
4952 return codeFileName;
4953 }
4954
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004955 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004956 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004957 codeFileName = createTempPackageFile(installDir).getPath();
4958 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004959 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004960 }
4961
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004962 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004963 if (temp) {
4964 // Generate temp file name
4965 createCopyFile();
4966 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004967 // Get a ParcelFileDescriptor to write to the output file
4968 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004969 if (!created) {
4970 try {
4971 codeFile.createNewFile();
4972 // Set permissions
4973 if (!setPermissions()) {
4974 // Failed setting permissions.
4975 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4976 }
4977 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004978 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004979 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4980 }
4981 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004982 ParcelFileDescriptor out = null;
4983 try {
Kenny Root85387d72010-08-26 10:13:11 -07004984 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004985 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004986 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004987 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4988 }
4989 // Copy the resource now
4990 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4991 try {
4992 if (imcs.copyResource(packageURI, out)) {
4993 ret = PackageManager.INSTALL_SUCCEEDED;
4994 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004995 } finally {
4996 try { if (out != null) out.close(); } catch (IOException e) {}
4997 }
Kenny Root85387d72010-08-26 10:13:11 -07004998
4999 if (!temp) {
5000 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5001 }
5002
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005003 return ret;
5004 }
5005
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005006 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005007 if (status != PackageManager.INSTALL_SUCCEEDED) {
5008 cleanUp();
5009 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005010 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005011 }
5012
5013 boolean doRename(int status, final String pkgName, String oldCodePath) {
5014 if (status != PackageManager.INSTALL_SUCCEEDED) {
5015 cleanUp();
5016 return false;
5017 } else {
5018 // Rename based on packageName
5019 File codeFile = new File(getCodePath());
5020 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5021 File desFile = new File(installDir, apkName + ".apk");
5022 if (!codeFile.renameTo(desFile)) {
5023 return false;
5024 }
5025 // Reset paths since the file has been renamed.
5026 codeFileName = desFile.getPath();
5027 resourceFileName = getResourcePathFromCodePath();
5028 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005029 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005030 // Failed setting permissions.
5031 return false;
5032 }
5033 return true;
5034 }
5035 }
5036
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005037 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005038 if (status != PackageManager.INSTALL_SUCCEEDED) {
5039 cleanUp();
5040 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005041 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005042 }
5043
5044 String getResourcePath() {
5045 return resourceFileName;
5046 }
5047
5048 String getResourcePathFromCodePath() {
5049 String codePath = getCodePath();
5050 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5051 String apkNameOnly = getApkName(codePath);
5052 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5053 } else {
5054 return codePath;
5055 }
5056 }
5057
Kenny Root85387d72010-08-26 10:13:11 -07005058 @Override
5059 String getNativeLibraryPath() {
5060 return libraryPath;
5061 }
5062
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 private boolean cleanUp() {
5064 boolean ret = true;
5065 String sourceDir = getCodePath();
5066 String publicSourceDir = getResourcePath();
5067 if (sourceDir != null) {
5068 File sourceFile = new File(sourceDir);
5069 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005070 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005071 ret = false;
5072 }
5073 // Delete application's code and resources
5074 sourceFile.delete();
5075 }
5076 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5077 final File publicSourceFile = new File(publicSourceDir);
5078 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005079 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005080 }
5081 if (publicSourceFile.exists()) {
5082 publicSourceFile.delete();
5083 }
5084 }
5085 return ret;
5086 }
5087
5088 void cleanUpResourcesLI() {
5089 String sourceDir = getCodePath();
5090 if (cleanUp() && mInstaller != null) {
5091 int retCode = mInstaller.rmdex(sourceDir);
5092 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005093 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005094 + " at location "
5095 + sourceDir + ", retcode=" + retCode);
5096 // we don't consider this to be a failure of the core package deletion
5097 }
5098 }
Kenny Root85387d72010-08-26 10:13:11 -07005099 if (libraryPath != null) {
Kenny Root8f7cc022010-09-12 09:04:56 -07005100 NativeLibraryHelper.removeNativeBinariesLI(libraryPath);
Kenny Root85387d72010-08-26 10:13:11 -07005101 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005102 }
5103
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005104 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005105 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005106 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 final int filePermissions =
5108 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5109 |FileUtils.S_IROTH;
5110 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5111 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005112 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005113 getCodePath()
5114 + ". The return code was: " + retCode);
5115 // TODO Define new internal error
5116 return false;
5117 }
5118 return true;
5119 }
5120 return true;
5121 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005122
5123 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005124 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005125 cleanUpResourcesLI();
5126 return true;
5127 }
Kenny Root85387d72010-08-26 10:13:11 -07005128
5129 private boolean isFwdLocked() {
5130 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5131 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005132 }
5133
5134 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005135 static final String RES_FILE_NAME = "pkg.apk";
5136
Kenny Root85387d72010-08-26 10:13:11 -07005137 String cid;
5138 String packagePath;
5139 String libraryPath;
5140
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005141 SdInstallArgs(InstallParams params) {
5142 super(params.packageURI, params.observer,
5143 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005144 }
5145
Kenny Root85387d72010-08-26 10:13:11 -07005146 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005147 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005148 // Extract cid from fullCodePath
5149 int eidx = fullCodePath.lastIndexOf("/");
5150 String subStr1 = fullCodePath.substring(0, eidx);
5151 int sidx = subStr1.lastIndexOf("/");
5152 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005153 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005154 }
5155
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005156 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005157 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5158 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005159 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005160 }
5161
5162 SdInstallArgs(Uri packageURI, String cid) {
5163 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005164 this.cid = cid;
5165 }
5166
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005167 void createCopyFile() {
5168 cid = getTempContainerId();
5169 }
5170
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005171 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5172 return imcs.checkFreeStorage(true, packageURI);
5173 }
5174
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005175 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005176 if (temp) {
5177 createCopyFile();
5178 }
Kenny Root85387d72010-08-26 10:13:11 -07005179 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005180 packageURI, cid,
5181 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005182 if (newCachePath != null) {
5183 setCachePath(newCachePath);
5184 return PackageManager.INSTALL_SUCCEEDED;
5185 } else {
5186 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5187 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005188 }
5189
5190 @Override
5191 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005192 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005193 }
5194
5195 @Override
5196 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005197 return packagePath;
5198 }
5199
5200 @Override
5201 String getNativeLibraryPath() {
5202 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005203 }
5204
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005205 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005206 if (status != PackageManager.INSTALL_SUCCEEDED) {
5207 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005208 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005209 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005210 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005211 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005212 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5213 Process.SYSTEM_UID);
5214 if (newCachePath != null) {
5215 setCachePath(newCachePath);
5216 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005217 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5218 }
5219 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005220 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005221 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005222 }
5223
5224 boolean doRename(int status, final String pkgName,
5225 String oldCodePath) {
5226 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005227 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005228 if (PackageHelper.isContainerMounted(cid)) {
5229 // Unmount the container
5230 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005231 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005232 return false;
5233 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005234 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005235 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005236 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5237 " which might be stale. Will try to clean up.");
5238 // Clean up the stale container and proceed to recreate.
5239 if (!PackageHelper.destroySdDir(newCacheId)) {
5240 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5241 return false;
5242 }
5243 // Successfully cleaned up stale container. Try to rename again.
5244 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5245 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5246 + " inspite of cleaning it up.");
5247 return false;
5248 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005249 }
5250 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005251 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005252 newCachePath = PackageHelper.mountSdDir(newCacheId,
5253 getEncryptKey(), Process.SYSTEM_UID);
5254 } else {
5255 newCachePath = PackageHelper.getSdDir(newCacheId);
5256 }
5257 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005258 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005259 return false;
5260 }
5261 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005262 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005263 " at new path: " + newCachePath);
5264 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005265 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005266 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005267 }
5268
Kenny Root85387d72010-08-26 10:13:11 -07005269 private void setCachePath(String newCachePath) {
5270 File cachePath = new File(newCachePath);
5271 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5272 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5273 }
5274
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005275 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005276 if (status != PackageManager.INSTALL_SUCCEEDED) {
5277 cleanUp();
5278 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005279 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005280 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005281 PackageHelper.mountSdDir(cid,
5282 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005283 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005284 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005285 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005286 }
5287
5288 private void cleanUp() {
5289 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005290 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005291 }
5292
5293 void cleanUpResourcesLI() {
5294 String sourceFile = getCodePath();
5295 // Remove dex file
5296 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005297 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005298 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005299 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005300 + " at location "
5301 + sourceFile.toString() + ", retcode=" + retCode);
5302 // we don't consider this to be a failure of the core package deletion
5303 }
5304 }
5305 cleanUp();
5306 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005307
5308 boolean matchContainer(String app) {
5309 if (cid.startsWith(app)) {
5310 return true;
5311 }
5312 return false;
5313 }
5314
5315 String getPackageName() {
5316 int idx = cid.lastIndexOf("-");
5317 if (idx == -1) {
5318 return cid;
5319 }
5320 return cid.substring(0, idx);
5321 }
5322
5323 boolean doPostDeleteLI(boolean delete) {
5324 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005325 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005326 if (mounted) {
5327 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005328 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005329 }
5330 if (ret && delete) {
5331 cleanUpResourcesLI();
5332 }
5333 return ret;
5334 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005335 };
5336
5337 // Utility method used to create code paths based on package name and available index.
5338 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5339 String idxStr = "";
5340 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005341 // Fall back to default value of idx=1 if prefix is not
5342 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005343 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005344 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005345 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005346 if (subStr.endsWith(suffix)) {
5347 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005348 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005349 // If oldCodePath already contains prefix find out the
5350 // ending index to either increment or decrement.
5351 int sidx = subStr.lastIndexOf(prefix);
5352 if (sidx != -1) {
5353 subStr = subStr.substring(sidx + prefix.length());
5354 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005355 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5356 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005357 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005358 try {
5359 idx = Integer.parseInt(subStr);
5360 if (idx <= 1) {
5361 idx++;
5362 } else {
5363 idx--;
5364 }
5365 } catch(NumberFormatException e) {
5366 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005367 }
5368 }
5369 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005370 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 return prefix + idxStr;
5372 }
5373
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005374 // Utility method used to ignore ADD/REMOVE events
5375 // by directory observer.
5376 private static boolean ignoreCodePath(String fullPathStr) {
5377 String apkName = getApkName(fullPathStr);
5378 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5379 if (idx != -1 && ((idx+1) < apkName.length())) {
5380 // Make sure the package ends with a numeral
5381 String version = apkName.substring(idx+1);
5382 try {
5383 Integer.parseInt(version);
5384 return true;
5385 } catch (NumberFormatException e) {}
5386 }
5387 return false;
5388 }
5389
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005390 // Utility method that returns the relative package path with respect
5391 // to the installation directory. Like say for /data/data/com.test-1.apk
5392 // string com.test-1 is returned.
5393 static String getApkName(String codePath) {
5394 if (codePath == null) {
5395 return null;
5396 }
5397 int sidx = codePath.lastIndexOf("/");
5398 int eidx = codePath.lastIndexOf(".");
5399 if (eidx == -1) {
5400 eidx = codePath.length();
5401 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005402 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005403 return null;
5404 }
5405 return codePath.substring(sidx+1, eidx);
5406 }
5407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005408 class PackageInstalledInfo {
5409 String name;
5410 int uid;
5411 PackageParser.Package pkg;
5412 int returnCode;
5413 PackageRemovedInfo removedInfo;
5414 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005416 /*
5417 * Install a non-existing package.
5418 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005419 private void installNewPackageLI(PackageParser.Package pkg,
5420 int parseFlags,
5421 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005422 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005424 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005425
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005426 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 res.name = pkgName;
5428 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005429 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5430 // A package with the same name is already installed, though
5431 // it has been renamed to an older name. The package we
5432 // are trying to install should be installed as an update to
5433 // the existing one, but that has not been requested, so bail.
5434 Slog.w(TAG, "Attempt to re-install " + pkgName
5435 + " without first uninstalling package running as "
5436 + mSettings.mRenamedPackages.get(pkgName));
5437 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5438 return;
5439 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005440 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005441 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005442 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 + " without first uninstalling.");
5444 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5445 return;
5446 }
5447 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005449 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005451 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5453 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5454 }
5455 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005456 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005457 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 res);
5459 // delete the partially installed application. the data directory will have to be
5460 // restored if it was already existing
5461 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5462 // remove package from internal structures. Note that we want deletePackageX to
5463 // delete the package data and cache directories that it created in
5464 // scanPackageLocked, unless those directories existed before we even tried to
5465 // install.
5466 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005467 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5469 res.removedInfo);
5470 }
5471 }
5472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005473
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005474 private void replacePackageLI(PackageParser.Package pkg,
5475 int parseFlags,
5476 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005477 String installerPackageName, PackageInstalledInfo res) {
5478
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005479 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005480 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005481 // First find the old package info and check signatures
5482 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005483 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005484 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005485 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005486 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5487 return;
5488 }
5489 }
Kenny Root85387d72010-08-26 10:13:11 -07005490 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005491 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005492 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005493 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005494 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 }
5496 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005499 PackageParser.Package pkg,
5500 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005501 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502 PackageParser.Package newPackage = null;
5503 String pkgName = deletedPackage.packageName;
5504 boolean deletedPkg = true;
5505 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005506
Jacek Surazski65e13172009-04-28 15:26:38 +02005507 String oldInstallerPackageName = null;
5508 synchronized (mPackages) {
5509 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005513 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 res.removedInfo)) {
5515 // If the existing package was'nt successfully deleted
5516 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5517 deletedPkg = false;
5518 } else {
5519 // Successfully deleted the old package. Now proceed with re-installation
5520 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005521 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005523 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5525 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005526 }
5527 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005528 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005529 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 res);
5531 updatedSettings = true;
5532 }
5533 }
5534
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005535 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005536 // remove package from internal structures. Note that we want deletePackageX to
5537 // delete the package data and cache directories that it created in
5538 // scanPackageLocked, unless those directories existed before we even tried to
5539 // install.
5540 if(updatedSettings) {
5541 deletePackageLI(
5542 pkgName, true,
5543 PackageManager.DONT_DELETE_DATA,
5544 res.removedInfo);
5545 }
5546 // Since we failed to install the new package we need to restore the old
5547 // package that we deleted.
5548 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005549 File restoreFile = new File(deletedPackage.mPath);
5550 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005551 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005552 return;
5553 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005554 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005555 boolean oldOnSd = isExternal(deletedPackage);
5556 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5557 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5558 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5559 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5560 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5561 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5562 return;
5563 }
5564 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005565 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005566 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005567 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005568 mSettings.writeLP();
5569 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005570 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005571 }
5572 }
5573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005576 PackageParser.Package pkg,
5577 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005578 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 PackageParser.Package newPackage = null;
5580 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005581 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005582 PackageParser.PARSE_IS_SYSTEM;
5583 String packageName = deletedPackage.packageName;
5584 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5585 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005586 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005587 return;
5588 }
5589 PackageParser.Package oldPkg;
5590 PackageSetting oldPkgSetting;
5591 synchronized (mPackages) {
5592 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005593 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5595 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005596 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 return;
5598 }
5599 }
5600 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5601 res.removedInfo.removedPackage = packageName;
5602 // Remove existing system package
5603 removePackageLI(oldPkg, true);
5604 synchronized (mPackages) {
5605 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5606 }
5607
5608 // Successfully disabled the old package. Now proceed with re-installation
5609 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5610 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005611 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005613 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5615 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5616 }
5617 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005618 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 updatedSettings = true;
5620 }
5621
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005622 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 // Re installation failed. Restore old information
5624 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005625 if (newPackage != null) {
5626 removePackageLI(newPackage, true);
5627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005629 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005631 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 // Restore the old system information in Settings
5633 synchronized(mPackages) {
5634 if(updatedSettings) {
5635 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005636 mSettings.setInstallerPackageName(packageName,
5637 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 }
5639 mSettings.writeLP();
5640 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005641 } else {
5642 // If this is an update to an existing update, setup
5643 // to remove the existing update.
5644 synchronized (mPackages) {
5645 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5646 if (ps != null && ps.codePathString != null &&
5647 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5648 int installFlags = 0;
5649 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005650 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005651 }
5652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 }
5654 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005655
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005656 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005657 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005658 int retCode;
5659 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5660 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5661 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005662 if (mNoDexOpt) {
5663 /*
5664 * If we're in an engineering build, programs are lazily run
5665 * through dexopt. If the .dex file doesn't exist yet, it
5666 * will be created when the program is run next.
5667 */
5668 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5669 } else {
5670 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5671 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5672 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005673 }
5674 }
5675 return PackageManager.INSTALL_SUCCEEDED;
5676 }
5677
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005678 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005679 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005680 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 synchronized (mPackages) {
5682 //write settings. the installStatus will be incomplete at this stage.
5683 //note that the new package setting would have already been
5684 //added to mPackages. It hasn't been persisted yet.
5685 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5686 mSettings.writeLP();
5687 }
5688
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005689 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005690 != PackageManager.INSTALL_SUCCEEDED) {
5691 // Discontinue if moving dex files failed.
5692 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005693 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005694 if((res.returnCode = setPermissionsLI(newPackage))
5695 != PackageManager.INSTALL_SUCCEEDED) {
5696 if (mInstaller != null) {
5697 mInstaller.rmdex(newPackage.mScanPath);
5698 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005699 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005700 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005701 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005703 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005704 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005705 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 res.name = pkgName;
5707 res.uid = newPackage.applicationInfo.uid;
5708 res.pkg = newPackage;
5709 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005710 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005711 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5712 //to update install status
5713 mSettings.writeLP();
5714 }
5715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005716
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005717 private void installPackageLI(InstallArgs args,
5718 boolean newInstall, PackageInstalledInfo res) {
5719 int pFlags = args.flags;
5720 String installerPackageName = args.installerPackageName;
5721 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005722 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005723 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005724 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005725 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005726 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005727 // Result object to be returned
5728 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5729
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005730 // Retrieve PackageSettings and parse package
5731 int parseFlags = PackageParser.PARSE_CHATTY |
5732 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5733 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5734 parseFlags |= mDefParseFlags;
5735 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5736 pp.setSeparateProcesses(mSeparateProcesses);
5737 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5738 null, mMetrics, parseFlags);
5739 if (pkg == null) {
5740 res.returnCode = pp.getParseError();
5741 return;
5742 }
5743 String pkgName = res.name = pkg.packageName;
5744 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5745 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5746 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5747 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005749 }
5750 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5751 res.returnCode = pp.getParseError();
5752 return;
5753 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005754 // Get rid of all references to package scan path via parser.
5755 pp = null;
5756 String oldCodePath = null;
5757 boolean systemApp = false;
5758 synchronized (mPackages) {
5759 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005760 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5761 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005762 if (pkg.mOriginalPackages != null
5763 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005764 && mPackages.containsKey(oldName)) {
5765 // This package is derived from an original package,
5766 // and this device has been updating from that original
5767 // name. We must continue using the original name, so
5768 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005769 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005770 pkgName = pkg.packageName;
5771 replace = true;
5772 } else if (mPackages.containsKey(pkgName)) {
5773 // This package, under its official name, already exists
5774 // on the device; we should replace it.
5775 replace = true;
5776 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005777 }
5778 PackageSetting ps = mSettings.mPackages.get(pkgName);
5779 if (ps != null) {
5780 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5781 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5782 systemApp = (ps.pkg.applicationInfo.flags &
5783 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005784 }
5785 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005786 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005787
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005788 if (systemApp && onSd) {
5789 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005790 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005791 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5792 return;
5793 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005794
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005795 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5796 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5797 return;
5798 }
5799 // Set application objects path explicitly after the rename
5800 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005801 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005802 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005803 replacePackageLI(pkg, parseFlags, scanMode,
5804 installerPackageName, res);
5805 } else {
5806 installNewPackageLI(pkg, parseFlags, scanMode,
5807 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 }
5809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005810
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005811 private int setPermissionsLI(PackageParser.Package newPackage) {
5812 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005813 int retCode = 0;
5814 // TODO Gross hack but fix later. Ideally move this to be a post installation
5815 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005816 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005817 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005818 try {
5819 extractPublicFiles(newPackage, destResourceFile);
5820 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005821 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 -08005822 " forward-locked app.");
5823 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5824 } finally {
5825 //TODO clean up the extracted public files
5826 }
5827 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005828 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 newPackage.applicationInfo.uid);
5830 } else {
5831 final int filePermissions =
5832 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005833 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005834 newPackage.applicationInfo.uid);
5835 }
5836 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005837 // The permissions on the resource file was set when it was copied for
5838 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005842 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005843 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005845 // TODO Define new internal error
5846 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 }
5848 return PackageManager.INSTALL_SUCCEEDED;
5849 }
5850
Kenny Root85387d72010-08-26 10:13:11 -07005851 private static boolean isForwardLocked(PackageParser.Package pkg) {
5852 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005853 }
5854
Kenny Root85387d72010-08-26 10:13:11 -07005855 private static boolean isExternal(PackageParser.Package pkg) {
5856 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5857 }
5858
5859 private static boolean isSystemApp(PackageParser.Package pkg) {
5860 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5861 }
5862
5863 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5864 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005865 }
5866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 private void extractPublicFiles(PackageParser.Package newPackage,
5868 File publicZipFile) throws IOException {
5869 final ZipOutputStream publicZipOutStream =
5870 new ZipOutputStream(new FileOutputStream(publicZipFile));
5871 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5872
5873 // Copy manifest, resources.arsc and res directory to public zip
5874
5875 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5876 while (privateZipEntries.hasMoreElements()) {
5877 final ZipEntry zipEntry = privateZipEntries.nextElement();
5878 final String zipEntryName = zipEntry.getName();
5879 if ("AndroidManifest.xml".equals(zipEntryName)
5880 || "resources.arsc".equals(zipEntryName)
5881 || zipEntryName.startsWith("res/")) {
5882 try {
5883 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5884 } catch (IOException e) {
5885 try {
5886 publicZipOutStream.close();
5887 throw e;
5888 } finally {
5889 publicZipFile.delete();
5890 }
5891 }
5892 }
5893 }
5894
5895 publicZipOutStream.close();
5896 FileUtils.setPermissions(
5897 publicZipFile.getAbsolutePath(),
5898 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5899 -1, -1);
5900 }
5901
5902 private static void copyZipEntry(ZipEntry zipEntry,
5903 ZipFile inZipFile,
5904 ZipOutputStream outZipStream) throws IOException {
5905 byte[] buffer = new byte[4096];
5906 int num;
5907
5908 ZipEntry newEntry;
5909 if (zipEntry.getMethod() == ZipEntry.STORED) {
5910 // Preserve the STORED method of the input entry.
5911 newEntry = new ZipEntry(zipEntry);
5912 } else {
5913 // Create a new entry so that the compressed len is recomputed.
5914 newEntry = new ZipEntry(zipEntry.getName());
5915 }
5916 outZipStream.putNextEntry(newEntry);
5917
5918 InputStream data = inZipFile.getInputStream(zipEntry);
5919 while ((num = data.read(buffer)) > 0) {
5920 outZipStream.write(buffer, 0, num);
5921 }
5922 outZipStream.flush();
5923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 private void deleteTempPackageFiles() {
5926 FilenameFilter filter = new FilenameFilter() {
5927 public boolean accept(File dir, String name) {
5928 return name.startsWith("vmdl") && name.endsWith(".tmp");
5929 }
5930 };
5931 String tmpFilesList[] = mAppInstallDir.list(filter);
5932 if(tmpFilesList == null) {
5933 return;
5934 }
5935 for(int i = 0; i < tmpFilesList.length; i++) {
5936 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5937 tmpFile.delete();
5938 }
5939 }
5940
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005941 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 File tmpPackageFile;
5943 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005944 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005946 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 return null;
5948 }
5949 try {
5950 FileUtils.setPermissions(
5951 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5952 -1, -1);
5953 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005954 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005955 return null;
5956 }
5957 return tmpPackageFile;
5958 }
5959
5960 public void deletePackage(final String packageName,
5961 final IPackageDeleteObserver observer,
5962 final int flags) {
5963 mContext.enforceCallingOrSelfPermission(
5964 android.Manifest.permission.DELETE_PACKAGES, null);
5965 // Queue up an async operation since the package deletion may take a little while.
5966 mHandler.post(new Runnable() {
5967 public void run() {
5968 mHandler.removeCallbacks(this);
5969 final boolean succeded = deletePackageX(packageName, true, true, flags);
5970 if (observer != null) {
5971 try {
5972 observer.packageDeleted(succeded);
5973 } catch (RemoteException e) {
5974 Log.i(TAG, "Observer no longer exists.");
5975 } //end catch
5976 } //end if
5977 } //end run
5978 });
5979 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005981 /**
5982 * This method is an internal method that could be get invoked either
5983 * to delete an installed package or to clean up a failed installation.
5984 * After deleting an installed package, a broadcast is sent to notify any
5985 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005986 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005987 * installation wouldn't have sent the initial broadcast either
5988 * The key steps in deleting a package are
5989 * deleting the package information in internal structures like mPackages,
5990 * deleting the packages base directories through installd
5991 * updating mSettings to reflect current status
5992 * persisting settings for later use
5993 * sending a broadcast if necessary
5994 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5996 boolean deleteCodeAndResources, int flags) {
5997 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07005998 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006000 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6001 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6002 try {
6003 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006004 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006005 return false;
6006 }
6007 } catch (RemoteException e) {
6008 }
6009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006011 res = deletePackageLI(packageName, deleteCodeAndResources,
6012 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006016 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006017 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006018
6019 // If the removed package was a system update, the old system packaged
6020 // was re-enabled; we need to broadcast this information
6021 if (systemUpdate) {
6022 Bundle extras = new Bundle(1);
6023 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6024 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6025
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006026 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6027 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006030 // Force a gc here.
6031 Runtime.getRuntime().gc();
6032 // Delete the resources here after sending the broadcast to let
6033 // other processes clean up before deleting resources.
6034 if (info.args != null) {
6035 synchronized (mInstallLock) {
6036 info.args.doPostDeleteLI(deleteCodeAndResources);
6037 }
6038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 return res;
6040 }
6041
6042 static class PackageRemovedInfo {
6043 String removedPackage;
6044 int uid = -1;
6045 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006046 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006047 // Clean up resources deleted packages.
6048 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006049
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006050 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006051 Bundle extras = new Bundle(1);
6052 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6053 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6054 if (replacing) {
6055 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6056 }
6057 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006058 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 }
6060 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006061 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 }
6063 }
6064 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006065
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 /*
6067 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6068 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006069 * 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 -08006070 * delete a partially installed application.
6071 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006072 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006073 int flags) {
6074 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006075 if (outInfo != null) {
6076 outInfo.removedPackage = packageName;
6077 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006078 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 // Retrieve object to delete permissions for shared user later on
6080 PackageSetting deletedPs;
6081 synchronized (mPackages) {
6082 deletedPs = mSettings.mPackages.get(packageName);
6083 }
6084 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006085 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006087 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006089 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006090 + packageName + ", retcode=" + retCode);
6091 // we don't consider this to be a failure of the core package deletion
6092 }
6093 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006094 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006095 PackageParser.Package pkg = mPackages.get(packageName);
6096 File dataDir = new File(pkg.applicationInfo.dataDir);
6097 dataDir.delete();
6098 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006099 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 }
6101 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006102 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006103 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6104 if (outInfo != null) {
6105 outInfo.removedUid = mSettings.removePackageLP(packageName);
6106 }
6107 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006108 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006109 if (deletedPs.sharedUser != null) {
6110 // remove permissions associated with package
6111 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6112 }
6113 }
6114 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006115 // remove from preferred activities.
6116 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6117 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6118 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6119 removed.add(pa);
6120 }
6121 }
6122 for (PreferredActivity pa : removed) {
6123 mSettings.mPreferredActivities.removeFilter(pa);
6124 }
6125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006127 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 }
6129 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 /*
6132 * Tries to delete system package.
6133 */
6134 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006135 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006136 ApplicationInfo applicationInfo = p.applicationInfo;
6137 //applicable for non-partially installed applications only
6138 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006139 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140 return false;
6141 }
6142 PackageSetting ps = null;
6143 // Confirm if the system package has been updated
6144 // An updated system app can be deleted. This will also have to restore
6145 // the system pkg from system partition
6146 synchronized (mPackages) {
6147 ps = mSettings.getDisabledSystemPkg(p.packageName);
6148 }
6149 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006150 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 return false;
6152 } else {
6153 Log.i(TAG, "Deleting system pkg from data partition");
6154 }
6155 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006156 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006157 final boolean deleteCodeAndResources;
6158 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006159 // Delete code and resources for downgrades
6160 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006161 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006162 } else {
6163 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006164 deleteCodeAndResources = false;
6165 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6168 if (!ret) {
6169 return false;
6170 }
6171 synchronized (mPackages) {
6172 // Reinstate the old system package
6173 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006174 // Remove any native libraries from the upgraded package.
6175 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006176 }
6177 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006178 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006180 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006183 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 return false;
6185 }
6186 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006187 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 mSettings.writeLP();
6189 }
6190 return true;
6191 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006193 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6194 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6195 ApplicationInfo applicationInfo = p.applicationInfo;
6196 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006197 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 return false;
6199 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006200 if (outInfo != null) {
6201 outInfo.uid = applicationInfo.uid;
6202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203
6204 // Delete package data from internal structures and also remove data if flag is set
6205 removePackageDataLI(p, outInfo, flags);
6206
6207 // Delete application code and resources
6208 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006209 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006210 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6211 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6212 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6213 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 }
6215 return true;
6216 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006217
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 /*
6219 * This method handles package deletion in general
6220 */
6221 private boolean deletePackageLI(String packageName,
6222 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6223 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006224 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 return false;
6226 }
6227 PackageParser.Package p;
6228 boolean dataOnly = false;
6229 synchronized (mPackages) {
6230 p = mPackages.get(packageName);
6231 if (p == null) {
6232 //this retrieves partially installed apps
6233 dataOnly = true;
6234 PackageSetting ps = mSettings.mPackages.get(packageName);
6235 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006236 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 return false;
6238 }
6239 p = ps.pkg;
6240 }
6241 }
6242 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006243 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 return false;
6245 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 if (dataOnly) {
6248 // Delete application data first
6249 removePackageDataLI(p, outInfo, flags);
6250 return true;
6251 }
6252 // At this point the package should have ApplicationInfo associated with it
6253 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006254 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 return false;
6256 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006257 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006258 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 Log.i(TAG, "Removing system package:"+p.packageName);
6260 // When an updated system application is deleted we delete the existing resources as well and
6261 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006262 ret = deleteSystemPackageLI(p, flags, outInfo);
6263 } else {
6264 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006265 // Kill application pre-emptively especially for apps on sd.
6266 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006267 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006269 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006270 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 public void clearApplicationUserData(final String packageName,
6273 final IPackageDataObserver observer) {
6274 mContext.enforceCallingOrSelfPermission(
6275 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6276 // Queue up an async operation since the package deletion may take a little while.
6277 mHandler.post(new Runnable() {
6278 public void run() {
6279 mHandler.removeCallbacks(this);
6280 final boolean succeeded;
6281 synchronized (mInstallLock) {
6282 succeeded = clearApplicationUserDataLI(packageName);
6283 }
6284 if (succeeded) {
6285 // invoke DeviceStorageMonitor's update method to clear any notifications
6286 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6287 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6288 if (dsm != null) {
6289 dsm.updateMemory();
6290 }
6291 }
6292 if(observer != null) {
6293 try {
6294 observer.onRemoveCompleted(packageName, succeeded);
6295 } catch (RemoteException e) {
6296 Log.i(TAG, "Observer no longer exists.");
6297 }
6298 } //end if observer
6299 } //end run
6300 });
6301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 private boolean clearApplicationUserDataLI(String packageName) {
6304 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006305 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 return false;
6307 }
6308 PackageParser.Package p;
6309 boolean dataOnly = false;
6310 synchronized (mPackages) {
6311 p = mPackages.get(packageName);
6312 if(p == null) {
6313 dataOnly = true;
6314 PackageSetting ps = mSettings.mPackages.get(packageName);
6315 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006316 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 return false;
6318 }
6319 p = ps.pkg;
6320 }
6321 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006322 boolean useEncryptedFSDir = false;
6323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 if(!dataOnly) {
6325 //need to check this only for fully installed applications
6326 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006327 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 return false;
6329 }
6330 final ApplicationInfo applicationInfo = p.applicationInfo;
6331 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006332 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 return false;
6334 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006335 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 }
6337 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006338 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006339 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006340 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 + packageName);
6342 return false;
6343 }
6344 }
6345 return true;
6346 }
6347
6348 public void deleteApplicationCacheFiles(final String packageName,
6349 final IPackageDataObserver observer) {
6350 mContext.enforceCallingOrSelfPermission(
6351 android.Manifest.permission.DELETE_CACHE_FILES, null);
6352 // Queue up an async operation since the package deletion may take a little while.
6353 mHandler.post(new Runnable() {
6354 public void run() {
6355 mHandler.removeCallbacks(this);
6356 final boolean succeded;
6357 synchronized (mInstallLock) {
6358 succeded = deleteApplicationCacheFilesLI(packageName);
6359 }
6360 if(observer != null) {
6361 try {
6362 observer.onRemoveCompleted(packageName, succeded);
6363 } catch (RemoteException e) {
6364 Log.i(TAG, "Observer no longer exists.");
6365 }
6366 } //end if observer
6367 } //end run
6368 });
6369 }
6370
6371 private boolean deleteApplicationCacheFilesLI(String packageName) {
6372 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006373 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 return false;
6375 }
6376 PackageParser.Package p;
6377 synchronized (mPackages) {
6378 p = mPackages.get(packageName);
6379 }
6380 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006381 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 return false;
6383 }
6384 final ApplicationInfo applicationInfo = p.applicationInfo;
6385 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006386 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006387 return false;
6388 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006389 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006391 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006393 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 + packageName);
6395 return false;
6396 }
6397 }
6398 return true;
6399 }
6400
6401 public void getPackageSizeInfo(final String packageName,
6402 final IPackageStatsObserver observer) {
6403 mContext.enforceCallingOrSelfPermission(
6404 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6405 // Queue up an async operation since the package deletion may take a little while.
6406 mHandler.post(new Runnable() {
6407 public void run() {
6408 mHandler.removeCallbacks(this);
6409 PackageStats lStats = new PackageStats(packageName);
6410 final boolean succeded;
6411 synchronized (mInstallLock) {
6412 succeded = getPackageSizeInfoLI(packageName, lStats);
6413 }
6414 if(observer != null) {
6415 try {
6416 observer.onGetStatsCompleted(lStats, succeded);
6417 } catch (RemoteException e) {
6418 Log.i(TAG, "Observer no longer exists.");
6419 }
6420 } //end if observer
6421 } //end run
6422 });
6423 }
6424
6425 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6426 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006427 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 return false;
6429 }
6430 PackageParser.Package p;
6431 boolean dataOnly = false;
6432 synchronized (mPackages) {
6433 p = mPackages.get(packageName);
6434 if(p == null) {
6435 dataOnly = true;
6436 PackageSetting ps = mSettings.mPackages.get(packageName);
6437 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006438 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 return false;
6440 }
6441 p = ps.pkg;
6442 }
6443 }
6444 String publicSrcDir = null;
6445 if(!dataOnly) {
6446 final ApplicationInfo applicationInfo = p.applicationInfo;
6447 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006448 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 return false;
6450 }
6451 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6452 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006453 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 if (mInstaller != null) {
6455 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006456 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 if (res < 0) {
6458 return false;
6459 } else {
6460 return true;
6461 }
6462 }
6463 return true;
6464 }
6465
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006468 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 }
6470
6471 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006472 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 }
6474
6475 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006476 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 }
6478
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006479 int getUidTargetSdkVersionLockedLP(int uid) {
6480 Object obj = mSettings.getUserIdLP(uid);
6481 if (obj instanceof SharedUserSetting) {
6482 SharedUserSetting sus = (SharedUserSetting)obj;
6483 final int N = sus.packages.size();
6484 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6485 Iterator<PackageSetting> it = sus.packages.iterator();
6486 int i=0;
6487 while (it.hasNext()) {
6488 PackageSetting ps = it.next();
6489 if (ps.pkg != null) {
6490 int v = ps.pkg.applicationInfo.targetSdkVersion;
6491 if (v < vers) vers = v;
6492 }
6493 }
6494 return vers;
6495 } else if (obj instanceof PackageSetting) {
6496 PackageSetting ps = (PackageSetting)obj;
6497 if (ps.pkg != null) {
6498 return ps.pkg.applicationInfo.targetSdkVersion;
6499 }
6500 }
6501 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6502 }
6503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 public void addPreferredActivity(IntentFilter filter, int match,
6505 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006507 if (mContext.checkCallingOrSelfPermission(
6508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6509 != PackageManager.PERMISSION_GRANTED) {
6510 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6511 < Build.VERSION_CODES.FROYO) {
6512 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6513 + Binder.getCallingUid());
6514 return;
6515 }
6516 mContext.enforceCallingOrSelfPermission(
6517 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6518 }
6519
6520 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006521 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6522 mSettings.mPreferredActivities.addFilter(
6523 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006524 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 }
6526 }
6527
Satish Sampath8dbe6122009-06-02 23:35:54 +01006528 public void replacePreferredActivity(IntentFilter filter, int match,
6529 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006530 if (filter.countActions() != 1) {
6531 throw new IllegalArgumentException(
6532 "replacePreferredActivity expects filter to have only 1 action.");
6533 }
6534 if (filter.countCategories() != 1) {
6535 throw new IllegalArgumentException(
6536 "replacePreferredActivity expects filter to have only 1 category.");
6537 }
6538 if (filter.countDataAuthorities() != 0
6539 || filter.countDataPaths() != 0
6540 || filter.countDataSchemes() != 0
6541 || filter.countDataTypes() != 0) {
6542 throw new IllegalArgumentException(
6543 "replacePreferredActivity expects filter to have no data authorities, " +
6544 "paths, schemes or types.");
6545 }
6546 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006547 if (mContext.checkCallingOrSelfPermission(
6548 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6549 != PackageManager.PERMISSION_GRANTED) {
6550 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6551 < Build.VERSION_CODES.FROYO) {
6552 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6553 + Binder.getCallingUid());
6554 return;
6555 }
6556 mContext.enforceCallingOrSelfPermission(
6557 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6558 }
6559
Satish Sampath8dbe6122009-06-02 23:35:54 +01006560 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6561 String action = filter.getAction(0);
6562 String category = filter.getCategory(0);
6563 while (it.hasNext()) {
6564 PreferredActivity pa = it.next();
6565 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6566 it.remove();
6567 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6568 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6569 }
6570 }
6571 addPreferredActivity(filter, match, set, activity);
6572 }
6573 }
6574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006575 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006576 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006577 int uid = Binder.getCallingUid();
6578 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006579 if (pkg == null || pkg.applicationInfo.uid != uid) {
6580 if (mContext.checkCallingOrSelfPermission(
6581 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6582 != PackageManager.PERMISSION_GRANTED) {
6583 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6584 < Build.VERSION_CODES.FROYO) {
6585 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6586 + Binder.getCallingUid());
6587 return;
6588 }
6589 mContext.enforceCallingOrSelfPermission(
6590 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6591 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006592 }
6593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006595 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 }
6597 }
6598 }
6599
6600 boolean clearPackagePreferredActivitiesLP(String packageName) {
6601 boolean changed = false;
6602 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6603 while (it.hasNext()) {
6604 PreferredActivity pa = it.next();
6605 if (pa.mActivity.getPackageName().equals(packageName)) {
6606 it.remove();
6607 changed = true;
6608 }
6609 }
6610 return changed;
6611 }
6612
6613 public int getPreferredActivities(List<IntentFilter> outFilters,
6614 List<ComponentName> outActivities, String packageName) {
6615
6616 int num = 0;
6617 synchronized (mPackages) {
6618 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6619 while (it.hasNext()) {
6620 PreferredActivity pa = it.next();
6621 if (packageName == null
6622 || pa.mActivity.getPackageName().equals(packageName)) {
6623 if (outFilters != null) {
6624 outFilters.add(new IntentFilter(pa));
6625 }
6626 if (outActivities != null) {
6627 outActivities.add(pa.mActivity);
6628 }
6629 }
6630 }
6631 }
6632
6633 return num;
6634 }
6635
6636 public void setApplicationEnabledSetting(String appPackageName,
6637 int newState, int flags) {
6638 setEnabledSetting(appPackageName, null, newState, flags);
6639 }
6640
6641 public void setComponentEnabledSetting(ComponentName componentName,
6642 int newState, int flags) {
6643 setEnabledSetting(componentName.getPackageName(),
6644 componentName.getClassName(), newState, flags);
6645 }
6646
6647 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006648 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006649 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6650 || newState == COMPONENT_ENABLED_STATE_ENABLED
6651 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6652 throw new IllegalArgumentException("Invalid new component state: "
6653 + newState);
6654 }
6655 PackageSetting pkgSetting;
6656 final int uid = Binder.getCallingUid();
6657 final int permission = mContext.checkCallingPermission(
6658 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6659 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006660 boolean sendNow = false;
6661 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006662 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006663 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006664 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006666 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006668 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006670 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 }
6672 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006673 "Unknown component: " + packageName
6674 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 }
6676 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6677 throw new SecurityException(
6678 "Permission Denial: attempt to change component state from pid="
6679 + Binder.getCallingPid()
6680 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6681 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006682 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006684 if (pkgSetting.enabled == newState) {
6685 // Nothing to do
6686 return;
6687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006689 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 } else {
6691 // We're dealing with a component level state change
6692 switch (newState) {
6693 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006694 if (!pkgSetting.enableComponentLP(className)) {
6695 return;
6696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 break;
6698 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006699 if (!pkgSetting.disableComponentLP(className)) {
6700 return;
6701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 break;
6703 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006704 if (!pkgSetting.restoreComponentLP(className)) {
6705 return;
6706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 break;
6708 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006709 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006710 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 }
6712 }
6713 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006714 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006715 components = mPendingBroadcasts.get(packageName);
6716 boolean newPackage = components == null;
6717 if (newPackage) {
6718 components = new ArrayList<String>();
6719 }
6720 if (!components.contains(componentName)) {
6721 components.add(componentName);
6722 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006723 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6724 sendNow = true;
6725 // Purge entry from pending broadcast list if another one exists already
6726 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006727 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006728 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006729 if (newPackage) {
6730 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006731 }
6732 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6733 // Schedule a message
6734 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6735 }
6736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006739 long callingId = Binder.clearCallingIdentity();
6740 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006741 if (sendNow) {
6742 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006743 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 } finally {
6746 Binder.restoreCallingIdentity(callingId);
6747 }
6748 }
6749
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006750 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006751 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6752 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6753 + " components=" + componentNames);
6754 Bundle extras = new Bundle(4);
6755 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6756 String nameList[] = new String[componentNames.size()];
6757 componentNames.toArray(nameList);
6758 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006759 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6760 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006761 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006762 }
6763
Jacek Surazski65e13172009-04-28 15:26:38 +02006764 public String getInstallerPackageName(String packageName) {
6765 synchronized (mPackages) {
6766 PackageSetting pkg = mSettings.mPackages.get(packageName);
6767 if (pkg == null) {
6768 throw new IllegalArgumentException("Unknown package: " + packageName);
6769 }
6770 return pkg.installerPackageName;
6771 }
6772 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006774 public int getApplicationEnabledSetting(String appPackageName) {
6775 synchronized (mPackages) {
6776 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6777 if (pkg == null) {
6778 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6779 }
6780 return pkg.enabled;
6781 }
6782 }
6783
6784 public int getComponentEnabledSetting(ComponentName componentName) {
6785 synchronized (mPackages) {
6786 final String packageNameStr = componentName.getPackageName();
6787 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6788 if (pkg == null) {
6789 throw new IllegalArgumentException("Unknown component: " + componentName);
6790 }
6791 final String classNameStr = componentName.getClassName();
6792 return pkg.currentEnabledStateLP(classNameStr);
6793 }
6794 }
6795
6796 public void enterSafeMode() {
6797 if (!mSystemReady) {
6798 mSafeMode = true;
6799 }
6800 }
6801
6802 public void systemReady() {
6803 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006804
6805 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006806 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006807 mContext.getContentResolver(),
6808 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006809 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006810 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006811 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006812 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006813 }
6814
6815 public boolean isSafeMode() {
6816 return mSafeMode;
6817 }
6818
6819 public boolean hasSystemUidErrors() {
6820 return mHasSystemUidErrors;
6821 }
6822
6823 static String arrayToString(int[] array) {
6824 StringBuffer buf = new StringBuffer(128);
6825 buf.append('[');
6826 if (array != null) {
6827 for (int i=0; i<array.length; i++) {
6828 if (i > 0) buf.append(", ");
6829 buf.append(array[i]);
6830 }
6831 }
6832 buf.append(']');
6833 return buf.toString();
6834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 @Override
6837 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6838 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6839 != PackageManager.PERMISSION_GRANTED) {
6840 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6841 + Binder.getCallingPid()
6842 + ", uid=" + Binder.getCallingUid()
6843 + " without permission "
6844 + android.Manifest.permission.DUMP);
6845 return;
6846 }
6847
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006848 boolean dumpStar = true;
6849 boolean dumpLibs = false;
6850 boolean dumpFeatures = false;
6851 boolean dumpResolvers = false;
6852 boolean dumpPermissions = false;
6853 boolean dumpPackages = false;
6854 boolean dumpSharedUsers = false;
6855 boolean dumpMessages = false;
6856 boolean dumpProviders = false;
6857
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006858 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006859 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006860
6861 int opti = 0;
6862 while (opti < args.length) {
6863 String opt = args[opti];
6864 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6865 break;
6866 }
6867 opti++;
6868 if ("-a".equals(opt)) {
6869 // Right now we only know how to print all.
6870 } else if ("-h".equals(opt)) {
6871 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006872 pw.println(" [-h] [-f] [cmd] ...");
6873 pw.println(" -f: print details of intent filters");
6874 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006875 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006876 pw.println(" l[ibraries]: list known shared libraries");
6877 pw.println(" f[ibraries]: list device features");
6878 pw.println(" r[esolvers]: dump intent resolvers");
6879 pw.println(" perm[issions]: dump permissions");
6880 pw.println(" prov[iders]: dump content providers");
6881 pw.println(" p[ackages]: dump installed packages");
6882 pw.println(" s[hared-users]: dump shared user IDs");
6883 pw.println(" m[essages]: print collected runtime messages");
6884 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006885 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006886 } else if ("-f".equals(opt)) {
6887 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006888 } else {
6889 pw.println("Unknown argument: " + opt + "; use -h for help");
6890 }
6891 }
6892
6893 // Is the caller requesting to dump a particular piece of data?
6894 if (opti < args.length) {
6895 String cmd = args[opti];
6896 opti++;
6897 // Is this a package name?
6898 if ("android".equals(cmd) || cmd.contains(".")) {
6899 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006900 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
6901 dumpStar = false;
6902 dumpLibs = true;
6903 } else if ("f".equals(cmd) || "features".equals(cmd)) {
6904 dumpStar = false;
6905 dumpFeatures = true;
6906 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
6907 dumpStar = false;
6908 dumpResolvers = true;
6909 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
6910 dumpStar = false;
6911 dumpPermissions = true;
6912 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
6913 dumpStar = false;
6914 dumpPackages = true;
6915 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
6916 dumpStar = false;
6917 dumpSharedUsers = true;
6918 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
6919 dumpStar = false;
6920 dumpProviders = true;
6921 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
6922 dumpStar = false;
6923 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006924 }
6925 }
6926
6927 boolean printedTitle = false;
6928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006929 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006930 if ((dumpStar || dumpLibs) && packageName == null) {
6931 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006932 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006933 pw.println("Libraries:");
6934 Iterator<String> it = mSharedLibraries.keySet().iterator();
6935 while (it.hasNext()) {
6936 String name = it.next();
6937 pw.print(" ");
6938 pw.print(name);
6939 pw.print(" -> ");
6940 pw.println(mSharedLibraries.get(name));
6941 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006942 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006943
6944 if ((dumpStar || dumpFeatures) && packageName == null) {
6945 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006946 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006947 pw.println("Features:");
6948 Iterator<String> it = mAvailableFeatures.keySet().iterator();
6949 while (it.hasNext()) {
6950 String name = it.next();
6951 pw.print(" ");
6952 pw.println(name);
6953 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006954 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006955
6956 if (dumpStar || dumpResolvers) {
6957 if (mActivities.dump(pw, printedTitle
6958 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
6959 " ", packageName, showFilters)) {
6960 printedTitle = true;
6961 }
6962 if (mReceivers.dump(pw, printedTitle
6963 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6964 " ", packageName, showFilters)) {
6965 printedTitle = true;
6966 }
6967 if (mServices.dump(pw, printedTitle
6968 ? "\nService Resolver Table:" : "Service Resolver Table:",
6969 " ", packageName, showFilters)) {
6970 printedTitle = true;
6971 }
6972 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6973 ? "\nPreferred Activities:" : "Preferred Activities:",
6974 " ", packageName, showFilters)) {
6975 printedTitle = true;
6976 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006977 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006978
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006979 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006980 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006981 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006982 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6983 continue;
6984 }
6985 if (!printedSomething) {
6986 if (printedTitle) pw.println(" ");
6987 pw.println("Permissions:");
6988 printedSomething = true;
6989 printedTitle = true;
6990 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006991 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6992 pw.print(Integer.toHexString(System.identityHashCode(p)));
6993 pw.println("):");
6994 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6995 pw.print(" uid="); pw.print(p.uid);
6996 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006997 pw.print(" type="); pw.print(p.type);
6998 pw.print(" prot="); pw.println(p.protectionLevel);
6999 if (p.packageSetting != null) {
7000 pw.print(" packageSetting="); pw.println(p.packageSetting);
7001 }
7002 if (p.perm != null) {
7003 pw.print(" perm="); pw.println(p.perm);
7004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007005 }
7006 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007007
7008 if (dumpStar || dumpProviders) {
7009 printedSomething = false;
7010 for (PackageParser.Provider p : mProviders.values()) {
7011 if (packageName != null && !packageName.equals(p.info.packageName)) {
7012 continue;
7013 }
7014 if (!printedSomething) {
7015 if (printedTitle) pw.println(" ");
7016 pw.println("Registered ContentProviders:");
7017 printedSomething = true;
7018 printedTitle = true;
7019 }
7020 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7021 pw.println(p.toString());
7022 }
7023 }
7024
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007025 printedSomething = false;
7026 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007027 if (dumpStar || dumpPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007029 if (packageName != null && !packageName.equals(ps.realName)
7030 && !packageName.equals(ps.name)) {
7031 continue;
7032 }
7033 if (!printedSomething) {
7034 if (printedTitle) pw.println(" ");
7035 pw.println("Packages:");
7036 printedSomething = true;
7037 printedTitle = true;
7038 }
7039 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007040 pw.print(" Package [");
7041 pw.print(ps.realName != null ? ps.realName : ps.name);
7042 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007043 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7044 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007045 if (ps.realName != null) {
7046 pw.print(" compat name="); pw.println(ps.name);
7047 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007048 pw.print(" userId="); pw.print(ps.userId);
7049 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7050 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7051 pw.print(" pkg="); pw.println(ps.pkg);
7052 pw.print(" codePath="); pw.println(ps.codePathString);
7053 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007054 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007055 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007056 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007057 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007058 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007059 if (ps.pkg.mOperationPending) {
7060 pw.println(" mOperationPending=true");
7061 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007062 pw.print(" supportsScreens=[");
7063 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007064 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007065 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7066 if (!first) pw.print(", ");
7067 first = false;
7068 pw.print("small");
7069 }
7070 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007071 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007072 if (!first) pw.print(", ");
7073 first = false;
7074 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007076 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007077 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007078 if (!first) pw.print(", ");
7079 first = false;
7080 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007081 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007082 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007083 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007084 if (!first) pw.print(", ");
7085 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007086 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007087 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007088 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007089 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007090 if (!first) pw.print(", ");
7091 first = false;
7092 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007093 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007094 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007095 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7096 if (!first) pw.print(", ");
7097 first = false;
7098 pw.print("anyDensity");
7099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007101 pw.println("]");
Kenny Root7d794fb2010-09-13 16:29:49 -07007102 pw.print(" timeStamp="); pw.println(String.valueOf(ps.timeStamp));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007103 pw.print(" signatures="); pw.println(ps.signatures);
7104 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007105 pw.print(" haveGids="); pw.println(ps.haveGids);
7106 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007107 pw.print(" installStatus="); pw.print(ps.installStatus);
7108 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 if (ps.disabledComponents.size() > 0) {
7110 pw.println(" disabledComponents:");
7111 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007112 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007113 }
7114 }
7115 if (ps.enabledComponents.size() > 0) {
7116 pw.println(" enabledComponents:");
7117 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007118 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 }
7120 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007121 if (ps.grantedPermissions.size() > 0) {
7122 pw.println(" grantedPermissions:");
7123 for (String s : ps.grantedPermissions) {
7124 pw.print(" "); pw.println(s);
7125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007127 }
7128 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007129 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007130 if (dumpStar || dumpPackages) {
7131 if (mSettings.mRenamedPackages.size() > 0) {
7132 for (HashMap.Entry<String, String> e
7133 : mSettings.mRenamedPackages.entrySet()) {
7134 if (packageName != null && !packageName.equals(e.getKey())
7135 && !packageName.equals(e.getValue())) {
7136 continue;
7137 }
7138 if (!printedSomething) {
7139 if (printedTitle) pw.println(" ");
7140 pw.println("Renamed packages:");
7141 printedSomething = true;
7142 printedTitle = true;
7143 }
7144 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7145 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007146 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007147 }
7148 printedSomething = false;
7149 if (mSettings.mDisabledSysPackages.size() > 0) {
7150 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7151 if (packageName != null && !packageName.equals(ps.realName)
7152 && !packageName.equals(ps.name)) {
7153 continue;
7154 }
7155 if (!printedSomething) {
7156 if (printedTitle) pw.println(" ");
7157 pw.println("Hidden system packages:");
7158 printedSomething = true;
7159 printedTitle = true;
7160 }
7161 pw.print(" Package [");
7162 pw.print(ps.realName != null ? ps.realName : ps.name);
7163 pw.print("] (");
7164 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7165 pw.println("):");
7166 if (ps.realName != null) {
7167 pw.print(" compat name="); pw.println(ps.name);
7168 }
7169 pw.print(" userId="); pw.println(ps.userId);
7170 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7171 pw.print(" codePath="); pw.println(ps.codePathString);
7172 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007173 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007174 }
7175 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007176 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007177 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007179 if (packageName != null && su != packageSharedUser) {
7180 continue;
7181 }
7182 if (!printedSomething) {
7183 if (printedTitle) pw.println(" ");
7184 pw.println("Shared users:");
7185 printedSomething = true;
7186 printedTitle = true;
7187 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007188 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7189 pw.print(Integer.toHexString(System.identityHashCode(su)));
7190 pw.println("):");
7191 pw.print(" userId="); pw.print(su.userId);
7192 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007193 pw.println(" grantedPermissions:");
7194 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007195 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 }
7198 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007199
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007200 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007201 if (printedTitle) pw.println(" ");
7202 printedTitle = true;
7203 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007204 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007205
7206 pw.println(" ");
7207 pw.println("Package warning messages:");
7208 File fname = getSettingsProblemFile();
7209 FileInputStream in;
7210 try {
7211 in = new FileInputStream(fname);
7212 int avail = in.available();
7213 byte[] data = new byte[avail];
7214 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007215 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007216 } catch (FileNotFoundException e) {
7217 } catch (IOException e) {
7218 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007220 }
7221 }
7222
7223 static final class BasePermission {
7224 final static int TYPE_NORMAL = 0;
7225 final static int TYPE_BUILTIN = 1;
7226 final static int TYPE_DYNAMIC = 2;
7227
7228 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007229 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007230 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007231 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007232 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 PackageParser.Permission perm;
7234 PermissionInfo pendingInfo;
7235 int uid;
7236 int[] gids;
7237
7238 BasePermission(String _name, String _sourcePackage, int _type) {
7239 name = _name;
7240 sourcePackage = _sourcePackage;
7241 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007242 // Default to most conservative protection level.
7243 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7244 }
7245
7246 public String toString() {
7247 return "BasePermission{"
7248 + Integer.toHexString(System.identityHashCode(this))
7249 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007250 }
7251 }
7252
7253 static class PackageSignatures {
7254 private Signature[] mSignatures;
7255
7256 PackageSignatures(Signature[] sigs) {
7257 assignSignatures(sigs);
7258 }
7259
7260 PackageSignatures() {
7261 }
7262
7263 void writeXml(XmlSerializer serializer, String tagName,
7264 ArrayList<Signature> pastSignatures) throws IOException {
7265 if (mSignatures == null) {
7266 return;
7267 }
7268 serializer.startTag(null, tagName);
7269 serializer.attribute(null, "count",
7270 Integer.toString(mSignatures.length));
7271 for (int i=0; i<mSignatures.length; i++) {
7272 serializer.startTag(null, "cert");
7273 final Signature sig = mSignatures[i];
7274 final int sigHash = sig.hashCode();
7275 final int numPast = pastSignatures.size();
7276 int j;
7277 for (j=0; j<numPast; j++) {
7278 Signature pastSig = pastSignatures.get(j);
7279 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7280 serializer.attribute(null, "index", Integer.toString(j));
7281 break;
7282 }
7283 }
7284 if (j >= numPast) {
7285 pastSignatures.add(sig);
7286 serializer.attribute(null, "index", Integer.toString(numPast));
7287 serializer.attribute(null, "key", sig.toCharsString());
7288 }
7289 serializer.endTag(null, "cert");
7290 }
7291 serializer.endTag(null, tagName);
7292 }
7293
7294 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7295 throws IOException, XmlPullParserException {
7296 String countStr = parser.getAttributeValue(null, "count");
7297 if (countStr == null) {
7298 reportSettingsProblem(Log.WARN,
7299 "Error in package manager settings: <signatures> has"
7300 + " no count at " + parser.getPositionDescription());
7301 XmlUtils.skipCurrentTag(parser);
7302 }
7303 final int count = Integer.parseInt(countStr);
7304 mSignatures = new Signature[count];
7305 int pos = 0;
7306
7307 int outerDepth = parser.getDepth();
7308 int type;
7309 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7310 && (type != XmlPullParser.END_TAG
7311 || parser.getDepth() > outerDepth)) {
7312 if (type == XmlPullParser.END_TAG
7313 || type == XmlPullParser.TEXT) {
7314 continue;
7315 }
7316
7317 String tagName = parser.getName();
7318 if (tagName.equals("cert")) {
7319 if (pos < count) {
7320 String index = parser.getAttributeValue(null, "index");
7321 if (index != null) {
7322 try {
7323 int idx = Integer.parseInt(index);
7324 String key = parser.getAttributeValue(null, "key");
7325 if (key == null) {
7326 if (idx >= 0 && idx < pastSignatures.size()) {
7327 Signature sig = pastSignatures.get(idx);
7328 if (sig != null) {
7329 mSignatures[pos] = pastSignatures.get(idx);
7330 pos++;
7331 } else {
7332 reportSettingsProblem(Log.WARN,
7333 "Error in package manager settings: <cert> "
7334 + "index " + index + " is not defined at "
7335 + parser.getPositionDescription());
7336 }
7337 } else {
7338 reportSettingsProblem(Log.WARN,
7339 "Error in package manager settings: <cert> "
7340 + "index " + index + " is out of bounds at "
7341 + parser.getPositionDescription());
7342 }
7343 } else {
7344 while (pastSignatures.size() <= idx) {
7345 pastSignatures.add(null);
7346 }
7347 Signature sig = new Signature(key);
7348 pastSignatures.set(idx, sig);
7349 mSignatures[pos] = sig;
7350 pos++;
7351 }
7352 } catch (NumberFormatException e) {
7353 reportSettingsProblem(Log.WARN,
7354 "Error in package manager settings: <cert> "
7355 + "index " + index + " is not a number at "
7356 + parser.getPositionDescription());
7357 }
7358 } else {
7359 reportSettingsProblem(Log.WARN,
7360 "Error in package manager settings: <cert> has"
7361 + " no index at " + parser.getPositionDescription());
7362 }
7363 } else {
7364 reportSettingsProblem(Log.WARN,
7365 "Error in package manager settings: too "
7366 + "many <cert> tags, expected " + count
7367 + " at " + parser.getPositionDescription());
7368 }
7369 } else {
7370 reportSettingsProblem(Log.WARN,
7371 "Unknown element under <cert>: "
7372 + parser.getName());
7373 }
7374 XmlUtils.skipCurrentTag(parser);
7375 }
7376
7377 if (pos < count) {
7378 // Should never happen -- there is an error in the written
7379 // settings -- but if it does we don't want to generate
7380 // a bad array.
7381 Signature[] newSigs = new Signature[pos];
7382 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7383 mSignatures = newSigs;
7384 }
7385 }
7386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007387 private void assignSignatures(Signature[] sigs) {
7388 if (sigs == null) {
7389 mSignatures = null;
7390 return;
7391 }
7392 mSignatures = new Signature[sigs.length];
7393 for (int i=0; i<sigs.length; i++) {
7394 mSignatures[i] = sigs[i];
7395 }
7396 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007398 @Override
7399 public String toString() {
7400 StringBuffer buf = new StringBuffer(128);
7401 buf.append("PackageSignatures{");
7402 buf.append(Integer.toHexString(System.identityHashCode(this)));
7403 buf.append(" [");
7404 if (mSignatures != null) {
7405 for (int i=0; i<mSignatures.length; i++) {
7406 if (i > 0) buf.append(", ");
7407 buf.append(Integer.toHexString(
7408 System.identityHashCode(mSignatures[i])));
7409 }
7410 }
7411 buf.append("]}");
7412 return buf.toString();
7413 }
7414 }
7415
7416 static class PreferredActivity extends IntentFilter {
7417 final int mMatch;
7418 final String[] mSetPackages;
7419 final String[] mSetClasses;
7420 final String[] mSetComponents;
7421 final ComponentName mActivity;
7422 final String mShortActivity;
7423 String mParseError;
7424
7425 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7426 ComponentName activity) {
7427 super(filter);
7428 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7429 mActivity = activity;
7430 mShortActivity = activity.flattenToShortString();
7431 mParseError = null;
7432 if (set != null) {
7433 final int N = set.length;
7434 String[] myPackages = new String[N];
7435 String[] myClasses = new String[N];
7436 String[] myComponents = new String[N];
7437 for (int i=0; i<N; i++) {
7438 ComponentName cn = set[i];
7439 if (cn == null) {
7440 mSetPackages = null;
7441 mSetClasses = null;
7442 mSetComponents = null;
7443 return;
7444 }
7445 myPackages[i] = cn.getPackageName().intern();
7446 myClasses[i] = cn.getClassName().intern();
7447 myComponents[i] = cn.flattenToShortString().intern();
7448 }
7449 mSetPackages = myPackages;
7450 mSetClasses = myClasses;
7451 mSetComponents = myComponents;
7452 } else {
7453 mSetPackages = null;
7454 mSetClasses = null;
7455 mSetComponents = null;
7456 }
7457 }
7458
7459 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7460 IOException {
7461 mShortActivity = parser.getAttributeValue(null, "name");
7462 mActivity = ComponentName.unflattenFromString(mShortActivity);
7463 if (mActivity == null) {
7464 mParseError = "Bad activity name " + mShortActivity;
7465 }
7466 String matchStr = parser.getAttributeValue(null, "match");
7467 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7468 String setCountStr = parser.getAttributeValue(null, "set");
7469 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7470
7471 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7472 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7473 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7474
7475 int setPos = 0;
7476
7477 int outerDepth = parser.getDepth();
7478 int type;
7479 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7480 && (type != XmlPullParser.END_TAG
7481 || parser.getDepth() > outerDepth)) {
7482 if (type == XmlPullParser.END_TAG
7483 || type == XmlPullParser.TEXT) {
7484 continue;
7485 }
7486
7487 String tagName = parser.getName();
7488 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7489 // + parser.getDepth() + " tag=" + tagName);
7490 if (tagName.equals("set")) {
7491 String name = parser.getAttributeValue(null, "name");
7492 if (name == null) {
7493 if (mParseError == null) {
7494 mParseError = "No name in set tag in preferred activity "
7495 + mShortActivity;
7496 }
7497 } else if (setPos >= setCount) {
7498 if (mParseError == null) {
7499 mParseError = "Too many set tags in preferred activity "
7500 + mShortActivity;
7501 }
7502 } else {
7503 ComponentName cn = ComponentName.unflattenFromString(name);
7504 if (cn == null) {
7505 if (mParseError == null) {
7506 mParseError = "Bad set name " + name + " in preferred activity "
7507 + mShortActivity;
7508 }
7509 } else {
7510 myPackages[setPos] = cn.getPackageName();
7511 myClasses[setPos] = cn.getClassName();
7512 myComponents[setPos] = name;
7513 setPos++;
7514 }
7515 }
7516 XmlUtils.skipCurrentTag(parser);
7517 } else if (tagName.equals("filter")) {
7518 //Log.i(TAG, "Starting to parse filter...");
7519 readFromXml(parser);
7520 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7521 // + parser.getDepth() + " tag=" + parser.getName());
7522 } else {
7523 reportSettingsProblem(Log.WARN,
7524 "Unknown element under <preferred-activities>: "
7525 + parser.getName());
7526 XmlUtils.skipCurrentTag(parser);
7527 }
7528 }
7529
7530 if (setPos != setCount) {
7531 if (mParseError == null) {
7532 mParseError = "Not enough set tags (expected " + setCount
7533 + " but found " + setPos + ") in " + mShortActivity;
7534 }
7535 }
7536
7537 mSetPackages = myPackages;
7538 mSetClasses = myClasses;
7539 mSetComponents = myComponents;
7540 }
7541
7542 public void writeToXml(XmlSerializer serializer) throws IOException {
7543 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7544 serializer.attribute(null, "name", mShortActivity);
7545 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7546 serializer.attribute(null, "set", Integer.toString(NS));
7547 for (int s=0; s<NS; s++) {
7548 serializer.startTag(null, "set");
7549 serializer.attribute(null, "name", mSetComponents[s]);
7550 serializer.endTag(null, "set");
7551 }
7552 serializer.startTag(null, "filter");
7553 super.writeToXml(serializer);
7554 serializer.endTag(null, "filter");
7555 }
7556
7557 boolean sameSet(List<ResolveInfo> query, int priority) {
7558 if (mSetPackages == null) return false;
7559 final int NQ = query.size();
7560 final int NS = mSetPackages.length;
7561 int numMatch = 0;
7562 for (int i=0; i<NQ; i++) {
7563 ResolveInfo ri = query.get(i);
7564 if (ri.priority != priority) continue;
7565 ActivityInfo ai = ri.activityInfo;
7566 boolean good = false;
7567 for (int j=0; j<NS; j++) {
7568 if (mSetPackages[j].equals(ai.packageName)
7569 && mSetClasses[j].equals(ai.name)) {
7570 numMatch++;
7571 good = true;
7572 break;
7573 }
7574 }
7575 if (!good) return false;
7576 }
7577 return numMatch == NS;
7578 }
7579 }
7580
7581 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007582 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 HashSet<String> grantedPermissions = new HashSet<String>();
7585 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007588 setFlags(pkgFlags);
7589 }
7590
7591 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007592 this.pkgFlags = pkgFlags & (
7593 ApplicationInfo.FLAG_SYSTEM |
7594 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007595 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007596 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007597 }
7598 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 /**
7601 * Settings base class for pending and resolved classes.
7602 */
7603 static class PackageSettingBase extends GrantedPermissions {
7604 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007605 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007606 File codePath;
7607 String codePathString;
7608 File resourcePath;
7609 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007610 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007611 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007612 long timeStamp;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007613 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007614
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007615 boolean uidError;
7616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617 PackageSignatures signatures = new PackageSignatures();
7618
7619 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007620 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622 /* Explicitly disabled components */
7623 HashSet<String> disabledComponents = new HashSet<String>(0);
7624 /* Explicitly enabled components */
7625 HashSet<String> enabledComponents = new HashSet<String>(0);
7626 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7627 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007628
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007629 PackageSettingBase origPackage;
7630
Jacek Surazski65e13172009-04-28 15:26:38 +02007631 /* package name of the app that installed this package */
7632 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007634 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007635 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 super(pkgFlags);
7637 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007638 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007639 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007640 }
7641
Kenny Root806cc132010-09-12 08:34:19 -07007642 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7643 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 this.codePath = codePath;
7645 this.codePathString = codePath.toString();
7646 this.resourcePath = resourcePath;
7647 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007648 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007649 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007650 }
Kenny Root85387d72010-08-26 10:13:11 -07007651
Jacek Surazski65e13172009-04-28 15:26:38 +02007652 public void setInstallerPackageName(String packageName) {
7653 installerPackageName = packageName;
7654 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007655
Jacek Surazski65e13172009-04-28 15:26:38 +02007656 String getInstallerPackageName() {
7657 return installerPackageName;
7658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 public void setInstallStatus(int newStatus) {
7661 installStatus = newStatus;
7662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007664 public int getInstallStatus() {
7665 return installStatus;
7666 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 }
7671
7672 public void copyFrom(PackageSettingBase base) {
7673 grantedPermissions = base.grantedPermissions;
7674 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007676 timeStamp = base.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 signatures = base.signatures;
7678 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007679 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007680 disabledComponents = base.disabledComponents;
7681 enabledComponents = base.enabledComponents;
7682 enabled = base.enabled;
7683 installStatus = base.installStatus;
7684 }
7685
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007686 boolean enableComponentLP(String componentClassName) {
7687 boolean changed = disabledComponents.remove(componentClassName);
7688 changed |= enabledComponents.add(componentClassName);
7689 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 }
7691
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007692 boolean disableComponentLP(String componentClassName) {
7693 boolean changed = enabledComponents.remove(componentClassName);
7694 changed |= disabledComponents.add(componentClassName);
7695 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007696 }
7697
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007698 boolean restoreComponentLP(String componentClassName) {
7699 boolean changed = enabledComponents.remove(componentClassName);
7700 changed |= disabledComponents.remove(componentClassName);
7701 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 }
7703
7704 int currentEnabledStateLP(String componentName) {
7705 if (enabledComponents.contains(componentName)) {
7706 return COMPONENT_ENABLED_STATE_ENABLED;
7707 } else if (disabledComponents.contains(componentName)) {
7708 return COMPONENT_ENABLED_STATE_DISABLED;
7709 } else {
7710 return COMPONENT_ENABLED_STATE_DEFAULT;
7711 }
7712 }
7713 }
7714
7715 /**
7716 * Settings data for a particular package we know about.
7717 */
7718 static final class PackageSetting extends PackageSettingBase {
7719 int userId;
7720 PackageParser.Package pkg;
7721 SharedUserSetting sharedUser;
7722
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007723 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007724 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7725 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7726 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 @Override
7730 public String toString() {
7731 return "PackageSetting{"
7732 + Integer.toHexString(System.identityHashCode(this))
7733 + " " + name + "/" + userId + "}";
7734 }
7735 }
7736
7737 /**
7738 * Settings data for a particular shared user ID we know about.
7739 */
7740 static final class SharedUserSetting extends GrantedPermissions {
7741 final String name;
7742 int userId;
7743 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7744 final PackageSignatures signatures = new PackageSignatures();
7745
7746 SharedUserSetting(String _name, int _pkgFlags) {
7747 super(_pkgFlags);
7748 name = _name;
7749 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007751 @Override
7752 public String toString() {
7753 return "SharedUserSetting{"
7754 + Integer.toHexString(System.identityHashCode(this))
7755 + " " + name + "/" + userId + "}";
7756 }
7757 }
7758
7759 /**
7760 * Holds information about dynamic settings.
7761 */
7762 private static final class Settings {
7763 private final File mSettingsFilename;
7764 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007765 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007766 private final HashMap<String, PackageSetting> mPackages =
7767 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007768 // List of replaced system applications
7769 final HashMap<String, PackageSetting> mDisabledSysPackages =
7770 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007771
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007772 // These are the last platform API version we were using for
7773 // the apps installed on internal and external storage. It is
7774 // used to grant newer permissions one time during a system upgrade.
7775 int mInternalSdkPlatform;
7776 int mExternalSdkPlatform;
7777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007778 // The user's preferred activities associated with particular intent
7779 // filters.
7780 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7781 new IntentResolver<PreferredActivity, PreferredActivity>() {
7782 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007783 protected String packageForFilter(PreferredActivity filter) {
7784 return filter.mActivity.getPackageName();
7785 }
7786 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007787 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007789 out.print(prefix); out.print(
7790 Integer.toHexString(System.identityHashCode(filter)));
7791 out.print(' ');
7792 out.print(filter.mActivity.flattenToShortString());
7793 out.print(" match=0x");
7794 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007796 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007798 out.print(prefix); out.print(" ");
7799 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 }
7801 }
7802 }
7803 };
7804 private final HashMap<String, SharedUserSetting> mSharedUsers =
7805 new HashMap<String, SharedUserSetting>();
7806 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7807 private final SparseArray<Object> mOtherUserIds =
7808 new SparseArray<Object>();
7809
7810 // For reading/writing settings file.
7811 private final ArrayList<Signature> mPastSignatures =
7812 new ArrayList<Signature>();
7813
7814 // Mapping from permission names to info about them.
7815 final HashMap<String, BasePermission> mPermissions =
7816 new HashMap<String, BasePermission>();
7817
7818 // Mapping from permission tree names to info about them.
7819 final HashMap<String, BasePermission> mPermissionTrees =
7820 new HashMap<String, BasePermission>();
7821
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007822 // Packages that have been uninstalled and still need their external
7823 // storage data deleted.
7824 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7825
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007826 // Packages that have been renamed since they were first installed.
7827 // Keys are the new names of the packages, values are the original
7828 // names. The packages appear everwhere else under their original
7829 // names.
7830 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832 private final StringBuilder mReadMessages = new StringBuilder();
7833
7834 private static final class PendingPackage extends PackageSettingBase {
7835 final int sharedId;
7836
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007837 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007838 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7839 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7840 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007841 this.sharedId = sharedId;
7842 }
7843 }
7844 private final ArrayList<PendingPackage> mPendingPackages
7845 = new ArrayList<PendingPackage>();
7846
7847 Settings() {
7848 File dataDir = Environment.getDataDirectory();
7849 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007850 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7851 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007853 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 FileUtils.setPermissions(systemDir.toString(),
7855 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7856 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7857 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007858 FileUtils.setPermissions(systemSecureDir.toString(),
7859 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7860 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7861 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 mSettingsFilename = new File(systemDir, "packages.xml");
7863 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007864 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007865 }
7866
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007867 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007868 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007869 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007870 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007871 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007872 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007873 return p;
7874 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007875
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007876 PackageSetting peekPackageLP(String name) {
7877 return mPackages.get(name);
7878 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007879 PackageSetting p = mPackages.get(name);
7880 if (p != null && p.codePath.getPath().equals(codePath)) {
7881 return p;
7882 }
7883 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007884 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007885 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 void setInstallStatus(String pkgName, int status) {
7888 PackageSetting p = mPackages.get(pkgName);
7889 if(p != null) {
7890 if(p.getInstallStatus() != status) {
7891 p.setInstallStatus(status);
7892 }
7893 }
7894 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007895
Jacek Surazski65e13172009-04-28 15:26:38 +02007896 void setInstallerPackageName(String pkgName,
7897 String installerPkgName) {
7898 PackageSetting p = mPackages.get(pkgName);
7899 if(p != null) {
7900 p.setInstallerPackageName(installerPkgName);
7901 }
7902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007903
Jacek Surazski65e13172009-04-28 15:26:38 +02007904 String getInstallerPackageName(String pkgName) {
7905 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007906 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007907 }
7908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 int getInstallStatus(String pkgName) {
7910 PackageSetting p = mPackages.get(pkgName);
7911 if(p != null) {
7912 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007913 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007914 return -1;
7915 }
7916
7917 SharedUserSetting getSharedUserLP(String name,
7918 int pkgFlags, boolean create) {
7919 SharedUserSetting s = mSharedUsers.get(name);
7920 if (s == null) {
7921 if (!create) {
7922 return null;
7923 }
7924 s = new SharedUserSetting(name, pkgFlags);
7925 if (MULTIPLE_APPLICATION_UIDS) {
7926 s.userId = newUserIdLP(s);
7927 } else {
7928 s.userId = FIRST_APPLICATION_UID;
7929 }
7930 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7931 // < 0 means we couldn't assign a userid; fall out and return
7932 // s, which is currently null
7933 if (s.userId >= 0) {
7934 mSharedUsers.put(name, s);
7935 }
7936 }
7937
7938 return s;
7939 }
7940
7941 int disableSystemPackageLP(String name) {
7942 PackageSetting p = mPackages.get(name);
7943 if(p == null) {
7944 Log.w(TAG, "Package:"+name+" is not an installed package");
7945 return -1;
7946 }
7947 PackageSetting dp = mDisabledSysPackages.get(name);
7948 // always make sure the system package code and resource paths dont change
7949 if(dp == null) {
7950 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7951 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7952 }
7953 mDisabledSysPackages.put(name, p);
7954 }
7955 return removePackageLP(name);
7956 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007957
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 PackageSetting enableSystemPackageLP(String name) {
7959 PackageSetting p = mDisabledSysPackages.get(name);
7960 if(p == null) {
7961 Log.w(TAG, "Package:"+name+" is not disabled");
7962 return null;
7963 }
7964 // Reset flag in ApplicationInfo object
7965 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7966 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7967 }
Kenny Root806cc132010-09-12 08:34:19 -07007968 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
7969 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 mDisabledSysPackages.remove(name);
7971 return ret;
7972 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007973
Kenny Root806cc132010-09-12 08:34:19 -07007974 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
7975 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 PackageSetting p = mPackages.get(name);
7977 if (p != null) {
7978 if (p.userId == uid) {
7979 return p;
7980 }
7981 reportSettingsProblem(Log.ERROR,
7982 "Adding duplicate package, keeping first: " + name);
7983 return null;
7984 }
Kenny Root806cc132010-09-12 08:34:19 -07007985 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
7986 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 p.userId = uid;
7988 if (addUserIdLP(uid, p, name)) {
7989 mPackages.put(name, p);
7990 return p;
7991 }
7992 return null;
7993 }
7994
7995 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7996 SharedUserSetting s = mSharedUsers.get(name);
7997 if (s != null) {
7998 if (s.userId == uid) {
7999 return s;
8000 }
8001 reportSettingsProblem(Log.ERROR,
8002 "Adding duplicate shared user, keeping first: " + name);
8003 return null;
8004 }
8005 s = new SharedUserSetting(name, pkgFlags);
8006 s.userId = uid;
8007 if (addUserIdLP(uid, s, name)) {
8008 mSharedUsers.put(name, s);
8009 return s;
8010 }
8011 return null;
8012 }
8013
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008014 // Transfer ownership of permissions from one package to another.
8015 private void transferPermissions(String origPkg, String newPkg) {
8016 // Transfer ownership of permissions to the new package.
8017 for (int i=0; i<2; i++) {
8018 HashMap<String, BasePermission> permissions =
8019 i == 0 ? mPermissionTrees : mPermissions;
8020 for (BasePermission bp : permissions.values()) {
8021 if (origPkg.equals(bp.sourcePackage)) {
8022 if (DEBUG_UPGRADE) Log.v(TAG,
8023 "Moving permission " + bp.name
8024 + " from pkg " + bp.sourcePackage
8025 + " to " + newPkg);
8026 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008027 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008028 bp.perm = null;
8029 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008030 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008031 }
8032 bp.uid = 0;
8033 bp.gids = null;
8034 }
8035 }
8036 }
8037 }
8038
8039 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008040 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008041 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008042 PackageSetting p = mPackages.get(name);
8043 if (p != null) {
8044 if (!p.codePath.equals(codePath)) {
8045 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008046 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008047 // This is an updated system app with versions in both system
8048 // and data partition. Just let the most recent version
8049 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008050 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008051 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008052 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008053 // Just a change in the code path is not an issue, but
8054 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008055 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008056 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008057 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008058 }
8059 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 reportSettingsProblem(Log.WARN,
8061 "Package " + name + " shared user changed from "
8062 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8063 + " to "
8064 + (sharedUser != null ? sharedUser.name : "<nothing>")
8065 + "; replacing with new");
8066 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008067 } else {
8068 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8069 // If what we are scanning is a system package, then
8070 // make it so, regardless of whether it was previously
8071 // installed only in the data partition.
8072 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 }
8075 }
8076 if (p == null) {
8077 // Create a new PackageSettings entry. this can end up here because
8078 // of code path mismatch or user id mismatch of an updated system partition
8079 if (!create) {
8080 return null;
8081 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008082 if (origPackage != null) {
8083 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008084 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8085 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008086 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8087 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008088 // Note that we will retain the new package's signature so
8089 // that we can keep its data.
8090 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008091 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008092 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008093 p.sharedUser = origPackage.sharedUser;
8094 p.userId = origPackage.userId;
8095 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008096 mRenamedPackages.put(name, origPackage.name);
8097 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008098 // Update new package state.
8099 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008100 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008101 p = new PackageSetting(name, realName, codePath, resourcePath,
8102 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008103 p.setTimeStamp(codePath.lastModified());
8104 p.sharedUser = sharedUser;
8105 if (sharedUser != null) {
8106 p.userId = sharedUser.userId;
8107 } else if (MULTIPLE_APPLICATION_UIDS) {
8108 // Clone the setting here for disabled system packages
8109 PackageSetting dis = mDisabledSysPackages.get(name);
8110 if (dis != null) {
8111 // For disabled packages a new setting is created
8112 // from the existing user id. This still has to be
8113 // added to list of user id's
8114 // Copy signatures from previous setting
8115 if (dis.signatures.mSignatures != null) {
8116 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8117 }
8118 p.userId = dis.userId;
8119 // Clone permissions
8120 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008121 // Clone component info
8122 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8123 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8124 // Add new setting to list of user ids
8125 addUserIdLP(p.userId, p, name);
8126 } else {
8127 // Assign new user id
8128 p.userId = newUserIdLP(p);
8129 }
8130 } else {
8131 p.userId = FIRST_APPLICATION_UID;
8132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 }
8134 if (p.userId < 0) {
8135 reportSettingsProblem(Log.WARN,
8136 "Package " + name + " could not be assigned a valid uid");
8137 return null;
8138 }
8139 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008140 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008142 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008143 }
8144 }
8145 return p;
8146 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008147
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008148 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008149 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008150 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008151 final String codePath = pkg.applicationInfo.sourceDir;
8152 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008153 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008154 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008155 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008156 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008157 p.codePath = new File(codePath);
8158 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008159 }
8160 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008161 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008162 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008163 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008164 p.resourcePath = new File(resourcePath);
8165 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008166 }
Kenny Root85387d72010-08-26 10:13:11 -07008167 // Update the native library path if needed
8168 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8169 if (nativeLibraryPath != null
8170 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8171 p.nativeLibraryPathString = nativeLibraryPath;
8172 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008173 // Update version code if needed
8174 if (pkg.mVersionCode != p.versionCode) {
8175 p.versionCode = pkg.mVersionCode;
8176 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008177 // Update signatures if needed.
8178 if (p.signatures.mSignatures == null) {
8179 p.signatures.assignSignatures(pkg.mSignatures);
8180 }
8181 // If this app defines a shared user id initialize
8182 // the shared user signatures as well.
8183 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8184 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8185 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008186 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8187 }
8188
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 // Utility method that adds a PackageSetting to mPackages and
8190 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008191 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 SharedUserSetting sharedUser) {
8193 mPackages.put(name, p);
8194 if (sharedUser != null) {
8195 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8196 reportSettingsProblem(Log.ERROR,
8197 "Package " + p.name + " was user "
8198 + p.sharedUser + " but is now " + sharedUser
8199 + "; I am not changing its files so it will probably fail!");
8200 p.sharedUser.packages.remove(p);
8201 } else if (p.userId != sharedUser.userId) {
8202 reportSettingsProblem(Log.ERROR,
8203 "Package " + p.name + " was user id " + p.userId
8204 + " but is now user " + sharedUser
8205 + " with id " + sharedUser.userId
8206 + "; I am not changing its files so it will probably fail!");
8207 }
8208
8209 sharedUser.packages.add(p);
8210 p.sharedUser = sharedUser;
8211 p.userId = sharedUser.userId;
8212 }
8213 }
8214
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008215 /*
8216 * Update the shared user setting when a package using
8217 * specifying the shared user id is removed. The gids
8218 * associated with each permission of the deleted package
8219 * are removed from the shared user's gid list only if its
8220 * not in use by other permissions of packages in the
8221 * shared user setting.
8222 */
8223 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008224 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008225 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008226 return;
8227 }
8228 // No sharedUserId
8229 if (deletedPs.sharedUser == null) {
8230 return;
8231 }
8232 SharedUserSetting sus = deletedPs.sharedUser;
8233 // Update permissions
8234 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8235 boolean used = false;
8236 if (!sus.grantedPermissions.contains (eachPerm)) {
8237 continue;
8238 }
8239 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008240 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008241 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008242 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243 used = true;
8244 break;
8245 }
8246 }
8247 if (!used) {
8248 // can safely delete this permission from list
8249 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008250 }
8251 }
8252 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008253 int newGids[] = globalGids;
8254 for (String eachPerm : sus.grantedPermissions) {
8255 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008256 if (bp != null) {
8257 newGids = appendInts(newGids, bp.gids);
8258 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 }
8260 sus.gids = newGids;
8261 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008263 private int removePackageLP(String name) {
8264 PackageSetting p = mPackages.get(name);
8265 if (p != null) {
8266 mPackages.remove(name);
8267 if (p.sharedUser != null) {
8268 p.sharedUser.packages.remove(p);
8269 if (p.sharedUser.packages.size() == 0) {
8270 mSharedUsers.remove(p.sharedUser.name);
8271 removeUserIdLP(p.sharedUser.userId);
8272 return p.sharedUser.userId;
8273 }
8274 } else {
8275 removeUserIdLP(p.userId);
8276 return p.userId;
8277 }
8278 }
8279 return -1;
8280 }
8281
8282 private boolean addUserIdLP(int uid, Object obj, Object name) {
8283 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8284 return false;
8285 }
8286
8287 if (uid >= FIRST_APPLICATION_UID) {
8288 int N = mUserIds.size();
8289 final int index = uid - FIRST_APPLICATION_UID;
8290 while (index >= N) {
8291 mUserIds.add(null);
8292 N++;
8293 }
8294 if (mUserIds.get(index) != null) {
8295 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008296 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008297 + " name=" + name);
8298 return false;
8299 }
8300 mUserIds.set(index, obj);
8301 } else {
8302 if (mOtherUserIds.get(uid) != null) {
8303 reportSettingsProblem(Log.ERROR,
8304 "Adding duplicate shared id: " + uid
8305 + " name=" + name);
8306 return false;
8307 }
8308 mOtherUserIds.put(uid, obj);
8309 }
8310 return true;
8311 }
8312
8313 public Object getUserIdLP(int uid) {
8314 if (uid >= FIRST_APPLICATION_UID) {
8315 int N = mUserIds.size();
8316 final int index = uid - FIRST_APPLICATION_UID;
8317 return index < N ? mUserIds.get(index) : null;
8318 } else {
8319 return mOtherUserIds.get(uid);
8320 }
8321 }
8322
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008323 private Set<String> findPackagesWithFlag(int flag) {
8324 Set<String> ret = new HashSet<String>();
8325 for (PackageSetting ps : mPackages.values()) {
8326 // Has to match atleast all the flag bits set on flag
8327 if ((ps.pkgFlags & flag) == flag) {
8328 ret.add(ps.name);
8329 }
8330 }
8331 return ret;
8332 }
8333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008334 private void removeUserIdLP(int uid) {
8335 if (uid >= FIRST_APPLICATION_UID) {
8336 int N = mUserIds.size();
8337 final int index = uid - FIRST_APPLICATION_UID;
8338 if (index < N) mUserIds.set(index, null);
8339 } else {
8340 mOtherUserIds.remove(uid);
8341 }
8342 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 void writeLP() {
8345 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8346
8347 // Keep the old settings around until we know the new ones have
8348 // been successfully written.
8349 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008350 // Presence of backup settings file indicates that we failed
8351 // to persist settings earlier. So preserve the older
8352 // backup for future reference since the current settings
8353 // might have been corrupted.
8354 if (!mBackupSettingsFilename.exists()) {
8355 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008356 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008357 return;
8358 }
8359 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008360 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008361 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008363 }
8364
8365 mPastSignatures.clear();
8366
8367 try {
Kenny Root9f306d72010-09-26 11:19:47 -07008368 BufferedOutputStream str = new BufferedOutputStream(new FileOutputStream(
8369 mSettingsFilename));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008370
8371 //XmlSerializer serializer = XmlUtils.serializerInstance();
8372 XmlSerializer serializer = new FastXmlSerializer();
8373 serializer.setOutput(str, "utf-8");
8374 serializer.startDocument(null, true);
8375 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8376
8377 serializer.startTag(null, "packages");
8378
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008379 serializer.startTag(null, "last-platform-version");
8380 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8381 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8382 serializer.endTag(null, "last-platform-version");
8383
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008384 serializer.startTag(null, "permission-trees");
8385 for (BasePermission bp : mPermissionTrees.values()) {
8386 writePermission(serializer, bp);
8387 }
8388 serializer.endTag(null, "permission-trees");
8389
8390 serializer.startTag(null, "permissions");
8391 for (BasePermission bp : mPermissions.values()) {
8392 writePermission(serializer, bp);
8393 }
8394 serializer.endTag(null, "permissions");
8395
8396 for (PackageSetting pkg : mPackages.values()) {
8397 writePackage(serializer, pkg);
8398 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008400 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8401 writeDisabledSysPackage(serializer, pkg);
8402 }
8403
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008404 serializer.startTag(null, "preferred-activities");
8405 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8406 serializer.startTag(null, "item");
8407 pa.writeToXml(serializer);
8408 serializer.endTag(null, "item");
8409 }
8410 serializer.endTag(null, "preferred-activities");
8411
8412 for (SharedUserSetting usr : mSharedUsers.values()) {
8413 serializer.startTag(null, "shared-user");
8414 serializer.attribute(null, "name", usr.name);
8415 serializer.attribute(null, "userId",
8416 Integer.toString(usr.userId));
8417 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8418 serializer.startTag(null, "perms");
8419 for (String name : usr.grantedPermissions) {
8420 serializer.startTag(null, "item");
8421 serializer.attribute(null, "name", name);
8422 serializer.endTag(null, "item");
8423 }
8424 serializer.endTag(null, "perms");
8425 serializer.endTag(null, "shared-user");
8426 }
8427
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008428 if (mPackagesToBeCleaned.size() > 0) {
8429 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8430 serializer.startTag(null, "cleaning-package");
8431 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8432 serializer.endTag(null, "cleaning-package");
8433 }
8434 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008435
8436 if (mRenamedPackages.size() > 0) {
8437 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8438 serializer.startTag(null, "renamed-package");
8439 serializer.attribute(null, "new", e.getKey());
8440 serializer.attribute(null, "old", e.getValue());
8441 serializer.endTag(null, "renamed-package");
8442 }
8443 }
8444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008445 serializer.endTag(null, "packages");
8446
8447 serializer.endDocument();
8448
8449 str.flush();
8450 str.close();
8451
8452 // New settings successfully written, old ones are no longer
8453 // needed.
8454 mBackupSettingsFilename.delete();
8455 FileUtils.setPermissions(mSettingsFilename.toString(),
8456 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8457 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8458 |FileUtils.S_IROTH,
8459 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008460
8461 // Write package list file now, use a JournaledFile.
8462 //
8463 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8464 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8465
Kenny Root9f306d72010-09-26 11:19:47 -07008466 str = new BufferedOutputStream(new FileOutputStream(journal.chooseForWrite()));
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008467 try {
8468 StringBuilder sb = new StringBuilder();
8469 for (PackageSetting pkg : mPackages.values()) {
8470 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008471 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008472 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8473
8474 // Avoid any application that has a space in its path
8475 // or that is handled by the system.
8476 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8477 continue;
8478
8479 // we store on each line the following information for now:
8480 //
8481 // pkgName - package name
8482 // userId - application-specific user id
8483 // debugFlag - 0 or 1 if the package is debuggable.
8484 // dataPath - path to package's data path
8485 //
8486 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8487 //
8488 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8489 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8490 // system/core/run-as/run-as.c
8491 //
8492 sb.setLength(0);
8493 sb.append(ai.packageName);
8494 sb.append(" ");
8495 sb.append((int)ai.uid);
8496 sb.append(isDebug ? " 1 " : " 0 ");
8497 sb.append(dataPath);
8498 sb.append("\n");
8499 str.write(sb.toString().getBytes());
8500 }
8501 str.flush();
8502 str.close();
8503 journal.commit();
8504 }
8505 catch (Exception e) {
8506 journal.rollback();
8507 }
8508
8509 FileUtils.setPermissions(mPackageListFilename.toString(),
8510 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8511 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8512 |FileUtils.S_IROTH,
8513 -1, -1);
8514
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008515 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516
8517 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008518 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 -08008519 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008520 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 -08008521 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008522 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008523 if (mSettingsFilename.exists()) {
8524 if (!mSettingsFilename.delete()) {
8525 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8526 }
8527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008528 //Debug.stopMethodTracing();
8529 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008530
8531 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008532 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 serializer.startTag(null, "updated-package");
8534 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008535 if (pkg.realName != null) {
8536 serializer.attribute(null, "realName", pkg.realName);
8537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008538 serializer.attribute(null, "codePath", pkg.codePathString);
Kenny Root7d794fb2010-09-13 16:29:49 -07008539 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008540 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8542 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8543 }
Kenny Root85387d72010-08-26 10:13:11 -07008544 if (pkg.nativeLibraryPathString != null) {
8545 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008547 if (pkg.sharedUser == null) {
8548 serializer.attribute(null, "userId",
8549 Integer.toString(pkg.userId));
8550 } else {
8551 serializer.attribute(null, "sharedUserId",
8552 Integer.toString(pkg.userId));
8553 }
8554 serializer.startTag(null, "perms");
8555 if (pkg.sharedUser == null) {
8556 // If this is a shared user, the permissions will
8557 // be written there. We still need to write an
8558 // empty permissions list so permissionsFixed will
8559 // be set.
8560 for (final String name : pkg.grantedPermissions) {
8561 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008562 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 // We only need to write signature or system permissions but this wont
8564 // match the semantics of grantedPermissions. So write all permissions.
8565 serializer.startTag(null, "item");
8566 serializer.attribute(null, "name", name);
8567 serializer.endTag(null, "item");
8568 }
8569 }
8570 }
8571 serializer.endTag(null, "perms");
8572 serializer.endTag(null, "updated-package");
8573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008574
8575 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008576 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 serializer.startTag(null, "package");
8578 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008579 if (pkg.realName != null) {
8580 serializer.attribute(null, "realName", pkg.realName);
8581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008582 serializer.attribute(null, "codePath", pkg.codePathString);
8583 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8584 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8585 }
Kenny Root85387d72010-08-26 10:13:11 -07008586 if (pkg.nativeLibraryPathString != null) {
8587 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8588 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008589 serializer.attribute(null, "flags",
8590 Integer.toString(pkg.pkgFlags));
Kenny Root7d794fb2010-09-13 16:29:49 -07008591 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008592 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 if (pkg.sharedUser == null) {
8594 serializer.attribute(null, "userId",
8595 Integer.toString(pkg.userId));
8596 } else {
8597 serializer.attribute(null, "sharedUserId",
8598 Integer.toString(pkg.userId));
8599 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008600 if (pkg.uidError) {
8601 serializer.attribute(null, "uidError", "true");
8602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008603 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8604 serializer.attribute(null, "enabled",
8605 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8606 ? "true" : "false");
8607 }
8608 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8609 serializer.attribute(null, "installStatus", "false");
8610 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008611 if (pkg.installerPackageName != null) {
8612 serializer.attribute(null, "installer", pkg.installerPackageName);
8613 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008614 if (pkg.obbPathString != null) {
8615 serializer.attribute(null, "obbPath", pkg.obbPathString);
8616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008617 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8618 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8619 serializer.startTag(null, "perms");
8620 if (pkg.sharedUser == null) {
8621 // If this is a shared user, the permissions will
8622 // be written there. We still need to write an
8623 // empty permissions list so permissionsFixed will
8624 // be set.
8625 for (final String name : pkg.grantedPermissions) {
8626 serializer.startTag(null, "item");
8627 serializer.attribute(null, "name", name);
8628 serializer.endTag(null, "item");
8629 }
8630 }
8631 serializer.endTag(null, "perms");
8632 }
8633 if (pkg.disabledComponents.size() > 0) {
8634 serializer.startTag(null, "disabled-components");
8635 for (final String name : pkg.disabledComponents) {
8636 serializer.startTag(null, "item");
8637 serializer.attribute(null, "name", name);
8638 serializer.endTag(null, "item");
8639 }
8640 serializer.endTag(null, "disabled-components");
8641 }
8642 if (pkg.enabledComponents.size() > 0) {
8643 serializer.startTag(null, "enabled-components");
8644 for (final String name : pkg.enabledComponents) {
8645 serializer.startTag(null, "item");
8646 serializer.attribute(null, "name", name);
8647 serializer.endTag(null, "item");
8648 }
8649 serializer.endTag(null, "enabled-components");
8650 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008651
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008652 serializer.endTag(null, "package");
8653 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008655 void writePermission(XmlSerializer serializer, BasePermission bp)
8656 throws XmlPullParserException, java.io.IOException {
8657 if (bp.type != BasePermission.TYPE_BUILTIN
8658 && bp.sourcePackage != null) {
8659 serializer.startTag(null, "item");
8660 serializer.attribute(null, "name", bp.name);
8661 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008662 if (bp.protectionLevel !=
8663 PermissionInfo.PROTECTION_NORMAL) {
8664 serializer.attribute(null, "protection",
8665 Integer.toString(bp.protectionLevel));
8666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008667 if (DEBUG_SETTINGS) Log.v(TAG,
8668 "Writing perm: name=" + bp.name + " type=" + bp.type);
8669 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8670 PermissionInfo pi = bp.perm != null ? bp.perm.info
8671 : bp.pendingInfo;
8672 if (pi != null) {
8673 serializer.attribute(null, "type", "dynamic");
8674 if (pi.icon != 0) {
8675 serializer.attribute(null, "icon",
8676 Integer.toString(pi.icon));
8677 }
8678 if (pi.nonLocalizedLabel != null) {
8679 serializer.attribute(null, "label",
8680 pi.nonLocalizedLabel.toString());
8681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008682 }
8683 }
8684 serializer.endTag(null, "item");
8685 }
8686 }
8687
8688 String getReadMessagesLP() {
8689 return mReadMessages.toString();
8690 }
8691
Oscar Montemayora8529f62009-11-18 10:14:20 -08008692 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008693 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8694 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008695 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 while(its.hasNext()) {
8697 String key = its.next();
8698 PackageSetting ps = mPackages.get(key);
8699 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008700 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 }
8702 }
8703 return ret;
8704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008706 boolean readLP() {
8707 FileInputStream str = null;
8708 if (mBackupSettingsFilename.exists()) {
8709 try {
8710 str = new FileInputStream(mBackupSettingsFilename);
8711 mReadMessages.append("Reading from backup settings file\n");
8712 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008713 if (mSettingsFilename.exists()) {
8714 // If both the backup and settings file exist, we
8715 // ignore the settings since it might have been
8716 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008717 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008718 mSettingsFilename.delete();
8719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 } catch (java.io.IOException e) {
8721 // We'll try for the normal settings file.
8722 }
8723 }
8724
8725 mPastSignatures.clear();
8726
8727 try {
8728 if (str == null) {
8729 if (!mSettingsFilename.exists()) {
8730 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008731 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008732 return false;
8733 }
8734 str = new FileInputStream(mSettingsFilename);
8735 }
8736 XmlPullParser parser = Xml.newPullParser();
8737 parser.setInput(str, null);
8738
8739 int type;
8740 while ((type=parser.next()) != XmlPullParser.START_TAG
8741 && type != XmlPullParser.END_DOCUMENT) {
8742 ;
8743 }
8744
8745 if (type != XmlPullParser.START_TAG) {
8746 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008747 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008748 return false;
8749 }
8750
8751 int outerDepth = parser.getDepth();
8752 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8753 && (type != XmlPullParser.END_TAG
8754 || parser.getDepth() > outerDepth)) {
8755 if (type == XmlPullParser.END_TAG
8756 || type == XmlPullParser.TEXT) {
8757 continue;
8758 }
8759
8760 String tagName = parser.getName();
8761 if (tagName.equals("package")) {
8762 readPackageLP(parser);
8763 } else if (tagName.equals("permissions")) {
8764 readPermissionsLP(mPermissions, parser);
8765 } else if (tagName.equals("permission-trees")) {
8766 readPermissionsLP(mPermissionTrees, parser);
8767 } else if (tagName.equals("shared-user")) {
8768 readSharedUserLP(parser);
8769 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008770 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 } else if (tagName.equals("preferred-activities")) {
8772 readPreferredActivitiesLP(parser);
8773 } else if(tagName.equals("updated-package")) {
8774 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008775 } else if (tagName.equals("cleaning-package")) {
8776 String name = parser.getAttributeValue(null, "name");
8777 if (name != null) {
8778 mPackagesToBeCleaned.add(name);
8779 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008780 } else if (tagName.equals("renamed-package")) {
8781 String nname = parser.getAttributeValue(null, "new");
8782 String oname = parser.getAttributeValue(null, "old");
8783 if (nname != null && oname != null) {
8784 mRenamedPackages.put(nname, oname);
8785 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008786 } else if (tagName.equals("last-platform-version")) {
8787 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8788 try {
8789 String internal = parser.getAttributeValue(null, "internal");
8790 if (internal != null) {
8791 mInternalSdkPlatform = Integer.parseInt(internal);
8792 }
8793 String external = parser.getAttributeValue(null, "external");
8794 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008795 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008796 }
8797 } catch (NumberFormatException e) {
8798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008800 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 + parser.getName());
8802 XmlUtils.skipCurrentTag(parser);
8803 }
8804 }
8805
8806 str.close();
8807
8808 } catch(XmlPullParserException e) {
8809 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008810 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008811
8812 } catch(java.io.IOException e) {
8813 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008814 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008815
8816 }
8817
8818 int N = mPendingPackages.size();
8819 for (int i=0; i<N; i++) {
8820 final PendingPackage pp = mPendingPackages.get(i);
8821 Object idObj = getUserIdLP(pp.sharedId);
8822 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008823 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008824 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8825 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008826 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008827 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008828 + pp.name);
8829 continue;
8830 }
8831 p.copyFrom(pp);
8832 } else if (idObj != null) {
8833 String msg = "Bad package setting: package " + pp.name
8834 + " has shared uid " + pp.sharedId
8835 + " that is not a shared uid\n";
8836 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008837 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008838 } else {
8839 String msg = "Bad package setting: package " + pp.name
8840 + " has shared uid " + pp.sharedId
8841 + " that is not defined\n";
8842 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008843 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844 }
8845 }
8846 mPendingPackages.clear();
8847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008848 mReadMessages.append("Read completed successfully: "
8849 + mPackages.size() + " packages, "
8850 + mSharedUsers.size() + " shared uids\n");
8851
8852 return true;
8853 }
8854
8855 private int readInt(XmlPullParser parser, String ns, String name,
8856 int defValue) {
8857 String v = parser.getAttributeValue(ns, name);
8858 try {
8859 if (v == null) {
8860 return defValue;
8861 }
8862 return Integer.parseInt(v);
8863 } catch (NumberFormatException e) {
8864 reportSettingsProblem(Log.WARN,
8865 "Error in package manager settings: attribute " +
8866 name + " has bad integer value " + v + " at "
8867 + parser.getPositionDescription());
8868 }
8869 return defValue;
8870 }
8871
8872 private void readPermissionsLP(HashMap<String, BasePermission> out,
8873 XmlPullParser parser)
8874 throws IOException, XmlPullParserException {
8875 int outerDepth = parser.getDepth();
8876 int type;
8877 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8878 && (type != XmlPullParser.END_TAG
8879 || parser.getDepth() > outerDepth)) {
8880 if (type == XmlPullParser.END_TAG
8881 || type == XmlPullParser.TEXT) {
8882 continue;
8883 }
8884
8885 String tagName = parser.getName();
8886 if (tagName.equals("item")) {
8887 String name = parser.getAttributeValue(null, "name");
8888 String sourcePackage = parser.getAttributeValue(null, "package");
8889 String ptype = parser.getAttributeValue(null, "type");
8890 if (name != null && sourcePackage != null) {
8891 boolean dynamic = "dynamic".equals(ptype);
8892 BasePermission bp = new BasePermission(name, sourcePackage,
8893 dynamic
8894 ? BasePermission.TYPE_DYNAMIC
8895 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008896 bp.protectionLevel = readInt(parser, null, "protection",
8897 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008898 if (dynamic) {
8899 PermissionInfo pi = new PermissionInfo();
8900 pi.packageName = sourcePackage.intern();
8901 pi.name = name.intern();
8902 pi.icon = readInt(parser, null, "icon", 0);
8903 pi.nonLocalizedLabel = parser.getAttributeValue(
8904 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008905 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 bp.pendingInfo = pi;
8907 }
8908 out.put(bp.name, bp);
8909 } else {
8910 reportSettingsProblem(Log.WARN,
8911 "Error in package manager settings: permissions has"
8912 + " no name at " + parser.getPositionDescription());
8913 }
8914 } else {
8915 reportSettingsProblem(Log.WARN,
8916 "Unknown element reading permissions: "
8917 + parser.getName() + " at "
8918 + parser.getPositionDescription());
8919 }
8920 XmlUtils.skipCurrentTag(parser);
8921 }
8922 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008923
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008924 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008925 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008926 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008927 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 String codePathStr = parser.getAttributeValue(null, "codePath");
8929 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07008930 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008931 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 resourcePathStr = codePathStr;
8933 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008934 String version = parser.getAttributeValue(null, "version");
8935 int versionCode = 0;
8936 if (version != null) {
8937 try {
8938 versionCode = Integer.parseInt(version);
8939 } catch (NumberFormatException e) {
8940 }
8941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 int pkgFlags = 0;
8944 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07008945 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
8946 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 String timeStampStr = parser.getAttributeValue(null, "ts");
8948 if (timeStampStr != null) {
8949 try {
8950 long timeStamp = Long.parseLong(timeStampStr);
Kenny Root7d794fb2010-09-13 16:29:49 -07008951 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 } catch (NumberFormatException e) {
8953 }
8954 }
8955 String idStr = parser.getAttributeValue(null, "userId");
8956 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8957 if(ps.userId <= 0) {
8958 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8959 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8960 }
8961 int outerDepth = parser.getDepth();
8962 int type;
8963 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8964 && (type != XmlPullParser.END_TAG
8965 || parser.getDepth() > outerDepth)) {
8966 if (type == XmlPullParser.END_TAG
8967 || type == XmlPullParser.TEXT) {
8968 continue;
8969 }
8970
8971 String tagName = parser.getName();
8972 if (tagName.equals("perms")) {
8973 readGrantedPermissionsLP(parser,
8974 ps.grantedPermissions);
8975 } else {
8976 reportSettingsProblem(Log.WARN,
8977 "Unknown element under <updated-package>: "
8978 + parser.getName());
8979 XmlUtils.skipCurrentTag(parser);
8980 }
8981 }
8982 mDisabledSysPackages.put(name, ps);
8983 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 private void readPackageLP(XmlPullParser parser)
8986 throws XmlPullParserException, IOException {
8987 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008988 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 String idStr = null;
8990 String sharedIdStr = null;
8991 String codePathStr = null;
8992 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07008993 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07008994 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008995 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008996 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008997 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008998 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008999 long timeStamp = 0;
9000 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009001 String version = null;
9002 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009003 try {
9004 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009005 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009006 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009007 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9009 codePathStr = parser.getAttributeValue(null, "codePath");
9010 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009011 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009012 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009013 version = parser.getAttributeValue(null, "version");
9014 if (version != null) {
9015 try {
9016 versionCode = Integer.parseInt(version);
9017 } catch (NumberFormatException e) {
9018 }
9019 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009020 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009021
9022 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009024 try {
9025 pkgFlags = Integer.parseInt(systemStr);
9026 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 }
9028 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009029 // For backward compatibility
9030 systemStr = parser.getAttributeValue(null, "system");
9031 if (systemStr != null) {
9032 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9033 } else {
9034 // Old settings that don't specify system... just treat
9035 // them as system, good enough.
9036 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009038 }
Kenny Root7d794fb2010-09-13 16:29:49 -07009039 final String timeStampStr = parser.getAttributeValue(null, "ts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 if (timeStampStr != null) {
9041 try {
9042 timeStamp = Long.parseLong(timeStampStr);
9043 } catch (NumberFormatException e) {
9044 }
9045 }
9046 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9047 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9048 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9049 if (resourcePathStr == null) {
9050 resourcePathStr = codePathStr;
9051 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009052 if (realName != null) {
9053 realName = realName.intern();
9054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009055 if (name == null) {
9056 reportSettingsProblem(Log.WARN,
9057 "Error in package manager settings: <package> has no name at "
9058 + parser.getPositionDescription());
9059 } else if (codePathStr == null) {
9060 reportSettingsProblem(Log.WARN,
9061 "Error in package manager settings: <package> has no codePath at "
9062 + parser.getPositionDescription());
9063 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009064 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9065 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9066 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009067 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9068 + ": userId=" + userId + " pkg=" + packageSetting);
9069 if (packageSetting == null) {
9070 reportSettingsProblem(Log.ERROR,
9071 "Failure adding uid " + userId
9072 + " while parsing settings at "
9073 + parser.getPositionDescription());
9074 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009075 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009076 }
9077 } else if (sharedIdStr != null) {
9078 userId = sharedIdStr != null
9079 ? Integer.parseInt(sharedIdStr) : 0;
9080 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009081 packageSetting = new PendingPackage(name.intern(), realName,
9082 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009083 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009084 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009085 mPendingPackages.add((PendingPackage) packageSetting);
9086 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9087 + ": sharedUserId=" + userId + " pkg="
9088 + packageSetting);
9089 } else {
9090 reportSettingsProblem(Log.WARN,
9091 "Error in package manager settings: package "
9092 + name + " has bad sharedId " + sharedIdStr
9093 + " at " + parser.getPositionDescription());
9094 }
9095 } else {
9096 reportSettingsProblem(Log.WARN,
9097 "Error in package manager settings: package "
9098 + name + " has bad userId " + idStr + " at "
9099 + parser.getPositionDescription());
9100 }
9101 } catch (NumberFormatException e) {
9102 reportSettingsProblem(Log.WARN,
9103 "Error in package manager settings: package "
9104 + name + " has bad userId " + idStr + " at "
9105 + parser.getPositionDescription());
9106 }
9107 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009108 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009109 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009110 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009111 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009112 final String enabledStr = parser.getAttributeValue(null, "enabled");
9113 if (enabledStr != null) {
9114 if (enabledStr.equalsIgnoreCase("true")) {
9115 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9116 } else if (enabledStr.equalsIgnoreCase("false")) {
9117 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9118 } else if (enabledStr.equalsIgnoreCase("default")) {
9119 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9120 } else {
9121 reportSettingsProblem(Log.WARN,
9122 "Error in package manager settings: package "
9123 + name + " has bad enabled value: " + idStr
9124 + " at " + parser.getPositionDescription());
9125 }
9126 } else {
9127 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9128 }
9129 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9130 if (installStatusStr != null) {
9131 if (installStatusStr.equalsIgnoreCase("false")) {
9132 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9133 } else {
9134 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9135 }
9136 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009138 int outerDepth = parser.getDepth();
9139 int type;
9140 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9141 && (type != XmlPullParser.END_TAG
9142 || parser.getDepth() > outerDepth)) {
9143 if (type == XmlPullParser.END_TAG
9144 || type == XmlPullParser.TEXT) {
9145 continue;
9146 }
9147
9148 String tagName = parser.getName();
9149 if (tagName.equals("disabled-components")) {
9150 readDisabledComponentsLP(packageSetting, parser);
9151 } else if (tagName.equals("enabled-components")) {
9152 readEnabledComponentsLP(packageSetting, parser);
9153 } else if (tagName.equals("sigs")) {
9154 packageSetting.signatures.readXml(parser, mPastSignatures);
9155 } else if (tagName.equals("perms")) {
9156 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009157 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009158 packageSetting.permissionsFixed = true;
9159 } else {
9160 reportSettingsProblem(Log.WARN,
9161 "Unknown element under <package>: "
9162 + parser.getName());
9163 XmlUtils.skipCurrentTag(parser);
9164 }
9165 }
9166 } else {
9167 XmlUtils.skipCurrentTag(parser);
9168 }
9169 }
9170
9171 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9172 XmlPullParser parser)
9173 throws IOException, XmlPullParserException {
9174 int outerDepth = parser.getDepth();
9175 int type;
9176 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9177 && (type != XmlPullParser.END_TAG
9178 || parser.getDepth() > outerDepth)) {
9179 if (type == XmlPullParser.END_TAG
9180 || type == XmlPullParser.TEXT) {
9181 continue;
9182 }
9183
9184 String tagName = parser.getName();
9185 if (tagName.equals("item")) {
9186 String name = parser.getAttributeValue(null, "name");
9187 if (name != null) {
9188 packageSetting.disabledComponents.add(name.intern());
9189 } else {
9190 reportSettingsProblem(Log.WARN,
9191 "Error in package manager settings: <disabled-components> has"
9192 + " no name at " + parser.getPositionDescription());
9193 }
9194 } else {
9195 reportSettingsProblem(Log.WARN,
9196 "Unknown element under <disabled-components>: "
9197 + parser.getName());
9198 }
9199 XmlUtils.skipCurrentTag(parser);
9200 }
9201 }
9202
9203 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9204 XmlPullParser parser)
9205 throws IOException, XmlPullParserException {
9206 int outerDepth = parser.getDepth();
9207 int type;
9208 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9209 && (type != XmlPullParser.END_TAG
9210 || parser.getDepth() > outerDepth)) {
9211 if (type == XmlPullParser.END_TAG
9212 || type == XmlPullParser.TEXT) {
9213 continue;
9214 }
9215
9216 String tagName = parser.getName();
9217 if (tagName.equals("item")) {
9218 String name = parser.getAttributeValue(null, "name");
9219 if (name != null) {
9220 packageSetting.enabledComponents.add(name.intern());
9221 } else {
9222 reportSettingsProblem(Log.WARN,
9223 "Error in package manager settings: <enabled-components> has"
9224 + " no name at " + parser.getPositionDescription());
9225 }
9226 } else {
9227 reportSettingsProblem(Log.WARN,
9228 "Unknown element under <enabled-components>: "
9229 + parser.getName());
9230 }
9231 XmlUtils.skipCurrentTag(parser);
9232 }
9233 }
9234
9235 private void readSharedUserLP(XmlPullParser parser)
9236 throws XmlPullParserException, IOException {
9237 String name = null;
9238 String idStr = null;
9239 int pkgFlags = 0;
9240 SharedUserSetting su = null;
9241 try {
9242 name = parser.getAttributeValue(null, "name");
9243 idStr = parser.getAttributeValue(null, "userId");
9244 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9245 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9246 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9247 }
9248 if (name == null) {
9249 reportSettingsProblem(Log.WARN,
9250 "Error in package manager settings: <shared-user> has no name at "
9251 + parser.getPositionDescription());
9252 } else if (userId == 0) {
9253 reportSettingsProblem(Log.WARN,
9254 "Error in package manager settings: shared-user "
9255 + name + " has bad userId " + idStr + " at "
9256 + parser.getPositionDescription());
9257 } else {
9258 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9259 reportSettingsProblem(Log.ERROR,
9260 "Occurred while parsing settings at "
9261 + parser.getPositionDescription());
9262 }
9263 }
9264 } catch (NumberFormatException e) {
9265 reportSettingsProblem(Log.WARN,
9266 "Error in package manager settings: package "
9267 + name + " has bad userId " + idStr + " at "
9268 + parser.getPositionDescription());
9269 };
9270
9271 if (su != null) {
9272 int outerDepth = parser.getDepth();
9273 int type;
9274 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9275 && (type != XmlPullParser.END_TAG
9276 || parser.getDepth() > outerDepth)) {
9277 if (type == XmlPullParser.END_TAG
9278 || type == XmlPullParser.TEXT) {
9279 continue;
9280 }
9281
9282 String tagName = parser.getName();
9283 if (tagName.equals("sigs")) {
9284 su.signatures.readXml(parser, mPastSignatures);
9285 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009286 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009287 } else {
9288 reportSettingsProblem(Log.WARN,
9289 "Unknown element under <shared-user>: "
9290 + parser.getName());
9291 XmlUtils.skipCurrentTag(parser);
9292 }
9293 }
9294
9295 } else {
9296 XmlUtils.skipCurrentTag(parser);
9297 }
9298 }
9299
9300 private void readGrantedPermissionsLP(XmlPullParser parser,
9301 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9302 int outerDepth = parser.getDepth();
9303 int type;
9304 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9305 && (type != XmlPullParser.END_TAG
9306 || parser.getDepth() > outerDepth)) {
9307 if (type == XmlPullParser.END_TAG
9308 || type == XmlPullParser.TEXT) {
9309 continue;
9310 }
9311
9312 String tagName = parser.getName();
9313 if (tagName.equals("item")) {
9314 String name = parser.getAttributeValue(null, "name");
9315 if (name != null) {
9316 outPerms.add(name.intern());
9317 } else {
9318 reportSettingsProblem(Log.WARN,
9319 "Error in package manager settings: <perms> has"
9320 + " no name at " + parser.getPositionDescription());
9321 }
9322 } else {
9323 reportSettingsProblem(Log.WARN,
9324 "Unknown element under <perms>: "
9325 + parser.getName());
9326 }
9327 XmlUtils.skipCurrentTag(parser);
9328 }
9329 }
9330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009331 private void readPreferredActivitiesLP(XmlPullParser parser)
9332 throws XmlPullParserException, IOException {
9333 int outerDepth = parser.getDepth();
9334 int type;
9335 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9336 && (type != XmlPullParser.END_TAG
9337 || parser.getDepth() > outerDepth)) {
9338 if (type == XmlPullParser.END_TAG
9339 || type == XmlPullParser.TEXT) {
9340 continue;
9341 }
9342
9343 String tagName = parser.getName();
9344 if (tagName.equals("item")) {
9345 PreferredActivity pa = new PreferredActivity(parser);
9346 if (pa.mParseError == null) {
9347 mPreferredActivities.addFilter(pa);
9348 } else {
9349 reportSettingsProblem(Log.WARN,
9350 "Error in package manager settings: <preferred-activity> "
9351 + pa.mParseError + " at "
9352 + parser.getPositionDescription());
9353 }
9354 } else {
9355 reportSettingsProblem(Log.WARN,
9356 "Unknown element under <preferred-activities>: "
9357 + parser.getName());
9358 XmlUtils.skipCurrentTag(parser);
9359 }
9360 }
9361 }
9362
9363 // Returns -1 if we could not find an available UserId to assign
9364 private int newUserIdLP(Object obj) {
9365 // Let's be stupidly inefficient for now...
9366 final int N = mUserIds.size();
9367 for (int i=0; i<N; i++) {
9368 if (mUserIds.get(i) == null) {
9369 mUserIds.set(i, obj);
9370 return FIRST_APPLICATION_UID + i;
9371 }
9372 }
9373
9374 // None left?
9375 if (N >= MAX_APPLICATION_UIDS) {
9376 return -1;
9377 }
9378
9379 mUserIds.add(obj);
9380 return FIRST_APPLICATION_UID + N;
9381 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009383 public PackageSetting getDisabledSystemPkg(String name) {
9384 synchronized(mPackages) {
9385 PackageSetting ps = mDisabledSysPackages.get(name);
9386 return ps;
9387 }
9388 }
9389
9390 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009391 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9392 return true;
9393 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009394 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9395 if (Config.LOGV) {
9396 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9397 + " componentName = " + componentInfo.name);
9398 Log.v(TAG, "enabledComponents: "
9399 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9400 Log.v(TAG, "disabledComponents: "
9401 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9402 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009403 if (packageSettings == null) {
9404 if (false) {
9405 Log.w(TAG, "WAITING FOR DEBUGGER");
9406 Debug.waitForDebugger();
9407 Log.i(TAG, "We will crash!");
9408 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009409 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009410 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009411 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9412 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9413 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9414 return false;
9415 }
9416 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9417 return true;
9418 }
9419 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9420 return false;
9421 }
9422 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009423 }
9424 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009425
9426 // ------- apps on sdcard specific code -------
9427 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009428 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9429 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9430 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009431 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009432
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009433 private String getEncryptKey() {
9434 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009435 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9436 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009437 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009438 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9439 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009440 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009441 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009442 return null;
9443 }
9444 }
9445 return sdEncKey;
9446 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009447 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009448 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009449 } catch (IOException ioe) {
9450 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9451 + ioe);
9452 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009453 }
Rich Cannings8d578832010-09-09 15:12:40 -07009454
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009455 }
9456
Kenny Rootc78a8072010-07-27 15:18:38 -07009457 /* package */ static String getTempContainerId() {
9458 int tmpIdx = 1;
9459 String list[] = PackageHelper.getSecureContainerList();
9460 if (list != null) {
9461 for (final String name : list) {
9462 // Ignore null and non-temporary container entries
9463 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9464 continue;
9465 }
9466
9467 String subStr = name.substring(mTempContainerPrefix.length());
9468 try {
9469 int cid = Integer.parseInt(subStr);
9470 if (cid >= tmpIdx) {
9471 tmpIdx = cid + 1;
9472 }
9473 } catch (NumberFormatException e) {
9474 }
9475 }
9476 }
9477 return mTempContainerPrefix + tmpIdx;
9478 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009479
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009480 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009481 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009482 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009483 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9484 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9485 throw new SecurityException("Media status can only be updated by the system");
9486 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009487 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009488 Log.i(TAG, "Updating external media status from " +
9489 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9490 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009491 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9492 mediaStatus+", mMediaMounted=" + mMediaMounted);
9493 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009494 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9495 reportStatus ? 1 : 0, -1);
9496 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009497 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009498 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009499 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009500 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009501 // Queue up an async operation since the package installation may take a little while.
9502 mHandler.post(new Runnable() {
9503 public void run() {
9504 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009505 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009506 }
9507 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009508 }
9509
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009510 /*
9511 * Collect information of applications on external media, map them
9512 * against existing containers and update information based on current
9513 * mount status. Please note that we always have to report status
9514 * if reportStatus has been set to true especially when unloading packages.
9515 */
9516 private void updateExternalMediaStatusInner(boolean mediaStatus,
9517 boolean reportStatus) {
9518 // Collection of uids
9519 int uidArr[] = null;
9520 // Collection of stale containers
9521 HashSet<String> removeCids = new HashSet<String>();
9522 // Collection of packages on external media with valid containers.
9523 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9524 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009525 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009526 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009527 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009528 } else {
9529 // Process list of secure containers and categorize them
9530 // as active or stale based on their package internal state.
9531 int uidList[] = new int[list.length];
9532 int num = 0;
9533 synchronized (mPackages) {
9534 for (String cid : list) {
9535 SdInstallArgs args = new SdInstallArgs(cid);
9536 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009537 String pkgName = args.getPackageName();
9538 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009539 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9540 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009541 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009542 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009543 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9544 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009545 // The package status is changed only if the code path
9546 // matches between settings and the container id.
9547 if (ps != null && ps.codePathString != null &&
9548 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009549 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9550 " corresponds to pkg : " + pkgName +
9551 " at code path: " + ps.codePathString);
9552 // We do have a valid package installed on sdcard
9553 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009554 int uid = ps.userId;
9555 if (uid != -1) {
9556 uidList[num++] = uid;
9557 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009558 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009559 // Stale container on sdcard. Just delete
9560 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9561 removeCids.add(cid);
9562 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009563 }
9564 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009565
9566 if (num > 0) {
9567 // Sort uid list
9568 Arrays.sort(uidList, 0, num);
9569 // Throw away duplicates
9570 uidArr = new int[num];
9571 uidArr[0] = uidList[0];
9572 int di = 0;
9573 for (int i = 1; i < num; i++) {
9574 if (uidList[i-1] != uidList[i]) {
9575 uidArr[di++] = uidList[i];
9576 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009577 }
9578 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009579 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009580 // Process packages with valid entries.
9581 if (mediaStatus) {
9582 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009583 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009584 startCleaningPackages();
9585 } else {
9586 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009587 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009588 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009589 }
9590
9591 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009592 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009593 int size = pkgList.size();
9594 if (size > 0) {
9595 // Send broadcasts here
9596 Bundle extras = new Bundle();
9597 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9598 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009599 if (uidArr != null) {
9600 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9601 }
9602 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9603 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009604 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009605 }
9606 }
9607
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009608 /*
9609 * Look at potentially valid container ids from processCids
9610 * If package information doesn't match the one on record
9611 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009612 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009613 */
9614 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009615 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009616 ArrayList<String> pkgList = new ArrayList<String>();
9617 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009618 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009619 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009620 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009621 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9622 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009623 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009624 try {
9625 // Make sure there are no container errors first.
9626 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9627 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009628 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009629 " when installing from sdcard");
9630 continue;
9631 }
9632 // Check code path here.
9633 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009634 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009635 " does not match one in settings " + codePath);
9636 continue;
9637 }
9638 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009639 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009640 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009641 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009642 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9643 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009644 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009645 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009646 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009647 retCode = PackageManager.INSTALL_SUCCEEDED;
9648 pkgList.add(pkg.packageName);
9649 // Post process args
9650 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9651 }
9652 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009653 Slog.i(TAG, "Failed to install pkg from " +
9654 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009655 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009656 }
9657
9658 } finally {
9659 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9660 // Don't destroy container here. Wait till gc clears things up.
9661 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009662 }
9663 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009664 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009665 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009666 // If the platform SDK has changed since the last time we booted,
9667 // we need to re-grant app permission to catch any new ones that
9668 // appear. This is really a hack, and means that apps can in some
9669 // cases get permissions that the user didn't initially explicitly
9670 // allow... it would be nice to have some better way to handle
9671 // this situation.
9672 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9673 != mSdkVersion;
9674 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9675 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9676 + "; regranting permissions for external storage");
9677 mSettings.mExternalSdkPlatform = mSdkVersion;
9678
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009679 // Make sure group IDs have been assigned, and any permission
9680 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009681 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009682 // Persist settings
9683 mSettings.writeLP();
9684 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009685 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009686 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009687 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009688 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009689 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009690 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009691 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009692 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009693 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009694 if (removeCids != null) {
9695 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009696 if (cid.startsWith(mTempContainerPrefix)) {
9697 Log.i(TAG, "Destroying stale temporary container " + cid);
9698 PackageHelper.destroySdDir(cid);
9699 } else {
9700 Log.w(TAG, "Container " + cid + " is stale");
9701 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009702 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009703 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009704 }
9705
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009706 /*
9707 * Utility method to unload a list of specified containers
9708 */
9709 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9710 // Just unmount all valid containers.
9711 for (SdInstallArgs arg : cidArgs) {
9712 synchronized (mInstallLock) {
9713 arg.doPostDeleteLI(false);
9714 }
9715 }
9716 }
9717
9718 /*
9719 * Unload packages mounted on external media. This involves deleting
9720 * package data from internal structures, sending broadcasts about
9721 * diabled packages, gc'ing to free up references, unmounting all
9722 * secure containers corresponding to packages on external media, and
9723 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9724 * Please note that we always have to post this message if status has
9725 * been requested no matter what.
9726 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009727 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009728 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009729 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009730 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009731 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009732 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009733 for (SdInstallArgs args : keys) {
9734 String cid = args.cid;
9735 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009736 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009737 // Delete package internally
9738 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9739 synchronized (mInstallLock) {
9740 boolean res = deletePackageLI(pkgName, false,
9741 PackageManager.DONT_DELETE_DATA, outInfo);
9742 if (res) {
9743 pkgList.add(pkgName);
9744 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009745 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009746 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009747 }
9748 }
9749 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009750 // We have to absolutely send UPDATED_MEDIA_STATUS only
9751 // after confirming that all the receivers processed the ordered
9752 // broadcast when packages get disabled, force a gc to clean things up.
9753 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009754 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009755 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9756 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9757 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009758 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9759 reportStatus ? 1 : 0, 1, keys);
9760 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009761 }
9762 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009763 } else {
9764 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9765 reportStatus ? 1 : 0, -1, keys);
9766 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009767 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009768 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009769
9770 public void movePackage(final String packageName,
9771 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009772 mContext.enforceCallingOrSelfPermission(
9773 android.Manifest.permission.MOVE_PACKAGE, null);
9774 int returnCode = PackageManager.MOVE_SUCCEEDED;
9775 int currFlags = 0;
9776 int newFlags = 0;
9777 synchronized (mPackages) {
9778 PackageParser.Package pkg = mPackages.get(packageName);
9779 if (pkg == null) {
9780 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009781 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009782 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009783 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009784 Slog.w(TAG, "Cannot move system application");
9785 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009786 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009787 Slog.w(TAG, "Cannot move forward locked app.");
9788 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009789 } else if (pkg.mOperationPending) {
9790 Slog.w(TAG, "Attempt to move package which has pending operations");
9791 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009792 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009793 // Find install location first
9794 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9795 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9796 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009797 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009798 } else {
9799 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9800 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009801 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9802 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009803 if (newFlags == currFlags) {
9804 Slog.w(TAG, "No move required. Trying to move to same location");
9805 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9806 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009807 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009808 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9809 pkg.mOperationPending = true;
9810 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009811 }
9812 }
9813 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009814 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009815 } else {
9816 Message msg = mHandler.obtainMessage(INIT_COPY);
9817 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009818 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9819 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9820 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009821 msg.obj = mp;
9822 mHandler.sendMessage(msg);
9823 }
9824 }
9825 }
9826
9827 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9828 // Queue up an async operation since the package deletion may take a little while.
9829 mHandler.post(new Runnable() {
9830 public void run() {
9831 mHandler.removeCallbacks(this);
9832 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009833 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9834 int uidArr[] = null;
9835 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009836 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009837 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009838 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009839 Slog.w(TAG, " Package " + mp.packageName +
9840 " doesn't exist. Aborting move");
9841 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9842 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9843 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9844 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9845 " Aborting move and returning error");
9846 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9847 } else {
9848 uidArr = new int[] { pkg.applicationInfo.uid };
9849 pkgList = new ArrayList<String>();
9850 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009851 }
9852 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009853 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9854 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009855 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009856 // Update package code and resource paths
9857 synchronized (mInstallLock) {
9858 synchronized (mPackages) {
9859 PackageParser.Package pkg = mPackages.get(mp.packageName);
9860 // Recheck for package again.
9861 if (pkg == null ) {
9862 Slog.w(TAG, " Package " + mp.packageName +
9863 " doesn't exist. Aborting move");
9864 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9865 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9866 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9867 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9868 " Aborting move and returning error");
9869 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9870 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009871 final String oldCodePath = pkg.mPath;
9872 final String newCodePath = mp.targetArgs.getCodePath();
9873 final String newResPath = mp.targetArgs.getResourcePath();
9874 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009875 pkg.mPath = newCodePath;
9876 // Move dex files around
9877 if (moveDexFilesLI(pkg)
9878 != PackageManager.INSTALL_SUCCEEDED) {
9879 // Moving of dex files failed. Set
9880 // error code and abort move.
9881 pkg.mPath = pkg.mScanPath;
9882 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9883 } else {
9884 pkg.mScanPath = newCodePath;
9885 pkg.applicationInfo.sourceDir = newCodePath;
9886 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009887 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009888 PackageSetting ps = (PackageSetting) pkg.mExtras;
9889 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9890 ps.codePathString = ps.codePath.getPath();
9891 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9892 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009893 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009894 // Set the application info flag correctly.
9895 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9896 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9897 } else {
9898 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9899 }
9900 ps.setFlags(pkg.applicationInfo.flags);
9901 mAppDirs.remove(oldCodePath);
9902 mAppDirs.put(newCodePath, pkg);
9903 // Persist settings
9904 mSettings.writeLP();
9905 }
9906 }
9907 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009908 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009909 // Send resources available broadcast
9910 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009911 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009912 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009913 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009914 // Clean up failed installation
9915 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009916 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009917 }
9918 } else {
9919 // Force a gc to clear things up.
9920 Runtime.getRuntime().gc();
9921 // Delete older code
9922 synchronized (mInstallLock) {
9923 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009924 }
9925 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009926
9927 // Allow more operations on this file if we didn't fail because
9928 // an operation was already pending for this package.
9929 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9930 synchronized (mPackages) {
9931 PackageParser.Package pkg = mPackages.get(mp.packageName);
9932 if (pkg != null) {
9933 pkg.mOperationPending = false;
9934 }
9935 }
9936 }
9937
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009938 IPackageMoveObserver observer = mp.observer;
9939 if (observer != null) {
9940 try {
9941 observer.packageMoved(mp.packageName, returnCode);
9942 } catch (RemoteException e) {
9943 Log.i(TAG, "Observer no longer exists.");
9944 }
9945 }
9946 }
9947 });
9948 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009949
9950 public boolean setInstallLocation(int loc) {
9951 mContext.enforceCallingOrSelfPermission(
9952 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9953 if (getInstallLocation() == loc) {
9954 return true;
9955 }
9956 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9957 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9958 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9959 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9960 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9961 return true;
9962 }
9963 return false;
9964 }
9965
9966 public int getInstallLocation() {
9967 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9968 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9969 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009970}