blob: dbf92ba2aaf21df2cd8da82ab699419efcc6a7ec [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,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005469 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 }
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,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005514 res.removedInfo, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 // 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,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005544 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 }
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,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006012 flags | REMOVE_CHATTY, info, true);
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,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006073 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 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 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006126 if (writeSettings) {
6127 // Save settings now
6128 mSettings.writeLP();
6129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 }
6131 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 /*
6134 * Tries to delete system package.
6135 */
6136 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006137 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 ApplicationInfo applicationInfo = p.applicationInfo;
6139 //applicable for non-partially installed applications only
6140 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006141 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 return false;
6143 }
6144 PackageSetting ps = null;
6145 // Confirm if the system package has been updated
6146 // An updated system app can be deleted. This will also have to restore
6147 // the system pkg from system partition
6148 synchronized (mPackages) {
6149 ps = mSettings.getDisabledSystemPkg(p.packageName);
6150 }
6151 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006152 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 return false;
6154 } else {
6155 Log.i(TAG, "Deleting system pkg from data partition");
6156 }
6157 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006158 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006159 final boolean deleteCodeAndResources;
6160 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006161 // Delete code and resources for downgrades
6162 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006163 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006164 } else {
6165 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006166 deleteCodeAndResources = false;
6167 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006168 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006169 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6170 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 if (!ret) {
6172 return false;
6173 }
6174 synchronized (mPackages) {
6175 // Reinstate the old system package
6176 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006177 // Remove any native libraries from the upgraded package.
6178 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 }
6180 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006181 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006183 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006186 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 return false;
6188 }
6189 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006190 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006191 if (writeSettings) {
6192 mSettings.writeLP();
6193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 }
6195 return true;
6196 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006199 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6200 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 ApplicationInfo applicationInfo = p.applicationInfo;
6202 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006203 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 return false;
6205 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006206 if (outInfo != null) {
6207 outInfo.uid = applicationInfo.uid;
6208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209
6210 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006211 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212
6213 // Delete application code and resources
6214 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006215 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006216 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6217 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6218 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6219 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 }
6221 return true;
6222 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 /*
6225 * This method handles package deletion in general
6226 */
6227 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006228 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6229 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006231 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 return false;
6233 }
6234 PackageParser.Package p;
6235 boolean dataOnly = false;
6236 synchronized (mPackages) {
6237 p = mPackages.get(packageName);
6238 if (p == null) {
6239 //this retrieves partially installed apps
6240 dataOnly = true;
6241 PackageSetting ps = mSettings.mPackages.get(packageName);
6242 if (ps == 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 }
6246 p = ps.pkg;
6247 }
6248 }
6249 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006250 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 return false;
6252 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006254 if (dataOnly) {
6255 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006256 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 return true;
6258 }
6259 // At this point the package should have ApplicationInfo associated with it
6260 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006261 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 return false;
6263 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006264 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006265 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 Log.i(TAG, "Removing system package:"+p.packageName);
6267 // When an updated system application is deleted we delete the existing resources as well and
6268 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006269 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006270 } else {
6271 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006272 // Kill application pre-emptively especially for apps on sd.
6273 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006274 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6275 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006277 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 public void clearApplicationUserData(final String packageName,
6281 final IPackageDataObserver observer) {
6282 mContext.enforceCallingOrSelfPermission(
6283 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6284 // Queue up an async operation since the package deletion may take a little while.
6285 mHandler.post(new Runnable() {
6286 public void run() {
6287 mHandler.removeCallbacks(this);
6288 final boolean succeeded;
6289 synchronized (mInstallLock) {
6290 succeeded = clearApplicationUserDataLI(packageName);
6291 }
6292 if (succeeded) {
6293 // invoke DeviceStorageMonitor's update method to clear any notifications
6294 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6295 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6296 if (dsm != null) {
6297 dsm.updateMemory();
6298 }
6299 }
6300 if(observer != null) {
6301 try {
6302 observer.onRemoveCompleted(packageName, succeeded);
6303 } catch (RemoteException e) {
6304 Log.i(TAG, "Observer no longer exists.");
6305 }
6306 } //end if observer
6307 } //end run
6308 });
6309 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 private boolean clearApplicationUserDataLI(String packageName) {
6312 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006313 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 return false;
6315 }
6316 PackageParser.Package p;
6317 boolean dataOnly = false;
6318 synchronized (mPackages) {
6319 p = mPackages.get(packageName);
6320 if(p == null) {
6321 dataOnly = true;
6322 PackageSetting ps = mSettings.mPackages.get(packageName);
6323 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006324 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 return false;
6326 }
6327 p = ps.pkg;
6328 }
6329 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006330 boolean useEncryptedFSDir = false;
6331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 if(!dataOnly) {
6333 //need to check this only for fully installed applications
6334 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006335 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 return false;
6337 }
6338 final ApplicationInfo applicationInfo = p.applicationInfo;
6339 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006340 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 return false;
6342 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006343 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 }
6345 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006346 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006348 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 + packageName);
6350 return false;
6351 }
6352 }
6353 return true;
6354 }
6355
6356 public void deleteApplicationCacheFiles(final String packageName,
6357 final IPackageDataObserver observer) {
6358 mContext.enforceCallingOrSelfPermission(
6359 android.Manifest.permission.DELETE_CACHE_FILES, null);
6360 // Queue up an async operation since the package deletion may take a little while.
6361 mHandler.post(new Runnable() {
6362 public void run() {
6363 mHandler.removeCallbacks(this);
6364 final boolean succeded;
6365 synchronized (mInstallLock) {
6366 succeded = deleteApplicationCacheFilesLI(packageName);
6367 }
6368 if(observer != null) {
6369 try {
6370 observer.onRemoveCompleted(packageName, succeded);
6371 } catch (RemoteException e) {
6372 Log.i(TAG, "Observer no longer exists.");
6373 }
6374 } //end if observer
6375 } //end run
6376 });
6377 }
6378
6379 private boolean deleteApplicationCacheFilesLI(String packageName) {
6380 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006381 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006382 return false;
6383 }
6384 PackageParser.Package p;
6385 synchronized (mPackages) {
6386 p = mPackages.get(packageName);
6387 }
6388 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006389 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 return false;
6391 }
6392 final ApplicationInfo applicationInfo = p.applicationInfo;
6393 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006394 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 return false;
6396 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006397 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006399 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006401 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 + packageName);
6403 return false;
6404 }
6405 }
6406 return true;
6407 }
6408
6409 public void getPackageSizeInfo(final String packageName,
6410 final IPackageStatsObserver observer) {
6411 mContext.enforceCallingOrSelfPermission(
6412 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6413 // Queue up an async operation since the package deletion may take a little while.
6414 mHandler.post(new Runnable() {
6415 public void run() {
6416 mHandler.removeCallbacks(this);
6417 PackageStats lStats = new PackageStats(packageName);
6418 final boolean succeded;
6419 synchronized (mInstallLock) {
6420 succeded = getPackageSizeInfoLI(packageName, lStats);
6421 }
6422 if(observer != null) {
6423 try {
6424 observer.onGetStatsCompleted(lStats, succeded);
6425 } catch (RemoteException e) {
6426 Log.i(TAG, "Observer no longer exists.");
6427 }
6428 } //end if observer
6429 } //end run
6430 });
6431 }
6432
6433 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6434 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006435 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 return false;
6437 }
6438 PackageParser.Package p;
6439 boolean dataOnly = false;
6440 synchronized (mPackages) {
6441 p = mPackages.get(packageName);
6442 if(p == null) {
6443 dataOnly = true;
6444 PackageSetting ps = mSettings.mPackages.get(packageName);
6445 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006446 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 return false;
6448 }
6449 p = ps.pkg;
6450 }
6451 }
6452 String publicSrcDir = null;
6453 if(!dataOnly) {
6454 final ApplicationInfo applicationInfo = p.applicationInfo;
6455 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006456 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 return false;
6458 }
6459 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6460 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006461 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 if (mInstaller != null) {
6463 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006464 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006465 if (res < 0) {
6466 return false;
6467 } else {
6468 return true;
6469 }
6470 }
6471 return true;
6472 }
6473
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006476 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 }
6478
6479 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006480 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 }
6482
6483 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006484 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 }
6486
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006487 int getUidTargetSdkVersionLockedLP(int uid) {
6488 Object obj = mSettings.getUserIdLP(uid);
6489 if (obj instanceof SharedUserSetting) {
6490 SharedUserSetting sus = (SharedUserSetting)obj;
6491 final int N = sus.packages.size();
6492 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6493 Iterator<PackageSetting> it = sus.packages.iterator();
6494 int i=0;
6495 while (it.hasNext()) {
6496 PackageSetting ps = it.next();
6497 if (ps.pkg != null) {
6498 int v = ps.pkg.applicationInfo.targetSdkVersion;
6499 if (v < vers) vers = v;
6500 }
6501 }
6502 return vers;
6503 } else if (obj instanceof PackageSetting) {
6504 PackageSetting ps = (PackageSetting)obj;
6505 if (ps.pkg != null) {
6506 return ps.pkg.applicationInfo.targetSdkVersion;
6507 }
6508 }
6509 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6510 }
6511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006512 public void addPreferredActivity(IntentFilter filter, int match,
6513 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006514 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006515 if (mContext.checkCallingOrSelfPermission(
6516 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6517 != PackageManager.PERMISSION_GRANTED) {
6518 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6519 < Build.VERSION_CODES.FROYO) {
6520 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6521 + Binder.getCallingUid());
6522 return;
6523 }
6524 mContext.enforceCallingOrSelfPermission(
6525 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6526 }
6527
6528 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6530 mSettings.mPreferredActivities.addFilter(
6531 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006532 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 }
6534 }
6535
Satish Sampath8dbe6122009-06-02 23:35:54 +01006536 public void replacePreferredActivity(IntentFilter filter, int match,
6537 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006538 if (filter.countActions() != 1) {
6539 throw new IllegalArgumentException(
6540 "replacePreferredActivity expects filter to have only 1 action.");
6541 }
6542 if (filter.countCategories() != 1) {
6543 throw new IllegalArgumentException(
6544 "replacePreferredActivity expects filter to have only 1 category.");
6545 }
6546 if (filter.countDataAuthorities() != 0
6547 || filter.countDataPaths() != 0
6548 || filter.countDataSchemes() != 0
6549 || filter.countDataTypes() != 0) {
6550 throw new IllegalArgumentException(
6551 "replacePreferredActivity expects filter to have no data authorities, " +
6552 "paths, schemes or types.");
6553 }
6554 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006555 if (mContext.checkCallingOrSelfPermission(
6556 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6557 != PackageManager.PERMISSION_GRANTED) {
6558 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6559 < Build.VERSION_CODES.FROYO) {
6560 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6561 + Binder.getCallingUid());
6562 return;
6563 }
6564 mContext.enforceCallingOrSelfPermission(
6565 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6566 }
6567
Satish Sampath8dbe6122009-06-02 23:35:54 +01006568 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6569 String action = filter.getAction(0);
6570 String category = filter.getCategory(0);
6571 while (it.hasNext()) {
6572 PreferredActivity pa = it.next();
6573 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6574 it.remove();
6575 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6576 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6577 }
6578 }
6579 addPreferredActivity(filter, match, set, activity);
6580 }
6581 }
6582
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006585 int uid = Binder.getCallingUid();
6586 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006587 if (pkg == null || pkg.applicationInfo.uid != uid) {
6588 if (mContext.checkCallingOrSelfPermission(
6589 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6590 != PackageManager.PERMISSION_GRANTED) {
6591 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6592 < Build.VERSION_CODES.FROYO) {
6593 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6594 + Binder.getCallingUid());
6595 return;
6596 }
6597 mContext.enforceCallingOrSelfPermission(
6598 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6599 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006600 }
6601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006603 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 }
6605 }
6606 }
6607
6608 boolean clearPackagePreferredActivitiesLP(String packageName) {
6609 boolean changed = false;
6610 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6611 while (it.hasNext()) {
6612 PreferredActivity pa = it.next();
6613 if (pa.mActivity.getPackageName().equals(packageName)) {
6614 it.remove();
6615 changed = true;
6616 }
6617 }
6618 return changed;
6619 }
6620
6621 public int getPreferredActivities(List<IntentFilter> outFilters,
6622 List<ComponentName> outActivities, String packageName) {
6623
6624 int num = 0;
6625 synchronized (mPackages) {
6626 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6627 while (it.hasNext()) {
6628 PreferredActivity pa = it.next();
6629 if (packageName == null
6630 || pa.mActivity.getPackageName().equals(packageName)) {
6631 if (outFilters != null) {
6632 outFilters.add(new IntentFilter(pa));
6633 }
6634 if (outActivities != null) {
6635 outActivities.add(pa.mActivity);
6636 }
6637 }
6638 }
6639 }
6640
6641 return num;
6642 }
6643
6644 public void setApplicationEnabledSetting(String appPackageName,
6645 int newState, int flags) {
6646 setEnabledSetting(appPackageName, null, newState, flags);
6647 }
6648
6649 public void setComponentEnabledSetting(ComponentName componentName,
6650 int newState, int flags) {
6651 setEnabledSetting(componentName.getPackageName(),
6652 componentName.getClassName(), newState, flags);
6653 }
6654
6655 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006656 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006657 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6658 || newState == COMPONENT_ENABLED_STATE_ENABLED
6659 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6660 throw new IllegalArgumentException("Invalid new component state: "
6661 + newState);
6662 }
6663 PackageSetting pkgSetting;
6664 final int uid = Binder.getCallingUid();
6665 final int permission = mContext.checkCallingPermission(
6666 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6667 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006668 boolean sendNow = false;
6669 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006670 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006672 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006674 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006676 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006678 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 }
6680 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006681 "Unknown component: " + packageName
6682 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 }
6684 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6685 throw new SecurityException(
6686 "Permission Denial: attempt to change component state from pid="
6687 + Binder.getCallingPid()
6688 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6689 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006690 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006692 if (pkgSetting.enabled == newState) {
6693 // Nothing to do
6694 return;
6695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006697 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 } else {
6699 // We're dealing with a component level state change
6700 switch (newState) {
6701 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006702 if (!pkgSetting.enableComponentLP(className)) {
6703 return;
6704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 break;
6706 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006707 if (!pkgSetting.disableComponentLP(className)) {
6708 return;
6709 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 break;
6711 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006712 if (!pkgSetting.restoreComponentLP(className)) {
6713 return;
6714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 break;
6716 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006717 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006718 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 }
6720 }
6721 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006722 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006723 components = mPendingBroadcasts.get(packageName);
6724 boolean newPackage = components == null;
6725 if (newPackage) {
6726 components = new ArrayList<String>();
6727 }
6728 if (!components.contains(componentName)) {
6729 components.add(componentName);
6730 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006731 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6732 sendNow = true;
6733 // Purge entry from pending broadcast list if another one exists already
6734 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006735 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006736 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006737 if (newPackage) {
6738 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006739 }
6740 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6741 // Schedule a message
6742 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6743 }
6744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 long callingId = Binder.clearCallingIdentity();
6748 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006749 if (sendNow) {
6750 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006751 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006753 } finally {
6754 Binder.restoreCallingIdentity(callingId);
6755 }
6756 }
6757
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006758 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006759 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6760 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6761 + " components=" + componentNames);
6762 Bundle extras = new Bundle(4);
6763 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6764 String nameList[] = new String[componentNames.size()];
6765 componentNames.toArray(nameList);
6766 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006767 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6768 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006769 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006770 }
6771
Jacek Surazski65e13172009-04-28 15:26:38 +02006772 public String getInstallerPackageName(String packageName) {
6773 synchronized (mPackages) {
6774 PackageSetting pkg = mSettings.mPackages.get(packageName);
6775 if (pkg == null) {
6776 throw new IllegalArgumentException("Unknown package: " + packageName);
6777 }
6778 return pkg.installerPackageName;
6779 }
6780 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 public int getApplicationEnabledSetting(String appPackageName) {
6783 synchronized (mPackages) {
6784 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6785 if (pkg == null) {
6786 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6787 }
6788 return pkg.enabled;
6789 }
6790 }
6791
6792 public int getComponentEnabledSetting(ComponentName componentName) {
6793 synchronized (mPackages) {
6794 final String packageNameStr = componentName.getPackageName();
6795 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6796 if (pkg == null) {
6797 throw new IllegalArgumentException("Unknown component: " + componentName);
6798 }
6799 final String classNameStr = componentName.getClassName();
6800 return pkg.currentEnabledStateLP(classNameStr);
6801 }
6802 }
6803
6804 public void enterSafeMode() {
6805 if (!mSystemReady) {
6806 mSafeMode = true;
6807 }
6808 }
6809
6810 public void systemReady() {
6811 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006812
6813 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006814 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006815 mContext.getContentResolver(),
6816 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006817 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006818 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006819 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006821 }
6822
6823 public boolean isSafeMode() {
6824 return mSafeMode;
6825 }
6826
6827 public boolean hasSystemUidErrors() {
6828 return mHasSystemUidErrors;
6829 }
6830
6831 static String arrayToString(int[] array) {
6832 StringBuffer buf = new StringBuffer(128);
6833 buf.append('[');
6834 if (array != null) {
6835 for (int i=0; i<array.length; i++) {
6836 if (i > 0) buf.append(", ");
6837 buf.append(array[i]);
6838 }
6839 }
6840 buf.append(']');
6841 return buf.toString();
6842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 @Override
6845 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6846 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6847 != PackageManager.PERMISSION_GRANTED) {
6848 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6849 + Binder.getCallingPid()
6850 + ", uid=" + Binder.getCallingUid()
6851 + " without permission "
6852 + android.Manifest.permission.DUMP);
6853 return;
6854 }
6855
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006856 boolean dumpStar = true;
6857 boolean dumpLibs = false;
6858 boolean dumpFeatures = false;
6859 boolean dumpResolvers = false;
6860 boolean dumpPermissions = false;
6861 boolean dumpPackages = false;
6862 boolean dumpSharedUsers = false;
6863 boolean dumpMessages = false;
6864 boolean dumpProviders = false;
6865
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006866 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006867 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006868
6869 int opti = 0;
6870 while (opti < args.length) {
6871 String opt = args[opti];
6872 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6873 break;
6874 }
6875 opti++;
6876 if ("-a".equals(opt)) {
6877 // Right now we only know how to print all.
6878 } else if ("-h".equals(opt)) {
6879 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006880 pw.println(" [-h] [-f] [cmd] ...");
6881 pw.println(" -f: print details of intent filters");
6882 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006883 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006884 pw.println(" l[ibraries]: list known shared libraries");
6885 pw.println(" f[ibraries]: list device features");
6886 pw.println(" r[esolvers]: dump intent resolvers");
6887 pw.println(" perm[issions]: dump permissions");
6888 pw.println(" prov[iders]: dump content providers");
6889 pw.println(" p[ackages]: dump installed packages");
6890 pw.println(" s[hared-users]: dump shared user IDs");
6891 pw.println(" m[essages]: print collected runtime messages");
6892 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006893 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006894 } else if ("-f".equals(opt)) {
6895 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006896 } else {
6897 pw.println("Unknown argument: " + opt + "; use -h for help");
6898 }
6899 }
6900
6901 // Is the caller requesting to dump a particular piece of data?
6902 if (opti < args.length) {
6903 String cmd = args[opti];
6904 opti++;
6905 // Is this a package name?
6906 if ("android".equals(cmd) || cmd.contains(".")) {
6907 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006908 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
6909 dumpStar = false;
6910 dumpLibs = true;
6911 } else if ("f".equals(cmd) || "features".equals(cmd)) {
6912 dumpStar = false;
6913 dumpFeatures = true;
6914 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
6915 dumpStar = false;
6916 dumpResolvers = true;
6917 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
6918 dumpStar = false;
6919 dumpPermissions = true;
6920 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
6921 dumpStar = false;
6922 dumpPackages = true;
6923 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
6924 dumpStar = false;
6925 dumpSharedUsers = true;
6926 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
6927 dumpStar = false;
6928 dumpProviders = true;
6929 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
6930 dumpStar = false;
6931 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006932 }
6933 }
6934
6935 boolean printedTitle = false;
6936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006938 if ((dumpStar || dumpLibs) && packageName == null) {
6939 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006940 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006941 pw.println("Libraries:");
6942 Iterator<String> it = mSharedLibraries.keySet().iterator();
6943 while (it.hasNext()) {
6944 String name = it.next();
6945 pw.print(" ");
6946 pw.print(name);
6947 pw.print(" -> ");
6948 pw.println(mSharedLibraries.get(name));
6949 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006950 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006951
6952 if ((dumpStar || dumpFeatures) && packageName == null) {
6953 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006954 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006955 pw.println("Features:");
6956 Iterator<String> it = mAvailableFeatures.keySet().iterator();
6957 while (it.hasNext()) {
6958 String name = it.next();
6959 pw.print(" ");
6960 pw.println(name);
6961 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006962 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006963
6964 if (dumpStar || dumpResolvers) {
6965 if (mActivities.dump(pw, printedTitle
6966 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
6967 " ", packageName, showFilters)) {
6968 printedTitle = true;
6969 }
6970 if (mReceivers.dump(pw, printedTitle
6971 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6972 " ", packageName, showFilters)) {
6973 printedTitle = true;
6974 }
6975 if (mServices.dump(pw, printedTitle
6976 ? "\nService Resolver Table:" : "Service Resolver Table:",
6977 " ", packageName, showFilters)) {
6978 printedTitle = true;
6979 }
6980 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6981 ? "\nPreferred Activities:" : "Preferred Activities:",
6982 " ", packageName, showFilters)) {
6983 printedTitle = true;
6984 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006985 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006986
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006987 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006988 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006989 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006990 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6991 continue;
6992 }
6993 if (!printedSomething) {
6994 if (printedTitle) pw.println(" ");
6995 pw.println("Permissions:");
6996 printedSomething = true;
6997 printedTitle = true;
6998 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006999 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7000 pw.print(Integer.toHexString(System.identityHashCode(p)));
7001 pw.println("):");
7002 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7003 pw.print(" uid="); pw.print(p.uid);
7004 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007005 pw.print(" type="); pw.print(p.type);
7006 pw.print(" prot="); pw.println(p.protectionLevel);
7007 if (p.packageSetting != null) {
7008 pw.print(" packageSetting="); pw.println(p.packageSetting);
7009 }
7010 if (p.perm != null) {
7011 pw.print(" perm="); pw.println(p.perm);
7012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007013 }
7014 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007015
7016 if (dumpStar || dumpProviders) {
7017 printedSomething = false;
7018 for (PackageParser.Provider p : mProviders.values()) {
7019 if (packageName != null && !packageName.equals(p.info.packageName)) {
7020 continue;
7021 }
7022 if (!printedSomething) {
7023 if (printedTitle) pw.println(" ");
7024 pw.println("Registered ContentProviders:");
7025 printedSomething = true;
7026 printedTitle = true;
7027 }
7028 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7029 pw.println(p.toString());
7030 }
7031 }
7032
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007033 printedSomething = false;
7034 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007035 if (dumpStar || dumpPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007036 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007037 if (packageName != null && !packageName.equals(ps.realName)
7038 && !packageName.equals(ps.name)) {
7039 continue;
7040 }
7041 if (!printedSomething) {
7042 if (printedTitle) pw.println(" ");
7043 pw.println("Packages:");
7044 printedSomething = true;
7045 printedTitle = true;
7046 }
7047 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007048 pw.print(" Package [");
7049 pw.print(ps.realName != null ? ps.realName : ps.name);
7050 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007051 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7052 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007053 if (ps.realName != null) {
7054 pw.print(" compat name="); pw.println(ps.name);
7055 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007056 pw.print(" userId="); pw.print(ps.userId);
7057 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7058 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7059 pw.print(" pkg="); pw.println(ps.pkg);
7060 pw.print(" codePath="); pw.println(ps.codePathString);
7061 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007062 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007063 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007064 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007065 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007066 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007067 if (ps.pkg.mOperationPending) {
7068 pw.println(" mOperationPending=true");
7069 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007070 pw.print(" supportsScreens=[");
7071 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007072 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007073 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7074 if (!first) pw.print(", ");
7075 first = false;
7076 pw.print("small");
7077 }
7078 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007079 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007080 if (!first) pw.print(", ");
7081 first = false;
7082 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007083 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007084 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007085 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007086 if (!first) pw.print(", ");
7087 first = false;
7088 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007089 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007090 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007091 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007092 if (!first) pw.print(", ");
7093 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007094 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007095 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007096 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007097 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007098 if (!first) pw.print(", ");
7099 first = false;
7100 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007101 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007102 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007103 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7104 if (!first) pw.print(", ");
7105 first = false;
7106 pw.print("anyDensity");
7107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007108 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007109 pw.println("]");
Kenny Root7d794fb2010-09-13 16:29:49 -07007110 pw.print(" timeStamp="); pw.println(String.valueOf(ps.timeStamp));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007111 pw.print(" signatures="); pw.println(ps.signatures);
7112 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007113 pw.print(" haveGids="); pw.println(ps.haveGids);
7114 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007115 pw.print(" installStatus="); pw.print(ps.installStatus);
7116 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 if (ps.disabledComponents.size() > 0) {
7118 pw.println(" disabledComponents:");
7119 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007120 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007121 }
7122 }
7123 if (ps.enabledComponents.size() > 0) {
7124 pw.println(" enabledComponents:");
7125 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007126 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007127 }
7128 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007129 if (ps.grantedPermissions.size() > 0) {
7130 pw.println(" grantedPermissions:");
7131 for (String s : ps.grantedPermissions) {
7132 pw.print(" "); pw.println(s);
7133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007135 }
7136 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007137 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007138 if (dumpStar || dumpPackages) {
7139 if (mSettings.mRenamedPackages.size() > 0) {
7140 for (HashMap.Entry<String, String> e
7141 : mSettings.mRenamedPackages.entrySet()) {
7142 if (packageName != null && !packageName.equals(e.getKey())
7143 && !packageName.equals(e.getValue())) {
7144 continue;
7145 }
7146 if (!printedSomething) {
7147 if (printedTitle) pw.println(" ");
7148 pw.println("Renamed packages:");
7149 printedSomething = true;
7150 printedTitle = true;
7151 }
7152 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7153 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007154 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007155 }
7156 printedSomething = false;
7157 if (mSettings.mDisabledSysPackages.size() > 0) {
7158 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7159 if (packageName != null && !packageName.equals(ps.realName)
7160 && !packageName.equals(ps.name)) {
7161 continue;
7162 }
7163 if (!printedSomething) {
7164 if (printedTitle) pw.println(" ");
7165 pw.println("Hidden system packages:");
7166 printedSomething = true;
7167 printedTitle = true;
7168 }
7169 pw.print(" Package [");
7170 pw.print(ps.realName != null ? ps.realName : ps.name);
7171 pw.print("] (");
7172 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7173 pw.println("):");
7174 if (ps.realName != null) {
7175 pw.print(" compat name="); pw.println(ps.name);
7176 }
7177 pw.print(" userId="); pw.println(ps.userId);
7178 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7179 pw.print(" codePath="); pw.println(ps.codePathString);
7180 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007181 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007182 }
7183 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007184 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007185 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007186 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007187 if (packageName != null && su != packageSharedUser) {
7188 continue;
7189 }
7190 if (!printedSomething) {
7191 if (printedTitle) pw.println(" ");
7192 pw.println("Shared users:");
7193 printedSomething = true;
7194 printedTitle = true;
7195 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007196 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7197 pw.print(Integer.toHexString(System.identityHashCode(su)));
7198 pw.println("):");
7199 pw.print(" userId="); pw.print(su.userId);
7200 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007201 pw.println(" grantedPermissions:");
7202 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007203 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 }
7206 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007207
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007208 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007209 if (printedTitle) pw.println(" ");
7210 printedTitle = true;
7211 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007212 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007213
7214 pw.println(" ");
7215 pw.println("Package warning messages:");
7216 File fname = getSettingsProblemFile();
7217 FileInputStream in;
7218 try {
7219 in = new FileInputStream(fname);
7220 int avail = in.available();
7221 byte[] data = new byte[avail];
7222 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007223 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007224 } catch (FileNotFoundException e) {
7225 } catch (IOException e) {
7226 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 }
7229 }
7230
7231 static final class BasePermission {
7232 final static int TYPE_NORMAL = 0;
7233 final static int TYPE_BUILTIN = 1;
7234 final static int TYPE_DYNAMIC = 2;
7235
7236 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007237 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007238 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007239 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007240 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007241 PackageParser.Permission perm;
7242 PermissionInfo pendingInfo;
7243 int uid;
7244 int[] gids;
7245
7246 BasePermission(String _name, String _sourcePackage, int _type) {
7247 name = _name;
7248 sourcePackage = _sourcePackage;
7249 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007250 // Default to most conservative protection level.
7251 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7252 }
7253
7254 public String toString() {
7255 return "BasePermission{"
7256 + Integer.toHexString(System.identityHashCode(this))
7257 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007258 }
7259 }
7260
7261 static class PackageSignatures {
7262 private Signature[] mSignatures;
7263
7264 PackageSignatures(Signature[] sigs) {
7265 assignSignatures(sigs);
7266 }
7267
7268 PackageSignatures() {
7269 }
7270
7271 void writeXml(XmlSerializer serializer, String tagName,
7272 ArrayList<Signature> pastSignatures) throws IOException {
7273 if (mSignatures == null) {
7274 return;
7275 }
7276 serializer.startTag(null, tagName);
7277 serializer.attribute(null, "count",
7278 Integer.toString(mSignatures.length));
7279 for (int i=0; i<mSignatures.length; i++) {
7280 serializer.startTag(null, "cert");
7281 final Signature sig = mSignatures[i];
7282 final int sigHash = sig.hashCode();
7283 final int numPast = pastSignatures.size();
7284 int j;
7285 for (j=0; j<numPast; j++) {
7286 Signature pastSig = pastSignatures.get(j);
7287 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7288 serializer.attribute(null, "index", Integer.toString(j));
7289 break;
7290 }
7291 }
7292 if (j >= numPast) {
7293 pastSignatures.add(sig);
7294 serializer.attribute(null, "index", Integer.toString(numPast));
7295 serializer.attribute(null, "key", sig.toCharsString());
7296 }
7297 serializer.endTag(null, "cert");
7298 }
7299 serializer.endTag(null, tagName);
7300 }
7301
7302 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7303 throws IOException, XmlPullParserException {
7304 String countStr = parser.getAttributeValue(null, "count");
7305 if (countStr == null) {
7306 reportSettingsProblem(Log.WARN,
7307 "Error in package manager settings: <signatures> has"
7308 + " no count at " + parser.getPositionDescription());
7309 XmlUtils.skipCurrentTag(parser);
7310 }
7311 final int count = Integer.parseInt(countStr);
7312 mSignatures = new Signature[count];
7313 int pos = 0;
7314
7315 int outerDepth = parser.getDepth();
7316 int type;
7317 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7318 && (type != XmlPullParser.END_TAG
7319 || parser.getDepth() > outerDepth)) {
7320 if (type == XmlPullParser.END_TAG
7321 || type == XmlPullParser.TEXT) {
7322 continue;
7323 }
7324
7325 String tagName = parser.getName();
7326 if (tagName.equals("cert")) {
7327 if (pos < count) {
7328 String index = parser.getAttributeValue(null, "index");
7329 if (index != null) {
7330 try {
7331 int idx = Integer.parseInt(index);
7332 String key = parser.getAttributeValue(null, "key");
7333 if (key == null) {
7334 if (idx >= 0 && idx < pastSignatures.size()) {
7335 Signature sig = pastSignatures.get(idx);
7336 if (sig != null) {
7337 mSignatures[pos] = pastSignatures.get(idx);
7338 pos++;
7339 } else {
7340 reportSettingsProblem(Log.WARN,
7341 "Error in package manager settings: <cert> "
7342 + "index " + index + " is not defined at "
7343 + parser.getPositionDescription());
7344 }
7345 } else {
7346 reportSettingsProblem(Log.WARN,
7347 "Error in package manager settings: <cert> "
7348 + "index " + index + " is out of bounds at "
7349 + parser.getPositionDescription());
7350 }
7351 } else {
7352 while (pastSignatures.size() <= idx) {
7353 pastSignatures.add(null);
7354 }
7355 Signature sig = new Signature(key);
7356 pastSignatures.set(idx, sig);
7357 mSignatures[pos] = sig;
7358 pos++;
7359 }
7360 } catch (NumberFormatException e) {
7361 reportSettingsProblem(Log.WARN,
7362 "Error in package manager settings: <cert> "
7363 + "index " + index + " is not a number at "
7364 + parser.getPositionDescription());
7365 }
7366 } else {
7367 reportSettingsProblem(Log.WARN,
7368 "Error in package manager settings: <cert> has"
7369 + " no index at " + parser.getPositionDescription());
7370 }
7371 } else {
7372 reportSettingsProblem(Log.WARN,
7373 "Error in package manager settings: too "
7374 + "many <cert> tags, expected " + count
7375 + " at " + parser.getPositionDescription());
7376 }
7377 } else {
7378 reportSettingsProblem(Log.WARN,
7379 "Unknown element under <cert>: "
7380 + parser.getName());
7381 }
7382 XmlUtils.skipCurrentTag(parser);
7383 }
7384
7385 if (pos < count) {
7386 // Should never happen -- there is an error in the written
7387 // settings -- but if it does we don't want to generate
7388 // a bad array.
7389 Signature[] newSigs = new Signature[pos];
7390 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7391 mSignatures = newSigs;
7392 }
7393 }
7394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007395 private void assignSignatures(Signature[] sigs) {
7396 if (sigs == null) {
7397 mSignatures = null;
7398 return;
7399 }
7400 mSignatures = new Signature[sigs.length];
7401 for (int i=0; i<sigs.length; i++) {
7402 mSignatures[i] = sigs[i];
7403 }
7404 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007406 @Override
7407 public String toString() {
7408 StringBuffer buf = new StringBuffer(128);
7409 buf.append("PackageSignatures{");
7410 buf.append(Integer.toHexString(System.identityHashCode(this)));
7411 buf.append(" [");
7412 if (mSignatures != null) {
7413 for (int i=0; i<mSignatures.length; i++) {
7414 if (i > 0) buf.append(", ");
7415 buf.append(Integer.toHexString(
7416 System.identityHashCode(mSignatures[i])));
7417 }
7418 }
7419 buf.append("]}");
7420 return buf.toString();
7421 }
7422 }
7423
7424 static class PreferredActivity extends IntentFilter {
7425 final int mMatch;
7426 final String[] mSetPackages;
7427 final String[] mSetClasses;
7428 final String[] mSetComponents;
7429 final ComponentName mActivity;
7430 final String mShortActivity;
7431 String mParseError;
7432
7433 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7434 ComponentName activity) {
7435 super(filter);
7436 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7437 mActivity = activity;
7438 mShortActivity = activity.flattenToShortString();
7439 mParseError = null;
7440 if (set != null) {
7441 final int N = set.length;
7442 String[] myPackages = new String[N];
7443 String[] myClasses = new String[N];
7444 String[] myComponents = new String[N];
7445 for (int i=0; i<N; i++) {
7446 ComponentName cn = set[i];
7447 if (cn == null) {
7448 mSetPackages = null;
7449 mSetClasses = null;
7450 mSetComponents = null;
7451 return;
7452 }
7453 myPackages[i] = cn.getPackageName().intern();
7454 myClasses[i] = cn.getClassName().intern();
7455 myComponents[i] = cn.flattenToShortString().intern();
7456 }
7457 mSetPackages = myPackages;
7458 mSetClasses = myClasses;
7459 mSetComponents = myComponents;
7460 } else {
7461 mSetPackages = null;
7462 mSetClasses = null;
7463 mSetComponents = null;
7464 }
7465 }
7466
7467 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7468 IOException {
7469 mShortActivity = parser.getAttributeValue(null, "name");
7470 mActivity = ComponentName.unflattenFromString(mShortActivity);
7471 if (mActivity == null) {
7472 mParseError = "Bad activity name " + mShortActivity;
7473 }
7474 String matchStr = parser.getAttributeValue(null, "match");
7475 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7476 String setCountStr = parser.getAttributeValue(null, "set");
7477 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7478
7479 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7480 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7481 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7482
7483 int setPos = 0;
7484
7485 int outerDepth = parser.getDepth();
7486 int type;
7487 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7488 && (type != XmlPullParser.END_TAG
7489 || parser.getDepth() > outerDepth)) {
7490 if (type == XmlPullParser.END_TAG
7491 || type == XmlPullParser.TEXT) {
7492 continue;
7493 }
7494
7495 String tagName = parser.getName();
7496 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7497 // + parser.getDepth() + " tag=" + tagName);
7498 if (tagName.equals("set")) {
7499 String name = parser.getAttributeValue(null, "name");
7500 if (name == null) {
7501 if (mParseError == null) {
7502 mParseError = "No name in set tag in preferred activity "
7503 + mShortActivity;
7504 }
7505 } else if (setPos >= setCount) {
7506 if (mParseError == null) {
7507 mParseError = "Too many set tags in preferred activity "
7508 + mShortActivity;
7509 }
7510 } else {
7511 ComponentName cn = ComponentName.unflattenFromString(name);
7512 if (cn == null) {
7513 if (mParseError == null) {
7514 mParseError = "Bad set name " + name + " in preferred activity "
7515 + mShortActivity;
7516 }
7517 } else {
7518 myPackages[setPos] = cn.getPackageName();
7519 myClasses[setPos] = cn.getClassName();
7520 myComponents[setPos] = name;
7521 setPos++;
7522 }
7523 }
7524 XmlUtils.skipCurrentTag(parser);
7525 } else if (tagName.equals("filter")) {
7526 //Log.i(TAG, "Starting to parse filter...");
7527 readFromXml(parser);
7528 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7529 // + parser.getDepth() + " tag=" + parser.getName());
7530 } else {
7531 reportSettingsProblem(Log.WARN,
7532 "Unknown element under <preferred-activities>: "
7533 + parser.getName());
7534 XmlUtils.skipCurrentTag(parser);
7535 }
7536 }
7537
7538 if (setPos != setCount) {
7539 if (mParseError == null) {
7540 mParseError = "Not enough set tags (expected " + setCount
7541 + " but found " + setPos + ") in " + mShortActivity;
7542 }
7543 }
7544
7545 mSetPackages = myPackages;
7546 mSetClasses = myClasses;
7547 mSetComponents = myComponents;
7548 }
7549
7550 public void writeToXml(XmlSerializer serializer) throws IOException {
7551 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7552 serializer.attribute(null, "name", mShortActivity);
7553 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7554 serializer.attribute(null, "set", Integer.toString(NS));
7555 for (int s=0; s<NS; s++) {
7556 serializer.startTag(null, "set");
7557 serializer.attribute(null, "name", mSetComponents[s]);
7558 serializer.endTag(null, "set");
7559 }
7560 serializer.startTag(null, "filter");
7561 super.writeToXml(serializer);
7562 serializer.endTag(null, "filter");
7563 }
7564
7565 boolean sameSet(List<ResolveInfo> query, int priority) {
7566 if (mSetPackages == null) return false;
7567 final int NQ = query.size();
7568 final int NS = mSetPackages.length;
7569 int numMatch = 0;
7570 for (int i=0; i<NQ; i++) {
7571 ResolveInfo ri = query.get(i);
7572 if (ri.priority != priority) continue;
7573 ActivityInfo ai = ri.activityInfo;
7574 boolean good = false;
7575 for (int j=0; j<NS; j++) {
7576 if (mSetPackages[j].equals(ai.packageName)
7577 && mSetClasses[j].equals(ai.name)) {
7578 numMatch++;
7579 good = true;
7580 break;
7581 }
7582 }
7583 if (!good) return false;
7584 }
7585 return numMatch == NS;
7586 }
7587 }
7588
7589 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007590 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 HashSet<String> grantedPermissions = new HashSet<String>();
7593 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007595 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007596 setFlags(pkgFlags);
7597 }
7598
7599 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007600 this.pkgFlags = pkgFlags & (
7601 ApplicationInfo.FLAG_SYSTEM |
7602 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007603 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007604 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605 }
7606 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 /**
7609 * Settings base class for pending and resolved classes.
7610 */
7611 static class PackageSettingBase extends GrantedPermissions {
7612 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007613 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007614 File codePath;
7615 String codePathString;
7616 File resourcePath;
7617 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007618 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007619 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007620 long timeStamp;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007621 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007622
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007623 boolean uidError;
7624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007625 PackageSignatures signatures = new PackageSignatures();
7626
7627 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007628 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630 /* Explicitly disabled components */
7631 HashSet<String> disabledComponents = new HashSet<String>(0);
7632 /* Explicitly enabled components */
7633 HashSet<String> enabledComponents = new HashSet<String>(0);
7634 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7635 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007636
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007637 PackageSettingBase origPackage;
7638
Jacek Surazski65e13172009-04-28 15:26:38 +02007639 /* package name of the app that installed this package */
7640 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007642 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007643 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007644 super(pkgFlags);
7645 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007646 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007647 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007648 }
7649
Kenny Root806cc132010-09-12 08:34:19 -07007650 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7651 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 this.codePath = codePath;
7653 this.codePathString = codePath.toString();
7654 this.resourcePath = resourcePath;
7655 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007656 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007657 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658 }
Kenny Root85387d72010-08-26 10:13:11 -07007659
Jacek Surazski65e13172009-04-28 15:26:38 +02007660 public void setInstallerPackageName(String packageName) {
7661 installerPackageName = packageName;
7662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007663
Jacek Surazski65e13172009-04-28 15:26:38 +02007664 String getInstallerPackageName() {
7665 return installerPackageName;
7666 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 public void setInstallStatus(int newStatus) {
7669 installStatus = newStatus;
7670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007672 public int getInstallStatus() {
7673 return installStatus;
7674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007676 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007677 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 }
7679
7680 public void copyFrom(PackageSettingBase base) {
7681 grantedPermissions = base.grantedPermissions;
7682 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007684 timeStamp = base.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007685 signatures = base.signatures;
7686 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007687 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 disabledComponents = base.disabledComponents;
7689 enabledComponents = base.enabledComponents;
7690 enabled = base.enabled;
7691 installStatus = base.installStatus;
7692 }
7693
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007694 boolean enableComponentLP(String componentClassName) {
7695 boolean changed = disabledComponents.remove(componentClassName);
7696 changed |= enabledComponents.add(componentClassName);
7697 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007698 }
7699
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007700 boolean disableComponentLP(String componentClassName) {
7701 boolean changed = enabledComponents.remove(componentClassName);
7702 changed |= disabledComponents.add(componentClassName);
7703 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704 }
7705
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007706 boolean restoreComponentLP(String componentClassName) {
7707 boolean changed = enabledComponents.remove(componentClassName);
7708 changed |= disabledComponents.remove(componentClassName);
7709 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 }
7711
7712 int currentEnabledStateLP(String componentName) {
7713 if (enabledComponents.contains(componentName)) {
7714 return COMPONENT_ENABLED_STATE_ENABLED;
7715 } else if (disabledComponents.contains(componentName)) {
7716 return COMPONENT_ENABLED_STATE_DISABLED;
7717 } else {
7718 return COMPONENT_ENABLED_STATE_DEFAULT;
7719 }
7720 }
7721 }
7722
7723 /**
7724 * Settings data for a particular package we know about.
7725 */
7726 static final class PackageSetting extends PackageSettingBase {
7727 int userId;
7728 PackageParser.Package pkg;
7729 SharedUserSetting sharedUser;
7730
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007731 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007732 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7733 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7734 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007736
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 @Override
7738 public String toString() {
7739 return "PackageSetting{"
7740 + Integer.toHexString(System.identityHashCode(this))
7741 + " " + name + "/" + userId + "}";
7742 }
7743 }
7744
7745 /**
7746 * Settings data for a particular shared user ID we know about.
7747 */
7748 static final class SharedUserSetting extends GrantedPermissions {
7749 final String name;
7750 int userId;
7751 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7752 final PackageSignatures signatures = new PackageSignatures();
7753
7754 SharedUserSetting(String _name, int _pkgFlags) {
7755 super(_pkgFlags);
7756 name = _name;
7757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007759 @Override
7760 public String toString() {
7761 return "SharedUserSetting{"
7762 + Integer.toHexString(System.identityHashCode(this))
7763 + " " + name + "/" + userId + "}";
7764 }
7765 }
7766
7767 /**
7768 * Holds information about dynamic settings.
7769 */
7770 private static final class Settings {
7771 private final File mSettingsFilename;
7772 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007773 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 private final HashMap<String, PackageSetting> mPackages =
7775 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 // List of replaced system applications
7777 final HashMap<String, PackageSetting> mDisabledSysPackages =
7778 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007779
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007780 // These are the last platform API version we were using for
7781 // the apps installed on internal and external storage. It is
7782 // used to grant newer permissions one time during a system upgrade.
7783 int mInternalSdkPlatform;
7784 int mExternalSdkPlatform;
7785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 // The user's preferred activities associated with particular intent
7787 // filters.
7788 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7789 new IntentResolver<PreferredActivity, PreferredActivity>() {
7790 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007791 protected String packageForFilter(PreferredActivity filter) {
7792 return filter.mActivity.getPackageName();
7793 }
7794 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007795 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007797 out.print(prefix); out.print(
7798 Integer.toHexString(System.identityHashCode(filter)));
7799 out.print(' ');
7800 out.print(filter.mActivity.flattenToShortString());
7801 out.print(" match=0x");
7802 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007804 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007806 out.print(prefix); out.print(" ");
7807 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 }
7809 }
7810 }
7811 };
7812 private final HashMap<String, SharedUserSetting> mSharedUsers =
7813 new HashMap<String, SharedUserSetting>();
7814 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7815 private final SparseArray<Object> mOtherUserIds =
7816 new SparseArray<Object>();
7817
7818 // For reading/writing settings file.
7819 private final ArrayList<Signature> mPastSignatures =
7820 new ArrayList<Signature>();
7821
7822 // Mapping from permission names to info about them.
7823 final HashMap<String, BasePermission> mPermissions =
7824 new HashMap<String, BasePermission>();
7825
7826 // Mapping from permission tree names to info about them.
7827 final HashMap<String, BasePermission> mPermissionTrees =
7828 new HashMap<String, BasePermission>();
7829
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007830 // Packages that have been uninstalled and still need their external
7831 // storage data deleted.
7832 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7833
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007834 // Packages that have been renamed since they were first installed.
7835 // Keys are the new names of the packages, values are the original
7836 // names. The packages appear everwhere else under their original
7837 // names.
7838 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007840 private final StringBuilder mReadMessages = new StringBuilder();
7841
7842 private static final class PendingPackage extends PackageSettingBase {
7843 final int sharedId;
7844
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007845 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007846 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7847 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7848 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 this.sharedId = sharedId;
7850 }
7851 }
7852 private final ArrayList<PendingPackage> mPendingPackages
7853 = new ArrayList<PendingPackage>();
7854
7855 Settings() {
7856 File dataDir = Environment.getDataDirectory();
7857 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007858 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7859 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007860 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007861 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 FileUtils.setPermissions(systemDir.toString(),
7863 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7864 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7865 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007866 FileUtils.setPermissions(systemSecureDir.toString(),
7867 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7868 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7869 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007870 mSettingsFilename = new File(systemDir, "packages.xml");
7871 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007872 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007873 }
7874
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007875 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007876 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007877 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007878 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007879 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007880 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007881 return p;
7882 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007883
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007884 PackageSetting peekPackageLP(String name) {
7885 return mPackages.get(name);
7886 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 PackageSetting p = mPackages.get(name);
7888 if (p != null && p.codePath.getPath().equals(codePath)) {
7889 return p;
7890 }
7891 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007892 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 void setInstallStatus(String pkgName, int status) {
7896 PackageSetting p = mPackages.get(pkgName);
7897 if(p != null) {
7898 if(p.getInstallStatus() != status) {
7899 p.setInstallStatus(status);
7900 }
7901 }
7902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007903
Jacek Surazski65e13172009-04-28 15:26:38 +02007904 void setInstallerPackageName(String pkgName,
7905 String installerPkgName) {
7906 PackageSetting p = mPackages.get(pkgName);
7907 if(p != null) {
7908 p.setInstallerPackageName(installerPkgName);
7909 }
7910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007911
Jacek Surazski65e13172009-04-28 15:26:38 +02007912 String getInstallerPackageName(String pkgName) {
7913 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007914 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007915 }
7916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 int getInstallStatus(String pkgName) {
7918 PackageSetting p = mPackages.get(pkgName);
7919 if(p != null) {
7920 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007922 return -1;
7923 }
7924
7925 SharedUserSetting getSharedUserLP(String name,
7926 int pkgFlags, boolean create) {
7927 SharedUserSetting s = mSharedUsers.get(name);
7928 if (s == null) {
7929 if (!create) {
7930 return null;
7931 }
7932 s = new SharedUserSetting(name, pkgFlags);
7933 if (MULTIPLE_APPLICATION_UIDS) {
7934 s.userId = newUserIdLP(s);
7935 } else {
7936 s.userId = FIRST_APPLICATION_UID;
7937 }
7938 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7939 // < 0 means we couldn't assign a userid; fall out and return
7940 // s, which is currently null
7941 if (s.userId >= 0) {
7942 mSharedUsers.put(name, s);
7943 }
7944 }
7945
7946 return s;
7947 }
7948
7949 int disableSystemPackageLP(String name) {
7950 PackageSetting p = mPackages.get(name);
7951 if(p == null) {
7952 Log.w(TAG, "Package:"+name+" is not an installed package");
7953 return -1;
7954 }
7955 PackageSetting dp = mDisabledSysPackages.get(name);
7956 // always make sure the system package code and resource paths dont change
7957 if(dp == null) {
7958 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7959 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7960 }
7961 mDisabledSysPackages.put(name, p);
7962 }
7963 return removePackageLP(name);
7964 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007966 PackageSetting enableSystemPackageLP(String name) {
7967 PackageSetting p = mDisabledSysPackages.get(name);
7968 if(p == null) {
7969 Log.w(TAG, "Package:"+name+" is not disabled");
7970 return null;
7971 }
7972 // Reset flag in ApplicationInfo object
7973 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7974 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7975 }
Kenny Root806cc132010-09-12 08:34:19 -07007976 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
7977 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007978 mDisabledSysPackages.remove(name);
7979 return ret;
7980 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007981
Kenny Root806cc132010-09-12 08:34:19 -07007982 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
7983 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 PackageSetting p = mPackages.get(name);
7985 if (p != null) {
7986 if (p.userId == uid) {
7987 return p;
7988 }
7989 reportSettingsProblem(Log.ERROR,
7990 "Adding duplicate package, keeping first: " + name);
7991 return null;
7992 }
Kenny Root806cc132010-09-12 08:34:19 -07007993 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
7994 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007995 p.userId = uid;
7996 if (addUserIdLP(uid, p, name)) {
7997 mPackages.put(name, p);
7998 return p;
7999 }
8000 return null;
8001 }
8002
8003 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8004 SharedUserSetting s = mSharedUsers.get(name);
8005 if (s != null) {
8006 if (s.userId == uid) {
8007 return s;
8008 }
8009 reportSettingsProblem(Log.ERROR,
8010 "Adding duplicate shared user, keeping first: " + name);
8011 return null;
8012 }
8013 s = new SharedUserSetting(name, pkgFlags);
8014 s.userId = uid;
8015 if (addUserIdLP(uid, s, name)) {
8016 mSharedUsers.put(name, s);
8017 return s;
8018 }
8019 return null;
8020 }
8021
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008022 // Transfer ownership of permissions from one package to another.
8023 private void transferPermissions(String origPkg, String newPkg) {
8024 // Transfer ownership of permissions to the new package.
8025 for (int i=0; i<2; i++) {
8026 HashMap<String, BasePermission> permissions =
8027 i == 0 ? mPermissionTrees : mPermissions;
8028 for (BasePermission bp : permissions.values()) {
8029 if (origPkg.equals(bp.sourcePackage)) {
8030 if (DEBUG_UPGRADE) Log.v(TAG,
8031 "Moving permission " + bp.name
8032 + " from pkg " + bp.sourcePackage
8033 + " to " + newPkg);
8034 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008035 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008036 bp.perm = null;
8037 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008038 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008039 }
8040 bp.uid = 0;
8041 bp.gids = null;
8042 }
8043 }
8044 }
8045 }
8046
8047 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008048 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008049 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008050 PackageSetting p = mPackages.get(name);
8051 if (p != null) {
8052 if (!p.codePath.equals(codePath)) {
8053 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008054 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008055 // This is an updated system app with versions in both system
8056 // and data partition. Just let the most recent version
8057 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008058 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008059 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008060 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008061 // Just a change in the code path is not an issue, but
8062 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008063 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008064 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008065 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008066 }
8067 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008068 reportSettingsProblem(Log.WARN,
8069 "Package " + name + " shared user changed from "
8070 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8071 + " to "
8072 + (sharedUser != null ? sharedUser.name : "<nothing>")
8073 + "; replacing with new");
8074 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008075 } else {
8076 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8077 // If what we are scanning is a system package, then
8078 // make it so, regardless of whether it was previously
8079 // installed only in the data partition.
8080 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 }
8083 }
8084 if (p == null) {
8085 // Create a new PackageSettings entry. this can end up here because
8086 // of code path mismatch or user id mismatch of an updated system partition
8087 if (!create) {
8088 return null;
8089 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008090 if (origPackage != null) {
8091 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008092 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8093 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008094 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8095 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008096 // Note that we will retain the new package's signature so
8097 // that we can keep its data.
8098 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008099 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008100 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008101 p.sharedUser = origPackage.sharedUser;
8102 p.userId = origPackage.userId;
8103 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008104 mRenamedPackages.put(name, origPackage.name);
8105 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008106 // Update new package state.
8107 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008108 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008109 p = new PackageSetting(name, realName, codePath, resourcePath,
8110 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008111 p.setTimeStamp(codePath.lastModified());
8112 p.sharedUser = sharedUser;
8113 if (sharedUser != null) {
8114 p.userId = sharedUser.userId;
8115 } else if (MULTIPLE_APPLICATION_UIDS) {
8116 // Clone the setting here for disabled system packages
8117 PackageSetting dis = mDisabledSysPackages.get(name);
8118 if (dis != null) {
8119 // For disabled packages a new setting is created
8120 // from the existing user id. This still has to be
8121 // added to list of user id's
8122 // Copy signatures from previous setting
8123 if (dis.signatures.mSignatures != null) {
8124 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8125 }
8126 p.userId = dis.userId;
8127 // Clone permissions
8128 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008129 // Clone component info
8130 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8131 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8132 // Add new setting to list of user ids
8133 addUserIdLP(p.userId, p, name);
8134 } else {
8135 // Assign new user id
8136 p.userId = newUserIdLP(p);
8137 }
8138 } else {
8139 p.userId = FIRST_APPLICATION_UID;
8140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 }
8142 if (p.userId < 0) {
8143 reportSettingsProblem(Log.WARN,
8144 "Package " + name + " could not be assigned a valid uid");
8145 return null;
8146 }
8147 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008148 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008150 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 }
8152 }
8153 return p;
8154 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008155
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008156 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008157 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008158 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008159 final String codePath = pkg.applicationInfo.sourceDir;
8160 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008161 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008162 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008163 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008164 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008165 p.codePath = new File(codePath);
8166 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008167 }
8168 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008169 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008170 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008171 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008172 p.resourcePath = new File(resourcePath);
8173 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008174 }
Kenny Root85387d72010-08-26 10:13:11 -07008175 // Update the native library path if needed
8176 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8177 if (nativeLibraryPath != null
8178 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8179 p.nativeLibraryPathString = nativeLibraryPath;
8180 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008181 // Update version code if needed
8182 if (pkg.mVersionCode != p.versionCode) {
8183 p.versionCode = pkg.mVersionCode;
8184 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008185 // Update signatures if needed.
8186 if (p.signatures.mSignatures == null) {
8187 p.signatures.assignSignatures(pkg.mSignatures);
8188 }
8189 // If this app defines a shared user id initialize
8190 // the shared user signatures as well.
8191 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8192 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8193 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008194 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8195 }
8196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008197 // Utility method that adds a PackageSetting to mPackages and
8198 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008199 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 SharedUserSetting sharedUser) {
8201 mPackages.put(name, p);
8202 if (sharedUser != null) {
8203 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8204 reportSettingsProblem(Log.ERROR,
8205 "Package " + p.name + " was user "
8206 + p.sharedUser + " but is now " + sharedUser
8207 + "; I am not changing its files so it will probably fail!");
8208 p.sharedUser.packages.remove(p);
8209 } else if (p.userId != sharedUser.userId) {
8210 reportSettingsProblem(Log.ERROR,
8211 "Package " + p.name + " was user id " + p.userId
8212 + " but is now user " + sharedUser
8213 + " with id " + sharedUser.userId
8214 + "; I am not changing its files so it will probably fail!");
8215 }
8216
8217 sharedUser.packages.add(p);
8218 p.sharedUser = sharedUser;
8219 p.userId = sharedUser.userId;
8220 }
8221 }
8222
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008223 /*
8224 * Update the shared user setting when a package using
8225 * specifying the shared user id is removed. The gids
8226 * associated with each permission of the deleted package
8227 * are removed from the shared user's gid list only if its
8228 * not in use by other permissions of packages in the
8229 * shared user setting.
8230 */
8231 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008232 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008233 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008234 return;
8235 }
8236 // No sharedUserId
8237 if (deletedPs.sharedUser == null) {
8238 return;
8239 }
8240 SharedUserSetting sus = deletedPs.sharedUser;
8241 // Update permissions
8242 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8243 boolean used = false;
8244 if (!sus.grantedPermissions.contains (eachPerm)) {
8245 continue;
8246 }
8247 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008248 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008249 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008250 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251 used = true;
8252 break;
8253 }
8254 }
8255 if (!used) {
8256 // can safely delete this permission from list
8257 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008258 }
8259 }
8260 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008261 int newGids[] = globalGids;
8262 for (String eachPerm : sus.grantedPermissions) {
8263 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008264 if (bp != null) {
8265 newGids = appendInts(newGids, bp.gids);
8266 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 }
8268 sus.gids = newGids;
8269 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008271 private int removePackageLP(String name) {
8272 PackageSetting p = mPackages.get(name);
8273 if (p != null) {
8274 mPackages.remove(name);
8275 if (p.sharedUser != null) {
8276 p.sharedUser.packages.remove(p);
8277 if (p.sharedUser.packages.size() == 0) {
8278 mSharedUsers.remove(p.sharedUser.name);
8279 removeUserIdLP(p.sharedUser.userId);
8280 return p.sharedUser.userId;
8281 }
8282 } else {
8283 removeUserIdLP(p.userId);
8284 return p.userId;
8285 }
8286 }
8287 return -1;
8288 }
8289
8290 private boolean addUserIdLP(int uid, Object obj, Object name) {
8291 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8292 return false;
8293 }
8294
8295 if (uid >= FIRST_APPLICATION_UID) {
8296 int N = mUserIds.size();
8297 final int index = uid - FIRST_APPLICATION_UID;
8298 while (index >= N) {
8299 mUserIds.add(null);
8300 N++;
8301 }
8302 if (mUserIds.get(index) != null) {
8303 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008304 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008305 + " name=" + name);
8306 return false;
8307 }
8308 mUserIds.set(index, obj);
8309 } else {
8310 if (mOtherUserIds.get(uid) != null) {
8311 reportSettingsProblem(Log.ERROR,
8312 "Adding duplicate shared id: " + uid
8313 + " name=" + name);
8314 return false;
8315 }
8316 mOtherUserIds.put(uid, obj);
8317 }
8318 return true;
8319 }
8320
8321 public Object getUserIdLP(int uid) {
8322 if (uid >= FIRST_APPLICATION_UID) {
8323 int N = mUserIds.size();
8324 final int index = uid - FIRST_APPLICATION_UID;
8325 return index < N ? mUserIds.get(index) : null;
8326 } else {
8327 return mOtherUserIds.get(uid);
8328 }
8329 }
8330
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008331 private Set<String> findPackagesWithFlag(int flag) {
8332 Set<String> ret = new HashSet<String>();
8333 for (PackageSetting ps : mPackages.values()) {
8334 // Has to match atleast all the flag bits set on flag
8335 if ((ps.pkgFlags & flag) == flag) {
8336 ret.add(ps.name);
8337 }
8338 }
8339 return ret;
8340 }
8341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008342 private void removeUserIdLP(int uid) {
8343 if (uid >= FIRST_APPLICATION_UID) {
8344 int N = mUserIds.size();
8345 final int index = uid - FIRST_APPLICATION_UID;
8346 if (index < N) mUserIds.set(index, null);
8347 } else {
8348 mOtherUserIds.remove(uid);
8349 }
8350 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 void writeLP() {
8353 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8354
8355 // Keep the old settings around until we know the new ones have
8356 // been successfully written.
8357 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008358 // Presence of backup settings file indicates that we failed
8359 // to persist settings earlier. So preserve the older
8360 // backup for future reference since the current settings
8361 // might have been corrupted.
8362 if (!mBackupSettingsFilename.exists()) {
8363 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008364 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008365 return;
8366 }
8367 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008368 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008369 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 }
8372
8373 mPastSignatures.clear();
8374
8375 try {
Kenny Root9f306d72010-09-26 11:19:47 -07008376 BufferedOutputStream str = new BufferedOutputStream(new FileOutputStream(
8377 mSettingsFilename));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008378
8379 //XmlSerializer serializer = XmlUtils.serializerInstance();
8380 XmlSerializer serializer = new FastXmlSerializer();
8381 serializer.setOutput(str, "utf-8");
8382 serializer.startDocument(null, true);
8383 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8384
8385 serializer.startTag(null, "packages");
8386
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008387 serializer.startTag(null, "last-platform-version");
8388 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8389 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8390 serializer.endTag(null, "last-platform-version");
8391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008392 serializer.startTag(null, "permission-trees");
8393 for (BasePermission bp : mPermissionTrees.values()) {
8394 writePermission(serializer, bp);
8395 }
8396 serializer.endTag(null, "permission-trees");
8397
8398 serializer.startTag(null, "permissions");
8399 for (BasePermission bp : mPermissions.values()) {
8400 writePermission(serializer, bp);
8401 }
8402 serializer.endTag(null, "permissions");
8403
8404 for (PackageSetting pkg : mPackages.values()) {
8405 writePackage(serializer, pkg);
8406 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008408 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8409 writeDisabledSysPackage(serializer, pkg);
8410 }
8411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008412 serializer.startTag(null, "preferred-activities");
8413 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8414 serializer.startTag(null, "item");
8415 pa.writeToXml(serializer);
8416 serializer.endTag(null, "item");
8417 }
8418 serializer.endTag(null, "preferred-activities");
8419
8420 for (SharedUserSetting usr : mSharedUsers.values()) {
8421 serializer.startTag(null, "shared-user");
8422 serializer.attribute(null, "name", usr.name);
8423 serializer.attribute(null, "userId",
8424 Integer.toString(usr.userId));
8425 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8426 serializer.startTag(null, "perms");
8427 for (String name : usr.grantedPermissions) {
8428 serializer.startTag(null, "item");
8429 serializer.attribute(null, "name", name);
8430 serializer.endTag(null, "item");
8431 }
8432 serializer.endTag(null, "perms");
8433 serializer.endTag(null, "shared-user");
8434 }
8435
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008436 if (mPackagesToBeCleaned.size() > 0) {
8437 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8438 serializer.startTag(null, "cleaning-package");
8439 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8440 serializer.endTag(null, "cleaning-package");
8441 }
8442 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008443
8444 if (mRenamedPackages.size() > 0) {
8445 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8446 serializer.startTag(null, "renamed-package");
8447 serializer.attribute(null, "new", e.getKey());
8448 serializer.attribute(null, "old", e.getValue());
8449 serializer.endTag(null, "renamed-package");
8450 }
8451 }
8452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008453 serializer.endTag(null, "packages");
8454
8455 serializer.endDocument();
8456
8457 str.flush();
8458 str.close();
8459
8460 // New settings successfully written, old ones are no longer
8461 // needed.
8462 mBackupSettingsFilename.delete();
8463 FileUtils.setPermissions(mSettingsFilename.toString(),
8464 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8465 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8466 |FileUtils.S_IROTH,
8467 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008468
8469 // Write package list file now, use a JournaledFile.
8470 //
8471 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8472 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8473
Kenny Root9f306d72010-09-26 11:19:47 -07008474 str = new BufferedOutputStream(new FileOutputStream(journal.chooseForWrite()));
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008475 try {
8476 StringBuilder sb = new StringBuilder();
8477 for (PackageSetting pkg : mPackages.values()) {
8478 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008479 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008480 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8481
8482 // Avoid any application that has a space in its path
8483 // or that is handled by the system.
8484 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8485 continue;
8486
8487 // we store on each line the following information for now:
8488 //
8489 // pkgName - package name
8490 // userId - application-specific user id
8491 // debugFlag - 0 or 1 if the package is debuggable.
8492 // dataPath - path to package's data path
8493 //
8494 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8495 //
8496 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8497 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8498 // system/core/run-as/run-as.c
8499 //
8500 sb.setLength(0);
8501 sb.append(ai.packageName);
8502 sb.append(" ");
8503 sb.append((int)ai.uid);
8504 sb.append(isDebug ? " 1 " : " 0 ");
8505 sb.append(dataPath);
8506 sb.append("\n");
8507 str.write(sb.toString().getBytes());
8508 }
8509 str.flush();
8510 str.close();
8511 journal.commit();
8512 }
8513 catch (Exception e) {
8514 journal.rollback();
8515 }
8516
8517 FileUtils.setPermissions(mPackageListFilename.toString(),
8518 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8519 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8520 |FileUtils.S_IROTH,
8521 -1, -1);
8522
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008523 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524
8525 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008526 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 -08008527 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008528 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 -08008529 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008530 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008531 if (mSettingsFilename.exists()) {
8532 if (!mSettingsFilename.delete()) {
8533 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8534 }
8535 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008536 //Debug.stopMethodTracing();
8537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008538
8539 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008540 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 serializer.startTag(null, "updated-package");
8542 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008543 if (pkg.realName != null) {
8544 serializer.attribute(null, "realName", pkg.realName);
8545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008546 serializer.attribute(null, "codePath", pkg.codePathString);
Kenny Root7d794fb2010-09-13 16:29:49 -07008547 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008548 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008549 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8550 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8551 }
Kenny Root85387d72010-08-26 10:13:11 -07008552 if (pkg.nativeLibraryPathString != null) {
8553 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008555 if (pkg.sharedUser == null) {
8556 serializer.attribute(null, "userId",
8557 Integer.toString(pkg.userId));
8558 } else {
8559 serializer.attribute(null, "sharedUserId",
8560 Integer.toString(pkg.userId));
8561 }
8562 serializer.startTag(null, "perms");
8563 if (pkg.sharedUser == null) {
8564 // If this is a shared user, the permissions will
8565 // be written there. We still need to write an
8566 // empty permissions list so permissionsFixed will
8567 // be set.
8568 for (final String name : pkg.grantedPermissions) {
8569 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008570 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008571 // We only need to write signature or system permissions but this wont
8572 // match the semantics of grantedPermissions. So write all permissions.
8573 serializer.startTag(null, "item");
8574 serializer.attribute(null, "name", name);
8575 serializer.endTag(null, "item");
8576 }
8577 }
8578 }
8579 serializer.endTag(null, "perms");
8580 serializer.endTag(null, "updated-package");
8581 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008582
8583 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008584 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008585 serializer.startTag(null, "package");
8586 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008587 if (pkg.realName != null) {
8588 serializer.attribute(null, "realName", pkg.realName);
8589 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 serializer.attribute(null, "codePath", pkg.codePathString);
8591 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8592 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8593 }
Kenny Root85387d72010-08-26 10:13:11 -07008594 if (pkg.nativeLibraryPathString != null) {
8595 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8596 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008597 serializer.attribute(null, "flags",
8598 Integer.toString(pkg.pkgFlags));
Kenny Root7d794fb2010-09-13 16:29:49 -07008599 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008600 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008601 if (pkg.sharedUser == null) {
8602 serializer.attribute(null, "userId",
8603 Integer.toString(pkg.userId));
8604 } else {
8605 serializer.attribute(null, "sharedUserId",
8606 Integer.toString(pkg.userId));
8607 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008608 if (pkg.uidError) {
8609 serializer.attribute(null, "uidError", "true");
8610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008611 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8612 serializer.attribute(null, "enabled",
8613 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8614 ? "true" : "false");
8615 }
8616 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8617 serializer.attribute(null, "installStatus", "false");
8618 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008619 if (pkg.installerPackageName != null) {
8620 serializer.attribute(null, "installer", pkg.installerPackageName);
8621 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008622 if (pkg.obbPathString != null) {
8623 serializer.attribute(null, "obbPath", pkg.obbPathString);
8624 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008625 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8626 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8627 serializer.startTag(null, "perms");
8628 if (pkg.sharedUser == null) {
8629 // If this is a shared user, the permissions will
8630 // be written there. We still need to write an
8631 // empty permissions list so permissionsFixed will
8632 // be set.
8633 for (final String name : pkg.grantedPermissions) {
8634 serializer.startTag(null, "item");
8635 serializer.attribute(null, "name", name);
8636 serializer.endTag(null, "item");
8637 }
8638 }
8639 serializer.endTag(null, "perms");
8640 }
8641 if (pkg.disabledComponents.size() > 0) {
8642 serializer.startTag(null, "disabled-components");
8643 for (final String name : pkg.disabledComponents) {
8644 serializer.startTag(null, "item");
8645 serializer.attribute(null, "name", name);
8646 serializer.endTag(null, "item");
8647 }
8648 serializer.endTag(null, "disabled-components");
8649 }
8650 if (pkg.enabledComponents.size() > 0) {
8651 serializer.startTag(null, "enabled-components");
8652 for (final String name : pkg.enabledComponents) {
8653 serializer.startTag(null, "item");
8654 serializer.attribute(null, "name", name);
8655 serializer.endTag(null, "item");
8656 }
8657 serializer.endTag(null, "enabled-components");
8658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008660 serializer.endTag(null, "package");
8661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 void writePermission(XmlSerializer serializer, BasePermission bp)
8664 throws XmlPullParserException, java.io.IOException {
8665 if (bp.type != BasePermission.TYPE_BUILTIN
8666 && bp.sourcePackage != null) {
8667 serializer.startTag(null, "item");
8668 serializer.attribute(null, "name", bp.name);
8669 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008670 if (bp.protectionLevel !=
8671 PermissionInfo.PROTECTION_NORMAL) {
8672 serializer.attribute(null, "protection",
8673 Integer.toString(bp.protectionLevel));
8674 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008675 if (DEBUG_SETTINGS) Log.v(TAG,
8676 "Writing perm: name=" + bp.name + " type=" + bp.type);
8677 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8678 PermissionInfo pi = bp.perm != null ? bp.perm.info
8679 : bp.pendingInfo;
8680 if (pi != null) {
8681 serializer.attribute(null, "type", "dynamic");
8682 if (pi.icon != 0) {
8683 serializer.attribute(null, "icon",
8684 Integer.toString(pi.icon));
8685 }
8686 if (pi.nonLocalizedLabel != null) {
8687 serializer.attribute(null, "label",
8688 pi.nonLocalizedLabel.toString());
8689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 }
8691 }
8692 serializer.endTag(null, "item");
8693 }
8694 }
8695
8696 String getReadMessagesLP() {
8697 return mReadMessages.toString();
8698 }
8699
Oscar Montemayora8529f62009-11-18 10:14:20 -08008700 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8702 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008703 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008704 while(its.hasNext()) {
8705 String key = its.next();
8706 PackageSetting ps = mPackages.get(key);
8707 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008708 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 }
8710 }
8711 return ret;
8712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008714 boolean readLP() {
8715 FileInputStream str = null;
8716 if (mBackupSettingsFilename.exists()) {
8717 try {
8718 str = new FileInputStream(mBackupSettingsFilename);
8719 mReadMessages.append("Reading from backup settings file\n");
8720 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008721 if (mSettingsFilename.exists()) {
8722 // If both the backup and settings file exist, we
8723 // ignore the settings since it might have been
8724 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008725 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008726 mSettingsFilename.delete();
8727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 } catch (java.io.IOException e) {
8729 // We'll try for the normal settings file.
8730 }
8731 }
8732
8733 mPastSignatures.clear();
8734
8735 try {
8736 if (str == null) {
8737 if (!mSettingsFilename.exists()) {
8738 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008739 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008740 return false;
8741 }
8742 str = new FileInputStream(mSettingsFilename);
8743 }
8744 XmlPullParser parser = Xml.newPullParser();
8745 parser.setInput(str, null);
8746
8747 int type;
8748 while ((type=parser.next()) != XmlPullParser.START_TAG
8749 && type != XmlPullParser.END_DOCUMENT) {
8750 ;
8751 }
8752
8753 if (type != XmlPullParser.START_TAG) {
8754 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008755 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008756 return false;
8757 }
8758
8759 int outerDepth = parser.getDepth();
8760 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8761 && (type != XmlPullParser.END_TAG
8762 || parser.getDepth() > outerDepth)) {
8763 if (type == XmlPullParser.END_TAG
8764 || type == XmlPullParser.TEXT) {
8765 continue;
8766 }
8767
8768 String tagName = parser.getName();
8769 if (tagName.equals("package")) {
8770 readPackageLP(parser);
8771 } else if (tagName.equals("permissions")) {
8772 readPermissionsLP(mPermissions, parser);
8773 } else if (tagName.equals("permission-trees")) {
8774 readPermissionsLP(mPermissionTrees, parser);
8775 } else if (tagName.equals("shared-user")) {
8776 readSharedUserLP(parser);
8777 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008778 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008779 } else if (tagName.equals("preferred-activities")) {
8780 readPreferredActivitiesLP(parser);
8781 } else if(tagName.equals("updated-package")) {
8782 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008783 } else if (tagName.equals("cleaning-package")) {
8784 String name = parser.getAttributeValue(null, "name");
8785 if (name != null) {
8786 mPackagesToBeCleaned.add(name);
8787 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008788 } else if (tagName.equals("renamed-package")) {
8789 String nname = parser.getAttributeValue(null, "new");
8790 String oname = parser.getAttributeValue(null, "old");
8791 if (nname != null && oname != null) {
8792 mRenamedPackages.put(nname, oname);
8793 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008794 } else if (tagName.equals("last-platform-version")) {
8795 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8796 try {
8797 String internal = parser.getAttributeValue(null, "internal");
8798 if (internal != null) {
8799 mInternalSdkPlatform = Integer.parseInt(internal);
8800 }
8801 String external = parser.getAttributeValue(null, "external");
8802 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008803 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008804 }
8805 } catch (NumberFormatException e) {
8806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008807 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008808 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809 + parser.getName());
8810 XmlUtils.skipCurrentTag(parser);
8811 }
8812 }
8813
8814 str.close();
8815
8816 } catch(XmlPullParserException e) {
8817 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008818 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008819
8820 } catch(java.io.IOException e) {
8821 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008822 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008823
8824 }
8825
8826 int N = mPendingPackages.size();
8827 for (int i=0; i<N; i++) {
8828 final PendingPackage pp = mPendingPackages.get(i);
8829 Object idObj = getUserIdLP(pp.sharedId);
8830 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008831 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008832 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8833 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008834 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008835 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 + pp.name);
8837 continue;
8838 }
8839 p.copyFrom(pp);
8840 } else if (idObj != null) {
8841 String msg = "Bad package setting: package " + pp.name
8842 + " has shared uid " + pp.sharedId
8843 + " that is not a shared uid\n";
8844 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008845 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008846 } else {
8847 String msg = "Bad package setting: package " + pp.name
8848 + " has shared uid " + pp.sharedId
8849 + " that is not defined\n";
8850 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008851 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008852 }
8853 }
8854 mPendingPackages.clear();
8855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008856 mReadMessages.append("Read completed successfully: "
8857 + mPackages.size() + " packages, "
8858 + mSharedUsers.size() + " shared uids\n");
8859
8860 return true;
8861 }
8862
8863 private int readInt(XmlPullParser parser, String ns, String name,
8864 int defValue) {
8865 String v = parser.getAttributeValue(ns, name);
8866 try {
8867 if (v == null) {
8868 return defValue;
8869 }
8870 return Integer.parseInt(v);
8871 } catch (NumberFormatException e) {
8872 reportSettingsProblem(Log.WARN,
8873 "Error in package manager settings: attribute " +
8874 name + " has bad integer value " + v + " at "
8875 + parser.getPositionDescription());
8876 }
8877 return defValue;
8878 }
8879
8880 private void readPermissionsLP(HashMap<String, BasePermission> out,
8881 XmlPullParser parser)
8882 throws IOException, XmlPullParserException {
8883 int outerDepth = parser.getDepth();
8884 int type;
8885 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8886 && (type != XmlPullParser.END_TAG
8887 || parser.getDepth() > outerDepth)) {
8888 if (type == XmlPullParser.END_TAG
8889 || type == XmlPullParser.TEXT) {
8890 continue;
8891 }
8892
8893 String tagName = parser.getName();
8894 if (tagName.equals("item")) {
8895 String name = parser.getAttributeValue(null, "name");
8896 String sourcePackage = parser.getAttributeValue(null, "package");
8897 String ptype = parser.getAttributeValue(null, "type");
8898 if (name != null && sourcePackage != null) {
8899 boolean dynamic = "dynamic".equals(ptype);
8900 BasePermission bp = new BasePermission(name, sourcePackage,
8901 dynamic
8902 ? BasePermission.TYPE_DYNAMIC
8903 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008904 bp.protectionLevel = readInt(parser, null, "protection",
8905 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 if (dynamic) {
8907 PermissionInfo pi = new PermissionInfo();
8908 pi.packageName = sourcePackage.intern();
8909 pi.name = name.intern();
8910 pi.icon = readInt(parser, null, "icon", 0);
8911 pi.nonLocalizedLabel = parser.getAttributeValue(
8912 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008913 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008914 bp.pendingInfo = pi;
8915 }
8916 out.put(bp.name, bp);
8917 } else {
8918 reportSettingsProblem(Log.WARN,
8919 "Error in package manager settings: permissions has"
8920 + " no name at " + parser.getPositionDescription());
8921 }
8922 } else {
8923 reportSettingsProblem(Log.WARN,
8924 "Unknown element reading permissions: "
8925 + parser.getName() + " at "
8926 + parser.getPositionDescription());
8927 }
8928 XmlUtils.skipCurrentTag(parser);
8929 }
8930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008933 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008934 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008935 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 String codePathStr = parser.getAttributeValue(null, "codePath");
8937 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07008938 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008939 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008940 resourcePathStr = codePathStr;
8941 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008942 String version = parser.getAttributeValue(null, "version");
8943 int versionCode = 0;
8944 if (version != null) {
8945 try {
8946 versionCode = Integer.parseInt(version);
8947 } catch (NumberFormatException e) {
8948 }
8949 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008951 int pkgFlags = 0;
8952 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07008953 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
8954 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 String timeStampStr = parser.getAttributeValue(null, "ts");
8956 if (timeStampStr != null) {
8957 try {
8958 long timeStamp = Long.parseLong(timeStampStr);
Kenny Root7d794fb2010-09-13 16:29:49 -07008959 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 } catch (NumberFormatException e) {
8961 }
8962 }
8963 String idStr = parser.getAttributeValue(null, "userId");
8964 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8965 if(ps.userId <= 0) {
8966 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8967 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8968 }
8969 int outerDepth = parser.getDepth();
8970 int type;
8971 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8972 && (type != XmlPullParser.END_TAG
8973 || parser.getDepth() > outerDepth)) {
8974 if (type == XmlPullParser.END_TAG
8975 || type == XmlPullParser.TEXT) {
8976 continue;
8977 }
8978
8979 String tagName = parser.getName();
8980 if (tagName.equals("perms")) {
8981 readGrantedPermissionsLP(parser,
8982 ps.grantedPermissions);
8983 } else {
8984 reportSettingsProblem(Log.WARN,
8985 "Unknown element under <updated-package>: "
8986 + parser.getName());
8987 XmlUtils.skipCurrentTag(parser);
8988 }
8989 }
8990 mDisabledSysPackages.put(name, ps);
8991 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008993 private void readPackageLP(XmlPullParser parser)
8994 throws XmlPullParserException, IOException {
8995 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008996 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008997 String idStr = null;
8998 String sharedIdStr = null;
8999 String codePathStr = null;
9000 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009001 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009002 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009003 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009004 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009005 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009006 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009007 long timeStamp = 0;
9008 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009009 String version = null;
9010 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011 try {
9012 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009013 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009015 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9017 codePathStr = parser.getAttributeValue(null, "codePath");
9018 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009019 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009020 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009021 version = parser.getAttributeValue(null, "version");
9022 if (version != null) {
9023 try {
9024 versionCode = Integer.parseInt(version);
9025 } catch (NumberFormatException e) {
9026 }
9027 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009028 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009029
9030 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009032 try {
9033 pkgFlags = Integer.parseInt(systemStr);
9034 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009035 }
9036 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009037 // For backward compatibility
9038 systemStr = parser.getAttributeValue(null, "system");
9039 if (systemStr != null) {
9040 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9041 } else {
9042 // Old settings that don't specify system... just treat
9043 // them as system, good enough.
9044 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9045 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046 }
Kenny Root7d794fb2010-09-13 16:29:49 -07009047 final String timeStampStr = parser.getAttributeValue(null, "ts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009048 if (timeStampStr != null) {
9049 try {
9050 timeStamp = Long.parseLong(timeStampStr);
9051 } catch (NumberFormatException e) {
9052 }
9053 }
9054 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9055 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9056 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9057 if (resourcePathStr == null) {
9058 resourcePathStr = codePathStr;
9059 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009060 if (realName != null) {
9061 realName = realName.intern();
9062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009063 if (name == null) {
9064 reportSettingsProblem(Log.WARN,
9065 "Error in package manager settings: <package> has no name at "
9066 + parser.getPositionDescription());
9067 } else if (codePathStr == null) {
9068 reportSettingsProblem(Log.WARN,
9069 "Error in package manager settings: <package> has no codePath at "
9070 + parser.getPositionDescription());
9071 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009072 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9073 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9074 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009075 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9076 + ": userId=" + userId + " pkg=" + packageSetting);
9077 if (packageSetting == null) {
9078 reportSettingsProblem(Log.ERROR,
9079 "Failure adding uid " + userId
9080 + " while parsing settings at "
9081 + parser.getPositionDescription());
9082 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009083 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 }
9085 } else if (sharedIdStr != null) {
9086 userId = sharedIdStr != null
9087 ? Integer.parseInt(sharedIdStr) : 0;
9088 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009089 packageSetting = new PendingPackage(name.intern(), realName,
9090 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009091 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009092 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009093 mPendingPackages.add((PendingPackage) packageSetting);
9094 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9095 + ": sharedUserId=" + userId + " pkg="
9096 + packageSetting);
9097 } else {
9098 reportSettingsProblem(Log.WARN,
9099 "Error in package manager settings: package "
9100 + name + " has bad sharedId " + sharedIdStr
9101 + " at " + parser.getPositionDescription());
9102 }
9103 } else {
9104 reportSettingsProblem(Log.WARN,
9105 "Error in package manager settings: package "
9106 + name + " has bad userId " + idStr + " at "
9107 + parser.getPositionDescription());
9108 }
9109 } catch (NumberFormatException e) {
9110 reportSettingsProblem(Log.WARN,
9111 "Error in package manager settings: package "
9112 + name + " has bad userId " + idStr + " at "
9113 + parser.getPositionDescription());
9114 }
9115 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009116 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009117 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009118 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009119 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009120 final String enabledStr = parser.getAttributeValue(null, "enabled");
9121 if (enabledStr != null) {
9122 if (enabledStr.equalsIgnoreCase("true")) {
9123 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9124 } else if (enabledStr.equalsIgnoreCase("false")) {
9125 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9126 } else if (enabledStr.equalsIgnoreCase("default")) {
9127 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9128 } else {
9129 reportSettingsProblem(Log.WARN,
9130 "Error in package manager settings: package "
9131 + name + " has bad enabled value: " + idStr
9132 + " at " + parser.getPositionDescription());
9133 }
9134 } else {
9135 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9136 }
9137 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9138 if (installStatusStr != null) {
9139 if (installStatusStr.equalsIgnoreCase("false")) {
9140 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9141 } else {
9142 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9143 }
9144 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146 int outerDepth = parser.getDepth();
9147 int type;
9148 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9149 && (type != XmlPullParser.END_TAG
9150 || parser.getDepth() > outerDepth)) {
9151 if (type == XmlPullParser.END_TAG
9152 || type == XmlPullParser.TEXT) {
9153 continue;
9154 }
9155
9156 String tagName = parser.getName();
9157 if (tagName.equals("disabled-components")) {
9158 readDisabledComponentsLP(packageSetting, parser);
9159 } else if (tagName.equals("enabled-components")) {
9160 readEnabledComponentsLP(packageSetting, parser);
9161 } else if (tagName.equals("sigs")) {
9162 packageSetting.signatures.readXml(parser, mPastSignatures);
9163 } else if (tagName.equals("perms")) {
9164 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009165 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009166 packageSetting.permissionsFixed = true;
9167 } else {
9168 reportSettingsProblem(Log.WARN,
9169 "Unknown element under <package>: "
9170 + parser.getName());
9171 XmlUtils.skipCurrentTag(parser);
9172 }
9173 }
9174 } else {
9175 XmlUtils.skipCurrentTag(parser);
9176 }
9177 }
9178
9179 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9180 XmlPullParser parser)
9181 throws IOException, XmlPullParserException {
9182 int outerDepth = parser.getDepth();
9183 int type;
9184 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9185 && (type != XmlPullParser.END_TAG
9186 || parser.getDepth() > outerDepth)) {
9187 if (type == XmlPullParser.END_TAG
9188 || type == XmlPullParser.TEXT) {
9189 continue;
9190 }
9191
9192 String tagName = parser.getName();
9193 if (tagName.equals("item")) {
9194 String name = parser.getAttributeValue(null, "name");
9195 if (name != null) {
9196 packageSetting.disabledComponents.add(name.intern());
9197 } else {
9198 reportSettingsProblem(Log.WARN,
9199 "Error in package manager settings: <disabled-components> has"
9200 + " no name at " + parser.getPositionDescription());
9201 }
9202 } else {
9203 reportSettingsProblem(Log.WARN,
9204 "Unknown element under <disabled-components>: "
9205 + parser.getName());
9206 }
9207 XmlUtils.skipCurrentTag(parser);
9208 }
9209 }
9210
9211 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9212 XmlPullParser parser)
9213 throws IOException, XmlPullParserException {
9214 int outerDepth = parser.getDepth();
9215 int type;
9216 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9217 && (type != XmlPullParser.END_TAG
9218 || parser.getDepth() > outerDepth)) {
9219 if (type == XmlPullParser.END_TAG
9220 || type == XmlPullParser.TEXT) {
9221 continue;
9222 }
9223
9224 String tagName = parser.getName();
9225 if (tagName.equals("item")) {
9226 String name = parser.getAttributeValue(null, "name");
9227 if (name != null) {
9228 packageSetting.enabledComponents.add(name.intern());
9229 } else {
9230 reportSettingsProblem(Log.WARN,
9231 "Error in package manager settings: <enabled-components> has"
9232 + " no name at " + parser.getPositionDescription());
9233 }
9234 } else {
9235 reportSettingsProblem(Log.WARN,
9236 "Unknown element under <enabled-components>: "
9237 + parser.getName());
9238 }
9239 XmlUtils.skipCurrentTag(parser);
9240 }
9241 }
9242
9243 private void readSharedUserLP(XmlPullParser parser)
9244 throws XmlPullParserException, IOException {
9245 String name = null;
9246 String idStr = null;
9247 int pkgFlags = 0;
9248 SharedUserSetting su = null;
9249 try {
9250 name = parser.getAttributeValue(null, "name");
9251 idStr = parser.getAttributeValue(null, "userId");
9252 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9253 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9254 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9255 }
9256 if (name == null) {
9257 reportSettingsProblem(Log.WARN,
9258 "Error in package manager settings: <shared-user> has no name at "
9259 + parser.getPositionDescription());
9260 } else if (userId == 0) {
9261 reportSettingsProblem(Log.WARN,
9262 "Error in package manager settings: shared-user "
9263 + name + " has bad userId " + idStr + " at "
9264 + parser.getPositionDescription());
9265 } else {
9266 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9267 reportSettingsProblem(Log.ERROR,
9268 "Occurred while parsing settings at "
9269 + parser.getPositionDescription());
9270 }
9271 }
9272 } catch (NumberFormatException e) {
9273 reportSettingsProblem(Log.WARN,
9274 "Error in package manager settings: package "
9275 + name + " has bad userId " + idStr + " at "
9276 + parser.getPositionDescription());
9277 };
9278
9279 if (su != null) {
9280 int outerDepth = parser.getDepth();
9281 int type;
9282 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9283 && (type != XmlPullParser.END_TAG
9284 || parser.getDepth() > outerDepth)) {
9285 if (type == XmlPullParser.END_TAG
9286 || type == XmlPullParser.TEXT) {
9287 continue;
9288 }
9289
9290 String tagName = parser.getName();
9291 if (tagName.equals("sigs")) {
9292 su.signatures.readXml(parser, mPastSignatures);
9293 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009294 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009295 } else {
9296 reportSettingsProblem(Log.WARN,
9297 "Unknown element under <shared-user>: "
9298 + parser.getName());
9299 XmlUtils.skipCurrentTag(parser);
9300 }
9301 }
9302
9303 } else {
9304 XmlUtils.skipCurrentTag(parser);
9305 }
9306 }
9307
9308 private void readGrantedPermissionsLP(XmlPullParser parser,
9309 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9310 int outerDepth = parser.getDepth();
9311 int type;
9312 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9313 && (type != XmlPullParser.END_TAG
9314 || parser.getDepth() > outerDepth)) {
9315 if (type == XmlPullParser.END_TAG
9316 || type == XmlPullParser.TEXT) {
9317 continue;
9318 }
9319
9320 String tagName = parser.getName();
9321 if (tagName.equals("item")) {
9322 String name = parser.getAttributeValue(null, "name");
9323 if (name != null) {
9324 outPerms.add(name.intern());
9325 } else {
9326 reportSettingsProblem(Log.WARN,
9327 "Error in package manager settings: <perms> has"
9328 + " no name at " + parser.getPositionDescription());
9329 }
9330 } else {
9331 reportSettingsProblem(Log.WARN,
9332 "Unknown element under <perms>: "
9333 + parser.getName());
9334 }
9335 XmlUtils.skipCurrentTag(parser);
9336 }
9337 }
9338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009339 private void readPreferredActivitiesLP(XmlPullParser parser)
9340 throws XmlPullParserException, IOException {
9341 int outerDepth = parser.getDepth();
9342 int type;
9343 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9344 && (type != XmlPullParser.END_TAG
9345 || parser.getDepth() > outerDepth)) {
9346 if (type == XmlPullParser.END_TAG
9347 || type == XmlPullParser.TEXT) {
9348 continue;
9349 }
9350
9351 String tagName = parser.getName();
9352 if (tagName.equals("item")) {
9353 PreferredActivity pa = new PreferredActivity(parser);
9354 if (pa.mParseError == null) {
9355 mPreferredActivities.addFilter(pa);
9356 } else {
9357 reportSettingsProblem(Log.WARN,
9358 "Error in package manager settings: <preferred-activity> "
9359 + pa.mParseError + " at "
9360 + parser.getPositionDescription());
9361 }
9362 } else {
9363 reportSettingsProblem(Log.WARN,
9364 "Unknown element under <preferred-activities>: "
9365 + parser.getName());
9366 XmlUtils.skipCurrentTag(parser);
9367 }
9368 }
9369 }
9370
9371 // Returns -1 if we could not find an available UserId to assign
9372 private int newUserIdLP(Object obj) {
9373 // Let's be stupidly inefficient for now...
9374 final int N = mUserIds.size();
9375 for (int i=0; i<N; i++) {
9376 if (mUserIds.get(i) == null) {
9377 mUserIds.set(i, obj);
9378 return FIRST_APPLICATION_UID + i;
9379 }
9380 }
9381
9382 // None left?
9383 if (N >= MAX_APPLICATION_UIDS) {
9384 return -1;
9385 }
9386
9387 mUserIds.add(obj);
9388 return FIRST_APPLICATION_UID + N;
9389 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 public PackageSetting getDisabledSystemPkg(String name) {
9392 synchronized(mPackages) {
9393 PackageSetting ps = mDisabledSysPackages.get(name);
9394 return ps;
9395 }
9396 }
9397
9398 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009399 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9400 return true;
9401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009402 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9403 if (Config.LOGV) {
9404 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9405 + " componentName = " + componentInfo.name);
9406 Log.v(TAG, "enabledComponents: "
9407 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9408 Log.v(TAG, "disabledComponents: "
9409 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9410 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009411 if (packageSettings == null) {
9412 if (false) {
9413 Log.w(TAG, "WAITING FOR DEBUGGER");
9414 Debug.waitForDebugger();
9415 Log.i(TAG, "We will crash!");
9416 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009417 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009418 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009419 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9420 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9421 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9422 return false;
9423 }
9424 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9425 return true;
9426 }
9427 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9428 return false;
9429 }
9430 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009431 }
9432 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009433
9434 // ------- apps on sdcard specific code -------
9435 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009436 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9437 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9438 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009439 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009440
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009441 private String getEncryptKey() {
9442 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009443 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9444 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009445 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009446 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9447 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009448 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009449 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009450 return null;
9451 }
9452 }
9453 return sdEncKey;
9454 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009455 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009456 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009457 } catch (IOException ioe) {
9458 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9459 + ioe);
9460 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009461 }
Rich Cannings8d578832010-09-09 15:12:40 -07009462
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009463 }
9464
Kenny Rootc78a8072010-07-27 15:18:38 -07009465 /* package */ static String getTempContainerId() {
9466 int tmpIdx = 1;
9467 String list[] = PackageHelper.getSecureContainerList();
9468 if (list != null) {
9469 for (final String name : list) {
9470 // Ignore null and non-temporary container entries
9471 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9472 continue;
9473 }
9474
9475 String subStr = name.substring(mTempContainerPrefix.length());
9476 try {
9477 int cid = Integer.parseInt(subStr);
9478 if (cid >= tmpIdx) {
9479 tmpIdx = cid + 1;
9480 }
9481 } catch (NumberFormatException e) {
9482 }
9483 }
9484 }
9485 return mTempContainerPrefix + tmpIdx;
9486 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009487
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009488 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009489 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009490 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009491 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9492 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9493 throw new SecurityException("Media status can only be updated by the system");
9494 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009495 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009496 Log.i(TAG, "Updating external media status from " +
9497 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9498 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009499 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9500 mediaStatus+", mMediaMounted=" + mMediaMounted);
9501 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009502 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9503 reportStatus ? 1 : 0, -1);
9504 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009505 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009506 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009507 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009508 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009509 // Queue up an async operation since the package installation may take a little while.
9510 mHandler.post(new Runnable() {
9511 public void run() {
9512 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009513 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009514 }
9515 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009516 }
9517
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009518 /*
9519 * Collect information of applications on external media, map them
9520 * against existing containers and update information based on current
9521 * mount status. Please note that we always have to report status
9522 * if reportStatus has been set to true especially when unloading packages.
9523 */
9524 private void updateExternalMediaStatusInner(boolean mediaStatus,
9525 boolean reportStatus) {
9526 // Collection of uids
9527 int uidArr[] = null;
9528 // Collection of stale containers
9529 HashSet<String> removeCids = new HashSet<String>();
9530 // Collection of packages on external media with valid containers.
9531 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9532 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009533 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009534 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009535 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009536 } else {
9537 // Process list of secure containers and categorize them
9538 // as active or stale based on their package internal state.
9539 int uidList[] = new int[list.length];
9540 int num = 0;
9541 synchronized (mPackages) {
9542 for (String cid : list) {
9543 SdInstallArgs args = new SdInstallArgs(cid);
9544 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009545 String pkgName = args.getPackageName();
9546 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009547 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9548 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009549 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009550 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009551 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9552 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009553 // The package status is changed only if the code path
9554 // matches between settings and the container id.
9555 if (ps != null && ps.codePathString != null &&
9556 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009557 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9558 " corresponds to pkg : " + pkgName +
9559 " at code path: " + ps.codePathString);
9560 // We do have a valid package installed on sdcard
9561 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009562 int uid = ps.userId;
9563 if (uid != -1) {
9564 uidList[num++] = uid;
9565 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009566 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009567 // Stale container on sdcard. Just delete
9568 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9569 removeCids.add(cid);
9570 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009571 }
9572 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009573
9574 if (num > 0) {
9575 // Sort uid list
9576 Arrays.sort(uidList, 0, num);
9577 // Throw away duplicates
9578 uidArr = new int[num];
9579 uidArr[0] = uidList[0];
9580 int di = 0;
9581 for (int i = 1; i < num; i++) {
9582 if (uidList[i-1] != uidList[i]) {
9583 uidArr[di++] = uidList[i];
9584 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009585 }
9586 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009587 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009588 // Process packages with valid entries.
9589 if (mediaStatus) {
9590 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009591 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009592 startCleaningPackages();
9593 } else {
9594 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009595 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009596 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009597 }
9598
9599 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009600 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009601 int size = pkgList.size();
9602 if (size > 0) {
9603 // Send broadcasts here
9604 Bundle extras = new Bundle();
9605 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9606 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009607 if (uidArr != null) {
9608 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9609 }
9610 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9611 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009612 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009613 }
9614 }
9615
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009616 /*
9617 * Look at potentially valid container ids from processCids
9618 * If package information doesn't match the one on record
9619 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009620 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009621 */
9622 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009623 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009624 ArrayList<String> pkgList = new ArrayList<String>();
9625 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009626 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009627 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009628 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009629 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9630 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009631 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009632 try {
9633 // Make sure there are no container errors first.
9634 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9635 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009636 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009637 " when installing from sdcard");
9638 continue;
9639 }
9640 // Check code path here.
9641 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009642 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009643 " does not match one in settings " + codePath);
9644 continue;
9645 }
9646 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009647 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009648 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009649 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009650 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9651 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009652 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009653 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009654 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009655 retCode = PackageManager.INSTALL_SUCCEEDED;
9656 pkgList.add(pkg.packageName);
9657 // Post process args
9658 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9659 }
9660 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009661 Slog.i(TAG, "Failed to install pkg from " +
9662 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009663 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009664 }
9665
9666 } finally {
9667 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9668 // Don't destroy container here. Wait till gc clears things up.
9669 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009670 }
9671 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009672 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009673 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009674 // If the platform SDK has changed since the last time we booted,
9675 // we need to re-grant app permission to catch any new ones that
9676 // appear. This is really a hack, and means that apps can in some
9677 // cases get permissions that the user didn't initially explicitly
9678 // allow... it would be nice to have some better way to handle
9679 // this situation.
9680 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9681 != mSdkVersion;
9682 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9683 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9684 + "; regranting permissions for external storage");
9685 mSettings.mExternalSdkPlatform = mSdkVersion;
9686
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009687 // Make sure group IDs have been assigned, and any permission
9688 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009689 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009690 // Persist settings
9691 mSettings.writeLP();
9692 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009693 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009694 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009695 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009696 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009697 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009698 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009699 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009700 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009701 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009702 if (removeCids != null) {
9703 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009704 if (cid.startsWith(mTempContainerPrefix)) {
9705 Log.i(TAG, "Destroying stale temporary container " + cid);
9706 PackageHelper.destroySdDir(cid);
9707 } else {
9708 Log.w(TAG, "Container " + cid + " is stale");
9709 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009710 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009711 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009712 }
9713
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009714 /*
9715 * Utility method to unload a list of specified containers
9716 */
9717 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9718 // Just unmount all valid containers.
9719 for (SdInstallArgs arg : cidArgs) {
9720 synchronized (mInstallLock) {
9721 arg.doPostDeleteLI(false);
9722 }
9723 }
9724 }
9725
9726 /*
9727 * Unload packages mounted on external media. This involves deleting
9728 * package data from internal structures, sending broadcasts about
9729 * diabled packages, gc'ing to free up references, unmounting all
9730 * secure containers corresponding to packages on external media, and
9731 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9732 * Please note that we always have to post this message if status has
9733 * been requested no matter what.
9734 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009735 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009736 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009737 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009738 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009739 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009740 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009741 for (SdInstallArgs args : keys) {
9742 String cid = args.cid;
9743 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009744 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009745 // Delete package internally
9746 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9747 synchronized (mInstallLock) {
9748 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009749 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009750 if (res) {
9751 pkgList.add(pkgName);
9752 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009753 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009754 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009755 }
9756 }
9757 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009758
9759 synchronized (mPackages) {
9760 // We didn't update the settings after removing each package;
9761 // write them now for all packages.
9762 mSettings.writeLP();
9763 }
9764
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009765 // We have to absolutely send UPDATED_MEDIA_STATUS only
9766 // after confirming that all the receivers processed the ordered
9767 // broadcast when packages get disabled, force a gc to clean things up.
9768 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009769 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009770 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9771 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9772 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009773 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9774 reportStatus ? 1 : 0, 1, keys);
9775 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009776 }
9777 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009778 } else {
9779 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9780 reportStatus ? 1 : 0, -1, keys);
9781 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009782 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009783 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009784
9785 public void movePackage(final String packageName,
9786 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009787 mContext.enforceCallingOrSelfPermission(
9788 android.Manifest.permission.MOVE_PACKAGE, null);
9789 int returnCode = PackageManager.MOVE_SUCCEEDED;
9790 int currFlags = 0;
9791 int newFlags = 0;
9792 synchronized (mPackages) {
9793 PackageParser.Package pkg = mPackages.get(packageName);
9794 if (pkg == null) {
9795 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009796 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009797 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009798 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009799 Slog.w(TAG, "Cannot move system application");
9800 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009801 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009802 Slog.w(TAG, "Cannot move forward locked app.");
9803 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009804 } else if (pkg.mOperationPending) {
9805 Slog.w(TAG, "Attempt to move package which has pending operations");
9806 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009807 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009808 // Find install location first
9809 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9810 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9811 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009812 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009813 } else {
9814 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9815 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009816 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9817 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009818 if (newFlags == currFlags) {
9819 Slog.w(TAG, "No move required. Trying to move to same location");
9820 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9821 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009822 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009823 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9824 pkg.mOperationPending = true;
9825 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009826 }
9827 }
9828 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009829 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009830 } else {
9831 Message msg = mHandler.obtainMessage(INIT_COPY);
9832 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009833 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9834 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9835 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009836 msg.obj = mp;
9837 mHandler.sendMessage(msg);
9838 }
9839 }
9840 }
9841
9842 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9843 // Queue up an async operation since the package deletion may take a little while.
9844 mHandler.post(new Runnable() {
9845 public void run() {
9846 mHandler.removeCallbacks(this);
9847 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009848 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9849 int uidArr[] = null;
9850 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009851 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009852 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009853 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009854 Slog.w(TAG, " Package " + mp.packageName +
9855 " doesn't exist. Aborting move");
9856 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9857 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9858 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9859 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9860 " Aborting move and returning error");
9861 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9862 } else {
9863 uidArr = new int[] { pkg.applicationInfo.uid };
9864 pkgList = new ArrayList<String>();
9865 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009866 }
9867 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009868 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9869 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009870 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009871 // Update package code and resource paths
9872 synchronized (mInstallLock) {
9873 synchronized (mPackages) {
9874 PackageParser.Package pkg = mPackages.get(mp.packageName);
9875 // Recheck for package again.
9876 if (pkg == null ) {
9877 Slog.w(TAG, " Package " + mp.packageName +
9878 " doesn't exist. Aborting move");
9879 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9880 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9881 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9882 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9883 " Aborting move and returning error");
9884 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9885 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009886 final String oldCodePath = pkg.mPath;
9887 final String newCodePath = mp.targetArgs.getCodePath();
9888 final String newResPath = mp.targetArgs.getResourcePath();
9889 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009890 pkg.mPath = newCodePath;
9891 // Move dex files around
9892 if (moveDexFilesLI(pkg)
9893 != PackageManager.INSTALL_SUCCEEDED) {
9894 // Moving of dex files failed. Set
9895 // error code and abort move.
9896 pkg.mPath = pkg.mScanPath;
9897 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9898 } else {
9899 pkg.mScanPath = newCodePath;
9900 pkg.applicationInfo.sourceDir = newCodePath;
9901 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009902 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009903 PackageSetting ps = (PackageSetting) pkg.mExtras;
9904 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9905 ps.codePathString = ps.codePath.getPath();
9906 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9907 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009908 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009909 // Set the application info flag correctly.
9910 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9911 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9912 } else {
9913 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9914 }
9915 ps.setFlags(pkg.applicationInfo.flags);
9916 mAppDirs.remove(oldCodePath);
9917 mAppDirs.put(newCodePath, pkg);
9918 // Persist settings
9919 mSettings.writeLP();
9920 }
9921 }
9922 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009923 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009924 // Send resources available broadcast
9925 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009926 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009927 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009928 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009929 // Clean up failed installation
9930 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009931 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009932 }
9933 } else {
9934 // Force a gc to clear things up.
9935 Runtime.getRuntime().gc();
9936 // Delete older code
9937 synchronized (mInstallLock) {
9938 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009939 }
9940 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009941
9942 // Allow more operations on this file if we didn't fail because
9943 // an operation was already pending for this package.
9944 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9945 synchronized (mPackages) {
9946 PackageParser.Package pkg = mPackages.get(mp.packageName);
9947 if (pkg != null) {
9948 pkg.mOperationPending = false;
9949 }
9950 }
9951 }
9952
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009953 IPackageMoveObserver observer = mp.observer;
9954 if (observer != null) {
9955 try {
9956 observer.packageMoved(mp.packageName, returnCode);
9957 } catch (RemoteException e) {
9958 Log.i(TAG, "Observer no longer exists.");
9959 }
9960 }
9961 }
9962 });
9963 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009964
9965 public boolean setInstallLocation(int loc) {
9966 mContext.enforceCallingOrSelfPermission(
9967 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9968 if (getInstallLocation() == loc) {
9969 return true;
9970 }
9971 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9972 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9973 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9974 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9975 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9976 return true;
9977 }
9978 return false;
9979 }
9980
9981 public int getInstallLocation() {
9982 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9983 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009985}