blob: 72daa6438155a05154616d84af186e3dda22f7dc [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);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001105
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001106 StringBuilder sb = new StringBuilder(128);
1107 sb.append("Libs:");
1108 Iterator<String> it = mSharedLibraries.keySet().iterator();
1109 while (it.hasNext()) {
1110 sb.append(' ');
1111 String name = it.next();
1112 sb.append(name);
1113 sb.append(':');
1114 sb.append(mSharedLibraries.get(name));
1115 }
1116 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001117
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001118 sb.setLength(0);
1119 sb.append("Features:");
1120 it = mAvailableFeatures.keySet().iterator();
1121 while (it.hasNext()) {
1122 sb.append(' ');
1123 sb.append(it.next());
1124 }
1125 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001127
1128 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 FileReader permReader = null;
1130 try {
1131 permReader = new FileReader(permFile);
1132 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001133 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 return;
1135 }
1136
1137 try {
1138 XmlPullParser parser = Xml.newPullParser();
1139 parser.setInput(permReader);
1140
1141 XmlUtils.beginDocument(parser, "permissions");
1142
1143 while (true) {
1144 XmlUtils.nextElement(parser);
1145 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1146 break;
1147 }
1148
1149 String name = parser.getName();
1150 if ("group".equals(name)) {
1151 String gidStr = parser.getAttributeValue(null, "gid");
1152 if (gidStr != null) {
1153 int gid = Integer.parseInt(gidStr);
1154 mGlobalGids = appendInt(mGlobalGids, gid);
1155 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001156 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 + parser.getPositionDescription());
1158 }
1159
1160 XmlUtils.skipCurrentTag(parser);
1161 continue;
1162 } else if ("permission".equals(name)) {
1163 String perm = parser.getAttributeValue(null, "name");
1164 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001165 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 + parser.getPositionDescription());
1167 XmlUtils.skipCurrentTag(parser);
1168 continue;
1169 }
1170 perm = perm.intern();
1171 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001172
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 } else if ("assign-permission".equals(name)) {
1174 String perm = parser.getAttributeValue(null, "name");
1175 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001176 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 + parser.getPositionDescription());
1178 XmlUtils.skipCurrentTag(parser);
1179 continue;
1180 }
1181 String uidStr = parser.getAttributeValue(null, "uid");
1182 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001183 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 + parser.getPositionDescription());
1185 XmlUtils.skipCurrentTag(parser);
1186 continue;
1187 }
1188 int uid = Process.getUidForName(uidStr);
1189 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001190 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 + uidStr + "\" at "
1192 + parser.getPositionDescription());
1193 XmlUtils.skipCurrentTag(parser);
1194 continue;
1195 }
1196 perm = perm.intern();
1197 HashSet<String> perms = mSystemPermissions.get(uid);
1198 if (perms == null) {
1199 perms = new HashSet<String>();
1200 mSystemPermissions.put(uid, perms);
1201 }
1202 perms.add(perm);
1203 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 } else if ("library".equals(name)) {
1206 String lname = parser.getAttributeValue(null, "name");
1207 String lfile = parser.getAttributeValue(null, "file");
1208 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001209 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 + parser.getPositionDescription());
1211 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001212 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 + parser.getPositionDescription());
1214 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001215 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001216 mSharedLibraries.put(lname, lfile);
1217 }
1218 XmlUtils.skipCurrentTag(parser);
1219 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001220
Dianne Hackborn49237342009-08-27 20:08:01 -07001221 } else if ("feature".equals(name)) {
1222 String fname = parser.getAttributeValue(null, "name");
1223 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001224 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001225 + parser.getPositionDescription());
1226 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001227 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001228 FeatureInfo fi = new FeatureInfo();
1229 fi.name = fname;
1230 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
1232 XmlUtils.skipCurrentTag(parser);
1233 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 } else {
1236 XmlUtils.skipCurrentTag(parser);
1237 continue;
1238 }
1239
1240 }
1241 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001242 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001244 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 }
1246 }
1247
1248 void readPermission(XmlPullParser parser, String name)
1249 throws IOException, XmlPullParserException {
1250
1251 name = name.intern();
1252
1253 BasePermission bp = mSettings.mPermissions.get(name);
1254 if (bp == null) {
1255 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1256 mSettings.mPermissions.put(name, bp);
1257 }
1258 int outerDepth = parser.getDepth();
1259 int type;
1260 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1261 && (type != XmlPullParser.END_TAG
1262 || parser.getDepth() > outerDepth)) {
1263 if (type == XmlPullParser.END_TAG
1264 || type == XmlPullParser.TEXT) {
1265 continue;
1266 }
1267
1268 String tagName = parser.getName();
1269 if ("group".equals(tagName)) {
1270 String gidStr = parser.getAttributeValue(null, "gid");
1271 if (gidStr != null) {
1272 int gid = Process.getGidForName(gidStr);
1273 bp.gids = appendInt(bp.gids, gid);
1274 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001275 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 + parser.getPositionDescription());
1277 }
1278 }
1279 XmlUtils.skipCurrentTag(parser);
1280 }
1281 }
1282
1283 static int[] appendInt(int[] cur, int val) {
1284 if (cur == null) {
1285 return new int[] { val };
1286 }
1287 final int N = cur.length;
1288 for (int i=0; i<N; i++) {
1289 if (cur[i] == val) {
1290 return cur;
1291 }
1292 }
1293 int[] ret = new int[N+1];
1294 System.arraycopy(cur, 0, ret, 0, N);
1295 ret[N] = val;
1296 return ret;
1297 }
1298
1299 static int[] appendInts(int[] cur, int[] add) {
1300 if (add == null) return cur;
1301 if (cur == null) return add;
1302 final int N = add.length;
1303 for (int i=0; i<N; i++) {
1304 cur = appendInt(cur, add[i]);
1305 }
1306 return cur;
1307 }
1308
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001309 static int[] removeInt(int[] cur, int val) {
1310 if (cur == null) {
1311 return null;
1312 }
1313 final int N = cur.length;
1314 for (int i=0; i<N; i++) {
1315 if (cur[i] == val) {
1316 int[] ret = new int[N-1];
1317 if (i > 0) {
1318 System.arraycopy(cur, 0, ret, 0, i);
1319 }
1320 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001321 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001322 }
1323 return ret;
1324 }
1325 }
1326 return cur;
1327 }
1328
1329 static int[] removeInts(int[] cur, int[] rem) {
1330 if (rem == null) return cur;
1331 if (cur == null) return cur;
1332 final int N = rem.length;
1333 for (int i=0; i<N; i++) {
1334 cur = removeInt(cur, rem[i]);
1335 }
1336 return cur;
1337 }
1338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001340 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1341 // The package has been uninstalled but has retained data and resources.
1342 return PackageParser.generatePackageInfo(p, null, flags);
1343 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 final PackageSetting ps = (PackageSetting)p.mExtras;
1345 if (ps == null) {
1346 return null;
1347 }
1348 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1349 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1350 }
1351
1352 public PackageInfo getPackageInfo(String packageName, int flags) {
1353 synchronized (mPackages) {
1354 PackageParser.Package p = mPackages.get(packageName);
1355 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001356 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 + ": " + p);
1358 if (p != null) {
1359 return generatePackageInfo(p, flags);
1360 }
1361 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1362 return generatePackageInfoFromSettingsLP(packageName, flags);
1363 }
1364 }
1365 return null;
1366 }
1367
Dianne Hackborn47096932010-02-11 15:57:09 -08001368 public String[] currentToCanonicalPackageNames(String[] names) {
1369 String[] out = new String[names.length];
1370 synchronized (mPackages) {
1371 for (int i=names.length-1; i>=0; i--) {
1372 PackageSetting ps = mSettings.mPackages.get(names[i]);
1373 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1374 }
1375 }
1376 return out;
1377 }
1378
1379 public String[] canonicalToCurrentPackageNames(String[] names) {
1380 String[] out = new String[names.length];
1381 synchronized (mPackages) {
1382 for (int i=names.length-1; i>=0; i--) {
1383 String cur = mSettings.mRenamedPackages.get(names[i]);
1384 out[i] = cur != null ? cur : names[i];
1385 }
1386 }
1387 return out;
1388 }
1389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 public int getPackageUid(String packageName) {
1391 synchronized (mPackages) {
1392 PackageParser.Package p = mPackages.get(packageName);
1393 if(p != null) {
1394 return p.applicationInfo.uid;
1395 }
1396 PackageSetting ps = mSettings.mPackages.get(packageName);
1397 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1398 return -1;
1399 }
1400 p = ps.pkg;
1401 return p != null ? p.applicationInfo.uid : -1;
1402 }
1403 }
1404
1405 public int[] getPackageGids(String packageName) {
1406 synchronized (mPackages) {
1407 PackageParser.Package p = mPackages.get(packageName);
1408 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001409 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 + ": " + p);
1411 if (p != null) {
1412 final PackageSetting ps = (PackageSetting)p.mExtras;
1413 final SharedUserSetting suid = ps.sharedUser;
1414 return suid != null ? suid.gids : ps.gids;
1415 }
1416 }
1417 // stupid thing to indicate an error.
1418 return new int[0];
1419 }
1420
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001421 static final PermissionInfo generatePermissionInfo(
1422 BasePermission bp, int flags) {
1423 if (bp.perm != null) {
1424 return PackageParser.generatePermissionInfo(bp.perm, flags);
1425 }
1426 PermissionInfo pi = new PermissionInfo();
1427 pi.name = bp.name;
1428 pi.packageName = bp.sourcePackage;
1429 pi.nonLocalizedLabel = bp.name;
1430 pi.protectionLevel = bp.protectionLevel;
1431 return pi;
1432 }
1433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 public PermissionInfo getPermissionInfo(String name, int flags) {
1435 synchronized (mPackages) {
1436 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001437 if (p != null) {
1438 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440 return null;
1441 }
1442 }
1443
1444 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1445 synchronized (mPackages) {
1446 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1447 for (BasePermission p : mSettings.mPermissions.values()) {
1448 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001449 if (p.perm == null || p.perm.info.group == null) {
1450 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 }
1452 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001453 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1455 }
1456 }
1457 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 if (out.size() > 0) {
1460 return out;
1461 }
1462 return mPermissionGroups.containsKey(group) ? out : null;
1463 }
1464 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1467 synchronized (mPackages) {
1468 return PackageParser.generatePermissionGroupInfo(
1469 mPermissionGroups.get(name), flags);
1470 }
1471 }
1472
1473 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1474 synchronized (mPackages) {
1475 final int N = mPermissionGroups.size();
1476 ArrayList<PermissionGroupInfo> out
1477 = new ArrayList<PermissionGroupInfo>(N);
1478 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1479 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1480 }
1481 return out;
1482 }
1483 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001485 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1486 PackageSetting ps = mSettings.mPackages.get(packageName);
1487 if(ps != null) {
1488 if(ps.pkg == null) {
1489 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1490 if(pInfo != null) {
1491 return pInfo.applicationInfo;
1492 }
1493 return null;
1494 }
1495 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1496 }
1497 return null;
1498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001500 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1501 PackageSetting ps = mSettings.mPackages.get(packageName);
1502 if(ps != null) {
1503 if(ps.pkg == null) {
1504 ps.pkg = new PackageParser.Package(packageName);
1505 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001506 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1507 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1508 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1509 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001510 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001511 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513 return generatePackageInfo(ps.pkg, flags);
1514 }
1515 return null;
1516 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1519 synchronized (mPackages) {
1520 PackageParser.Package p = mPackages.get(packageName);
1521 if (Config.LOGV) Log.v(
1522 TAG, "getApplicationInfo " + packageName
1523 + ": " + p);
1524 if (p != null) {
1525 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001526 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528 if ("android".equals(packageName)||"system".equals(packageName)) {
1529 return mAndroidApplication;
1530 }
1531 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1532 return generateApplicationInfoFromSettingsLP(packageName, flags);
1533 }
1534 }
1535 return null;
1536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001537
1538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1540 mContext.enforceCallingOrSelfPermission(
1541 android.Manifest.permission.CLEAR_APP_CACHE, null);
1542 // Queue up an async operation since clearing cache may take a little while.
1543 mHandler.post(new Runnable() {
1544 public void run() {
1545 mHandler.removeCallbacks(this);
1546 int retCode = -1;
1547 if (mInstaller != null) {
1548 retCode = mInstaller.freeCache(freeStorageSize);
1549 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001550 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 }
1552 } //end if mInstaller
1553 if (observer != null) {
1554 try {
1555 observer.onRemoveCompleted(null, (retCode >= 0));
1556 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001557 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 }
1559 }
1560 }
1561 });
1562 }
1563
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001564 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001565 mContext.enforceCallingOrSelfPermission(
1566 android.Manifest.permission.CLEAR_APP_CACHE, null);
1567 // Queue up an async operation since clearing cache may take a little while.
1568 mHandler.post(new Runnable() {
1569 public void run() {
1570 mHandler.removeCallbacks(this);
1571 int retCode = -1;
1572 if (mInstaller != null) {
1573 retCode = mInstaller.freeCache(freeStorageSize);
1574 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001575 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001576 }
1577 }
1578 if(pi != null) {
1579 try {
1580 // Callback via pending intent
1581 int code = (retCode >= 0) ? 1 : 0;
1582 pi.sendIntent(null, code, null,
1583 null, null);
1584 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001585 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001586 }
1587 }
1588 }
1589 });
1590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1593 synchronized (mPackages) {
1594 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001595
1596 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001598 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
1600 if (mResolveComponentName.equals(component)) {
1601 return mResolveActivity;
1602 }
1603 }
1604 return null;
1605 }
1606
1607 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1608 synchronized (mPackages) {
1609 PackageParser.Activity a = mReceivers.mActivities.get(component);
1610 if (Config.LOGV) Log.v(
1611 TAG, "getReceiverInfo " + component + ": " + a);
1612 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1613 return PackageParser.generateActivityInfo(a, flags);
1614 }
1615 }
1616 return null;
1617 }
1618
1619 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1620 synchronized (mPackages) {
1621 PackageParser.Service s = mServices.mServices.get(component);
1622 if (Config.LOGV) Log.v(
1623 TAG, "getServiceInfo " + component + ": " + s);
1624 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1625 return PackageParser.generateServiceInfo(s, flags);
1626 }
1627 }
1628 return null;
1629 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001630
Dianne Hackborn361199b2010-08-30 17:42:07 -07001631 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1632 synchronized (mPackages) {
1633 PackageParser.Provider p = mProvidersByComponent.get(component);
1634 if (Config.LOGV) Log.v(
1635 TAG, "getProviderInfo " + component + ": " + p);
1636 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1637 return PackageParser.generateProviderInfo(p, flags);
1638 }
1639 }
1640 return null;
1641 }
1642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001643 public String[] getSystemSharedLibraryNames() {
1644 Set<String> libSet;
1645 synchronized (mPackages) {
1646 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001647 int size = libSet.size();
1648 if (size > 0) {
1649 String[] libs = new String[size];
1650 libSet.toArray(libs);
1651 return libs;
1652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001654 return null;
1655 }
1656
1657 public FeatureInfo[] getSystemAvailableFeatures() {
1658 Collection<FeatureInfo> featSet;
1659 synchronized (mPackages) {
1660 featSet = mAvailableFeatures.values();
1661 int size = featSet.size();
1662 if (size > 0) {
1663 FeatureInfo[] features = new FeatureInfo[size+1];
1664 featSet.toArray(features);
1665 FeatureInfo fi = new FeatureInfo();
1666 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1667 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1668 features[size] = fi;
1669 return features;
1670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 }
1672 return null;
1673 }
1674
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001675 public boolean hasSystemFeature(String name) {
1676 synchronized (mPackages) {
1677 return mAvailableFeatures.containsKey(name);
1678 }
1679 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 public int checkPermission(String permName, String pkgName) {
1682 synchronized (mPackages) {
1683 PackageParser.Package p = mPackages.get(pkgName);
1684 if (p != null && p.mExtras != null) {
1685 PackageSetting ps = (PackageSetting)p.mExtras;
1686 if (ps.sharedUser != null) {
1687 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1688 return PackageManager.PERMISSION_GRANTED;
1689 }
1690 } else if (ps.grantedPermissions.contains(permName)) {
1691 return PackageManager.PERMISSION_GRANTED;
1692 }
1693 }
1694 }
1695 return PackageManager.PERMISSION_DENIED;
1696 }
1697
1698 public int checkUidPermission(String permName, int uid) {
1699 synchronized (mPackages) {
1700 Object obj = mSettings.getUserIdLP(uid);
1701 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001702 GrantedPermissions gp = (GrantedPermissions)obj;
1703 if (gp.grantedPermissions.contains(permName)) {
1704 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
1706 } else {
1707 HashSet<String> perms = mSystemPermissions.get(uid);
1708 if (perms != null && perms.contains(permName)) {
1709 return PackageManager.PERMISSION_GRANTED;
1710 }
1711 }
1712 }
1713 return PackageManager.PERMISSION_DENIED;
1714 }
1715
1716 private BasePermission findPermissionTreeLP(String permName) {
1717 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1718 if (permName.startsWith(bp.name) &&
1719 permName.length() > bp.name.length() &&
1720 permName.charAt(bp.name.length()) == '.') {
1721 return bp;
1722 }
1723 }
1724 return null;
1725 }
1726
1727 private BasePermission checkPermissionTreeLP(String permName) {
1728 if (permName != null) {
1729 BasePermission bp = findPermissionTreeLP(permName);
1730 if (bp != null) {
1731 if (bp.uid == Binder.getCallingUid()) {
1732 return bp;
1733 }
1734 throw new SecurityException("Calling uid "
1735 + Binder.getCallingUid()
1736 + " is not allowed to add to permission tree "
1737 + bp.name + " owned by uid " + bp.uid);
1738 }
1739 }
1740 throw new SecurityException("No permission tree found for " + permName);
1741 }
1742
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001743 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1744 if (s1 == null) {
1745 return s2 == null;
1746 }
1747 if (s2 == null) {
1748 return false;
1749 }
1750 if (s1.getClass() != s2.getClass()) {
1751 return false;
1752 }
1753 return s1.equals(s2);
1754 }
1755
1756 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1757 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001758 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001759 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1760 if (!compareStrings(pi1.name, pi2.name)) return false;
1761 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1762 // We'll take care of setting this one.
1763 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1764 // These are not currently stored in settings.
1765 //if (!compareStrings(pi1.group, pi2.group)) return false;
1766 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1767 //if (pi1.labelRes != pi2.labelRes) return false;
1768 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1769 return true;
1770 }
1771
1772 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1773 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1774 throw new SecurityException("Label must be specified in permission");
1775 }
1776 BasePermission tree = checkPermissionTreeLP(info.name);
1777 BasePermission bp = mSettings.mPermissions.get(info.name);
1778 boolean added = bp == null;
1779 boolean changed = true;
1780 if (added) {
1781 bp = new BasePermission(info.name, tree.sourcePackage,
1782 BasePermission.TYPE_DYNAMIC);
1783 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1784 throw new SecurityException(
1785 "Not allowed to modify non-dynamic permission "
1786 + info.name);
1787 } else {
1788 if (bp.protectionLevel == info.protectionLevel
1789 && bp.perm.owner.equals(tree.perm.owner)
1790 && bp.uid == tree.uid
1791 && comparePermissionInfos(bp.perm.info, info)) {
1792 changed = false;
1793 }
1794 }
1795 bp.protectionLevel = info.protectionLevel;
1796 bp.perm = new PackageParser.Permission(tree.perm.owner,
1797 new PermissionInfo(info));
1798 bp.perm.info.packageName = tree.perm.info.packageName;
1799 bp.uid = tree.uid;
1800 if (added) {
1801 mSettings.mPermissions.put(info.name, bp);
1802 }
1803 if (changed) {
1804 if (!async) {
1805 mSettings.writeLP();
1806 } else {
1807 scheduleWriteSettingsLocked();
1808 }
1809 }
1810 return added;
1811 }
1812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 public boolean addPermission(PermissionInfo info) {
1814 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001815 return addPermissionLocked(info, false);
1816 }
1817 }
1818
1819 public boolean addPermissionAsync(PermissionInfo info) {
1820 synchronized (mPackages) {
1821 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823 }
1824
1825 public void removePermission(String name) {
1826 synchronized (mPackages) {
1827 checkPermissionTreeLP(name);
1828 BasePermission bp = mSettings.mPermissions.get(name);
1829 if (bp != null) {
1830 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1831 throw new SecurityException(
1832 "Not allowed to modify non-dynamic permission "
1833 + name);
1834 }
1835 mSettings.mPermissions.remove(name);
1836 mSettings.writeLP();
1837 }
1838 }
1839 }
1840
Dianne Hackborn854060af2009-07-09 18:14:31 -07001841 public boolean isProtectedBroadcast(String actionName) {
1842 synchronized (mPackages) {
1843 return mProtectedBroadcasts.contains(actionName);
1844 }
1845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 public int checkSignatures(String pkg1, String pkg2) {
1848 synchronized (mPackages) {
1849 PackageParser.Package p1 = mPackages.get(pkg1);
1850 PackageParser.Package p2 = mPackages.get(pkg2);
1851 if (p1 == null || p1.mExtras == null
1852 || p2 == null || p2.mExtras == null) {
1853 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1854 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001855 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 }
1857 }
1858
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001859 public int checkUidSignatures(int uid1, int uid2) {
1860 synchronized (mPackages) {
1861 Signature[] s1;
1862 Signature[] s2;
1863 Object obj = mSettings.getUserIdLP(uid1);
1864 if (obj != null) {
1865 if (obj instanceof SharedUserSetting) {
1866 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1867 } else if (obj instanceof PackageSetting) {
1868 s1 = ((PackageSetting)obj).signatures.mSignatures;
1869 } else {
1870 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1871 }
1872 } else {
1873 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1874 }
1875 obj = mSettings.getUserIdLP(uid2);
1876 if (obj != null) {
1877 if (obj instanceof SharedUserSetting) {
1878 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1879 } else if (obj instanceof PackageSetting) {
1880 s2 = ((PackageSetting)obj).signatures.mSignatures;
1881 } else {
1882 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1883 }
1884 } else {
1885 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1886 }
1887 return checkSignaturesLP(s1, s2);
1888 }
1889 }
1890
1891 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1892 if (s1 == null) {
1893 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1895 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1896 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001897 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1899 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001900 HashSet<Signature> set1 = new HashSet<Signature>();
1901 for (Signature sig : s1) {
1902 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001903 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001904 HashSet<Signature> set2 = new HashSet<Signature>();
1905 for (Signature sig : s2) {
1906 set2.add(sig);
1907 }
1908 // Make sure s2 contains all signatures in s1.
1909 if (set1.equals(set2)) {
1910 return PackageManager.SIGNATURE_MATCH;
1911 }
1912 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001913 }
1914
1915 public String[] getPackagesForUid(int uid) {
1916 synchronized (mPackages) {
1917 Object obj = mSettings.getUserIdLP(uid);
1918 if (obj instanceof SharedUserSetting) {
1919 SharedUserSetting sus = (SharedUserSetting)obj;
1920 final int N = sus.packages.size();
1921 String[] res = new String[N];
1922 Iterator<PackageSetting> it = sus.packages.iterator();
1923 int i=0;
1924 while (it.hasNext()) {
1925 res[i++] = it.next().name;
1926 }
1927 return res;
1928 } else if (obj instanceof PackageSetting) {
1929 PackageSetting ps = (PackageSetting)obj;
1930 return new String[] { ps.name };
1931 }
1932 }
1933 return null;
1934 }
1935
1936 public String getNameForUid(int uid) {
1937 synchronized (mPackages) {
1938 Object obj = mSettings.getUserIdLP(uid);
1939 if (obj instanceof SharedUserSetting) {
1940 SharedUserSetting sus = (SharedUserSetting)obj;
1941 return sus.name + ":" + sus.userId;
1942 } else if (obj instanceof PackageSetting) {
1943 PackageSetting ps = (PackageSetting)obj;
1944 return ps.name;
1945 }
1946 }
1947 return null;
1948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 public int getUidForSharedUser(String sharedUserName) {
1951 if(sharedUserName == null) {
1952 return -1;
1953 }
1954 synchronized (mPackages) {
1955 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1956 if(suid == null) {
1957 return -1;
1958 }
1959 return suid.userId;
1960 }
1961 }
1962
1963 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1964 int flags) {
1965 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001966 return chooseBestActivity(intent, resolvedType, flags, query);
1967 }
1968
Mihai Predaeae850c2009-05-13 10:13:48 +02001969 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1970 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 if (query != null) {
1972 final int N = query.size();
1973 if (N == 1) {
1974 return query.get(0);
1975 } else if (N > 1) {
1976 // If there is more than one activity with the same priority,
1977 // then let the user decide between them.
1978 ResolveInfo r0 = query.get(0);
1979 ResolveInfo r1 = query.get(1);
1980 if (false) {
1981 System.out.println(r0.activityInfo.name +
1982 "=" + r0.priority + " vs " +
1983 r1.activityInfo.name +
1984 "=" + r1.priority);
1985 }
1986 // If the first activity has a higher priority, or a different
1987 // default, then it is always desireable to pick it.
1988 if (r0.priority != r1.priority
1989 || r0.preferredOrder != r1.preferredOrder
1990 || r0.isDefault != r1.isDefault) {
1991 return query.get(0);
1992 }
1993 // If we have saved a preference for a preferred activity for
1994 // this Intent, use that.
1995 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1996 flags, query, r0.priority);
1997 if (ri != null) {
1998 return ri;
1999 }
2000 return mResolveInfo;
2001 }
2002 }
2003 return null;
2004 }
2005
2006 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
2007 int flags, List<ResolveInfo> query, int priority) {
2008 synchronized (mPackages) {
2009 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2010 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02002011 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2013 if (prefs != null && prefs.size() > 0) {
2014 // First figure out how good the original match set is.
2015 // We will only allow preferred activities that came
2016 // from the same match quality.
2017 int match = 0;
2018 final int N = query.size();
2019 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2020 for (int j=0; j<N; j++) {
2021 ResolveInfo ri = query.get(j);
2022 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2023 + ": 0x" + Integer.toHexString(match));
2024 if (ri.match > match) match = ri.match;
2025 }
2026 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2027 + Integer.toHexString(match));
2028 match &= IntentFilter.MATCH_CATEGORY_MASK;
2029 final int M = prefs.size();
2030 for (int i=0; i<M; i++) {
2031 PreferredActivity pa = prefs.get(i);
2032 if (pa.mMatch != match) {
2033 continue;
2034 }
2035 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2036 if (DEBUG_PREFERRED) {
2037 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002038 if (ai != null) {
2039 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2040 } else {
2041 Log.v(TAG, " null");
2042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002043 }
2044 if (ai != null) {
2045 for (int j=0; j<N; j++) {
2046 ResolveInfo ri = query.get(j);
2047 if (!ri.activityInfo.applicationInfo.packageName
2048 .equals(ai.applicationInfo.packageName)) {
2049 continue;
2050 }
2051 if (!ri.activityInfo.name.equals(ai.name)) {
2052 continue;
2053 }
2054
2055 // Okay we found a previously set preferred app.
2056 // If the result set is different from when this
2057 // was created, we need to clear it and re-ask the
2058 // user their preference.
2059 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002060 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 + intent + " type " + resolvedType);
2062 mSettings.mPreferredActivities.removeFilter(pa);
2063 return null;
2064 }
2065
2066 // Yay!
2067 return ri;
2068 }
2069 }
2070 }
2071 }
2072 }
2073 return null;
2074 }
2075
2076 public List<ResolveInfo> queryIntentActivities(Intent intent,
2077 String resolvedType, int flags) {
2078 ComponentName comp = intent.getComponent();
2079 if (comp != null) {
2080 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2081 ActivityInfo ai = getActivityInfo(comp, flags);
2082 if (ai != null) {
2083 ResolveInfo ri = new ResolveInfo();
2084 ri.activityInfo = ai;
2085 list.add(ri);
2086 }
2087 return list;
2088 }
2089
2090 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002091 String pkgName = intent.getPackage();
2092 if (pkgName == null) {
2093 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2094 resolvedType, flags);
2095 }
2096 PackageParser.Package pkg = mPackages.get(pkgName);
2097 if (pkg != null) {
2098 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2099 resolvedType, flags, pkg.activities);
2100 }
2101 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 }
2103 }
2104
2105 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2106 Intent[] specifics, String[] specificTypes, Intent intent,
2107 String resolvedType, int flags) {
2108 final String resultsAction = intent.getAction();
2109
2110 List<ResolveInfo> results = queryIntentActivities(
2111 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2112 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2113
2114 int specificsPos = 0;
2115 int N;
2116
2117 // todo: note that the algorithm used here is O(N^2). This
2118 // isn't a problem in our current environment, but if we start running
2119 // into situations where we have more than 5 or 10 matches then this
2120 // should probably be changed to something smarter...
2121
2122 // First we go through and resolve each of the specific items
2123 // that were supplied, taking care of removing any corresponding
2124 // duplicate items in the generic resolve list.
2125 if (specifics != null) {
2126 for (int i=0; i<specifics.length; i++) {
2127 final Intent sintent = specifics[i];
2128 if (sintent == null) {
2129 continue;
2130 }
2131
2132 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2133 String action = sintent.getAction();
2134 if (resultsAction != null && resultsAction.equals(action)) {
2135 // If this action was explicitly requested, then don't
2136 // remove things that have it.
2137 action = null;
2138 }
2139 ComponentName comp = sintent.getComponent();
2140 ResolveInfo ri = null;
2141 ActivityInfo ai = null;
2142 if (comp == null) {
2143 ri = resolveIntent(
2144 sintent,
2145 specificTypes != null ? specificTypes[i] : null,
2146 flags);
2147 if (ri == null) {
2148 continue;
2149 }
2150 if (ri == mResolveInfo) {
2151 // ACK! Must do something better with this.
2152 }
2153 ai = ri.activityInfo;
2154 comp = new ComponentName(ai.applicationInfo.packageName,
2155 ai.name);
2156 } else {
2157 ai = getActivityInfo(comp, flags);
2158 if (ai == null) {
2159 continue;
2160 }
2161 }
2162
2163 // Look for any generic query activities that are duplicates
2164 // of this specific one, and remove them from the results.
2165 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2166 N = results.size();
2167 int j;
2168 for (j=specificsPos; j<N; j++) {
2169 ResolveInfo sri = results.get(j);
2170 if ((sri.activityInfo.name.equals(comp.getClassName())
2171 && sri.activityInfo.applicationInfo.packageName.equals(
2172 comp.getPackageName()))
2173 || (action != null && sri.filter.matchAction(action))) {
2174 results.remove(j);
2175 if (Config.LOGV) Log.v(
2176 TAG, "Removing duplicate item from " + j
2177 + " due to specific " + specificsPos);
2178 if (ri == null) {
2179 ri = sri;
2180 }
2181 j--;
2182 N--;
2183 }
2184 }
2185
2186 // Add this specific item to its proper place.
2187 if (ri == null) {
2188 ri = new ResolveInfo();
2189 ri.activityInfo = ai;
2190 }
2191 results.add(specificsPos, ri);
2192 ri.specificIndex = i;
2193 specificsPos++;
2194 }
2195 }
2196
2197 // Now we go through the remaining generic results and remove any
2198 // duplicate actions that are found here.
2199 N = results.size();
2200 for (int i=specificsPos; i<N-1; i++) {
2201 final ResolveInfo rii = results.get(i);
2202 if (rii.filter == null) {
2203 continue;
2204 }
2205
2206 // Iterate over all of the actions of this result's intent
2207 // filter... typically this should be just one.
2208 final Iterator<String> it = rii.filter.actionsIterator();
2209 if (it == null) {
2210 continue;
2211 }
2212 while (it.hasNext()) {
2213 final String action = it.next();
2214 if (resultsAction != null && resultsAction.equals(action)) {
2215 // If this action was explicitly requested, then don't
2216 // remove things that have it.
2217 continue;
2218 }
2219 for (int j=i+1; j<N; j++) {
2220 final ResolveInfo rij = results.get(j);
2221 if (rij.filter != null && rij.filter.hasAction(action)) {
2222 results.remove(j);
2223 if (Config.LOGV) Log.v(
2224 TAG, "Removing duplicate item from " + j
2225 + " due to action " + action + " at " + i);
2226 j--;
2227 N--;
2228 }
2229 }
2230 }
2231
2232 // If the caller didn't request filter information, drop it now
2233 // so we don't have to marshall/unmarshall it.
2234 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2235 rii.filter = null;
2236 }
2237 }
2238
2239 // Filter out the caller activity if so requested.
2240 if (caller != null) {
2241 N = results.size();
2242 for (int i=0; i<N; i++) {
2243 ActivityInfo ainfo = results.get(i).activityInfo;
2244 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2245 && caller.getClassName().equals(ainfo.name)) {
2246 results.remove(i);
2247 break;
2248 }
2249 }
2250 }
2251
2252 // If the caller didn't request filter information,
2253 // drop them now so we don't have to
2254 // marshall/unmarshall it.
2255 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2256 N = results.size();
2257 for (int i=0; i<N; i++) {
2258 results.get(i).filter = null;
2259 }
2260 }
2261
2262 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2263 return results;
2264 }
2265
2266 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2267 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002268 ComponentName comp = intent.getComponent();
2269 if (comp != null) {
2270 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2271 ActivityInfo ai = getReceiverInfo(comp, flags);
2272 if (ai != null) {
2273 ResolveInfo ri = new ResolveInfo();
2274 ri.activityInfo = ai;
2275 list.add(ri);
2276 }
2277 return list;
2278 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002281 String pkgName = intent.getPackage();
2282 if (pkgName == null) {
2283 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2284 resolvedType, flags);
2285 }
2286 PackageParser.Package pkg = mPackages.get(pkgName);
2287 if (pkg != null) {
2288 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2289 resolvedType, flags, pkg.receivers);
2290 }
2291 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 }
2293 }
2294
2295 public ResolveInfo resolveService(Intent intent, String resolvedType,
2296 int flags) {
2297 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2298 flags);
2299 if (query != null) {
2300 if (query.size() >= 1) {
2301 // If there is more than one service with the same priority,
2302 // just arbitrarily pick the first one.
2303 return query.get(0);
2304 }
2305 }
2306 return null;
2307 }
2308
2309 public List<ResolveInfo> queryIntentServices(Intent intent,
2310 String resolvedType, int flags) {
2311 ComponentName comp = intent.getComponent();
2312 if (comp != null) {
2313 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2314 ServiceInfo si = getServiceInfo(comp, flags);
2315 if (si != null) {
2316 ResolveInfo ri = new ResolveInfo();
2317 ri.serviceInfo = si;
2318 list.add(ri);
2319 }
2320 return list;
2321 }
2322
2323 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002324 String pkgName = intent.getPackage();
2325 if (pkgName == null) {
2326 return (List<ResolveInfo>)mServices.queryIntent(intent,
2327 resolvedType, flags);
2328 }
2329 PackageParser.Package pkg = mPackages.get(pkgName);
2330 if (pkg != null) {
2331 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2332 resolvedType, flags, pkg.services);
2333 }
2334 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002335 }
2336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 public List<PackageInfo> getInstalledPackages(int flags) {
2339 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2340
2341 synchronized (mPackages) {
2342 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2343 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2344 while (i.hasNext()) {
2345 final PackageSetting ps = i.next();
2346 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2347 if(psPkg != null) {
2348 finalList.add(psPkg);
2349 }
2350 }
2351 }
2352 else {
2353 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2354 while (i.hasNext()) {
2355 final PackageParser.Package p = i.next();
2356 if (p.applicationInfo != null) {
2357 PackageInfo pi = generatePackageInfo(p, flags);
2358 if(pi != null) {
2359 finalList.add(pi);
2360 }
2361 }
2362 }
2363 }
2364 }
2365 return finalList;
2366 }
2367
2368 public List<ApplicationInfo> getInstalledApplications(int flags) {
2369 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2370 synchronized(mPackages) {
2371 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2372 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2373 while (i.hasNext()) {
2374 final PackageSetting ps = i.next();
2375 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2376 if(ai != null) {
2377 finalList.add(ai);
2378 }
2379 }
2380 }
2381 else {
2382 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2383 while (i.hasNext()) {
2384 final PackageParser.Package p = i.next();
2385 if (p.applicationInfo != null) {
2386 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2387 if(ai != null) {
2388 finalList.add(ai);
2389 }
2390 }
2391 }
2392 }
2393 }
2394 return finalList;
2395 }
2396
2397 public List<ApplicationInfo> getPersistentApplications(int flags) {
2398 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2399
2400 synchronized (mPackages) {
2401 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2402 while (i.hasNext()) {
2403 PackageParser.Package p = i.next();
2404 if (p.applicationInfo != null
2405 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002406 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002407 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 }
2409 }
2410 }
2411
2412 return finalList;
2413 }
2414
2415 public ProviderInfo resolveContentProvider(String name, int flags) {
2416 synchronized (mPackages) {
2417 final PackageParser.Provider provider = mProviders.get(name);
2418 return provider != null
2419 && mSettings.isEnabledLP(provider.info, flags)
2420 && (!mSafeMode || (provider.info.applicationInfo.flags
2421 &ApplicationInfo.FLAG_SYSTEM) != 0)
2422 ? PackageParser.generateProviderInfo(provider, flags)
2423 : null;
2424 }
2425 }
2426
Fred Quintana718d8a22009-04-29 17:53:20 -07002427 /**
2428 * @deprecated
2429 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 public void querySyncProviders(List outNames, List outInfo) {
2431 synchronized (mPackages) {
2432 Iterator<Map.Entry<String, PackageParser.Provider>> i
2433 = mProviders.entrySet().iterator();
2434
2435 while (i.hasNext()) {
2436 Map.Entry<String, PackageParser.Provider> entry = i.next();
2437 PackageParser.Provider p = entry.getValue();
2438
2439 if (p.syncable
2440 && (!mSafeMode || (p.info.applicationInfo.flags
2441 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2442 outNames.add(entry.getKey());
2443 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2444 }
2445 }
2446 }
2447 }
2448
2449 public List<ProviderInfo> queryContentProviders(String processName,
2450 int uid, int flags) {
2451 ArrayList<ProviderInfo> finalList = null;
2452
2453 synchronized (mPackages) {
2454 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2455 while (i.hasNext()) {
2456 PackageParser.Provider p = i.next();
2457 if (p.info.authority != null
2458 && (processName == null ||
2459 (p.info.processName.equals(processName)
2460 && p.info.applicationInfo.uid == uid))
2461 && mSettings.isEnabledLP(p.info, flags)
2462 && (!mSafeMode || (p.info.applicationInfo.flags
2463 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2464 if (finalList == null) {
2465 finalList = new ArrayList<ProviderInfo>(3);
2466 }
2467 finalList.add(PackageParser.generateProviderInfo(p,
2468 flags));
2469 }
2470 }
2471 }
2472
2473 if (finalList != null) {
2474 Collections.sort(finalList, mProviderInitOrderSorter);
2475 }
2476
2477 return finalList;
2478 }
2479
2480 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2481 int flags) {
2482 synchronized (mPackages) {
2483 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2484 return PackageParser.generateInstrumentationInfo(i, flags);
2485 }
2486 }
2487
2488 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2489 int flags) {
2490 ArrayList<InstrumentationInfo> finalList =
2491 new ArrayList<InstrumentationInfo>();
2492
2493 synchronized (mPackages) {
2494 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2495 while (i.hasNext()) {
2496 PackageParser.Instrumentation p = i.next();
2497 if (targetPackage == null
2498 || targetPackage.equals(p.info.targetPackage)) {
2499 finalList.add(PackageParser.generateInstrumentationInfo(p,
2500 flags));
2501 }
2502 }
2503 }
2504
2505 return finalList;
2506 }
2507
2508 private void scanDirLI(File dir, int flags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002510 if (files == null) {
2511 Log.d(TAG, "No files in app dir " + dir);
2512 return;
2513 }
2514
2515 Log.d(TAG, "Scanning app dir " + dir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516
2517 int i;
2518 for (i=0; i<files.length; i++) {
2519 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002520 if (!isPackageFilename(files[i])) {
2521 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002522 continue;
2523 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002524 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002526 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002527 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2528 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002529 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002530 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002531 file.delete();
2532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 }
2534 }
2535
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002536 private static File getSettingsProblemFile() {
2537 File dataDir = Environment.getDataDirectory();
2538 File systemDir = new File(dataDir, "system");
2539 File fname = new File(systemDir, "uiderrors.txt");
2540 return fname;
2541 }
2542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 private static void reportSettingsProblem(int priority, String msg) {
2544 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002545 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 FileOutputStream out = new FileOutputStream(fname, true);
2547 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002548 SimpleDateFormat formatter = new SimpleDateFormat();
2549 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2550 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 pw.close();
2552 FileUtils.setPermissions(
2553 fname.toString(),
2554 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2555 -1, -1);
2556 } catch (java.io.IOException e) {
2557 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002558 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 }
2560
2561 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2562 PackageParser.Package pkg, File srcFile, int parseFlags) {
2563 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002564 if (ps != null
2565 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002566 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002567 if (ps.signatures.mSignatures != null
2568 && ps.signatures.mSignatures.length != 0) {
2569 // Optimization: reuse the existing cached certificates
2570 // if the package appears to be unchanged.
2571 pkg.mSignatures = ps.signatures.mSignatures;
2572 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
Jeff Browne7600722010-04-07 18:28:23 -07002574
2575 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002576 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002577 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2578 }
2579
2580 if (!pp.collectCertificates(pkg, parseFlags)) {
2581 mLastScanError = pp.getParseError();
2582 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 }
2584 }
2585 return true;
2586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 /*
2589 * Scan a package and return the newly parsed package.
2590 * Returns null in case of errors and the error code is stored in mLastScanError
2591 */
2592 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002593 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002595 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002597 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002599 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002600 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 if (pkg == null) {
2602 mLastScanError = pp.getParseError();
2603 return null;
2604 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002605 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002606 PackageSetting updatedPkg;
2607 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002608 // Look to see if we already know about this package.
2609 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002610 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002611 // This package has been renamed to its original name. Let's
2612 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002613 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002614 }
2615 // If there was no original package, see one for the real package name.
2616 if (ps == null) {
2617 ps = mSettings.peekPackageLP(pkg.packageName);
2618 }
2619 // Check to see if this package could be hiding/updating a system
2620 // package. Must look for it either under the original or real
2621 // package name depending on our state.
2622 updatedPkg = mSettings.mDisabledSysPackages.get(
2623 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002625 // First check if this is a system package that may involve an update
2626 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002627 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002628 // The path has changed from what was last scanned... check the
2629 // version of the new path against what we have stored to determine
2630 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002631 if (pkg.mVersionCode < ps.versionCode) {
2632 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002633 // Ignore entry. Skip it.
2634 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2635 + "ignored: updated version " + ps.versionCode
2636 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002637 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2638 return null;
2639 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002640 // The current app on the system partion is better than
2641 // what we have updated to on the data partition; switch
2642 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002643 // At this point, its safely assumed that package installation for
2644 // apps in system partition will go through. If not there won't be a working
2645 // version of the app
2646 synchronized (mPackages) {
2647 // Just remove the loaded entries from package lists.
2648 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002649 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002650 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002651 + "reverting from " + ps.codePathString
2652 + ": new version " + pkg.mVersionCode
2653 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002654 InstallArgs args = new FileInstallArgs(ps.codePathString,
2655 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002656 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002657 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 }
2660 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002661 if (updatedPkg != null) {
2662 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2663 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2664 }
2665 // Verify certificates against what was last scanned
2666 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002667 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002668 return null;
2669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 // The apk is forward locked (not public) if its code and resources
2671 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002672 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002674 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002675 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002676
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002677 String codePath = null;
2678 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002679 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2680 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002681 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002682 } else {
2683 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002684 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002685 }
2686 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002687 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002688 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002689 codePath = pkg.mScanPath;
2690 // Set application objects path explicitly.
2691 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002692 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002693 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 }
2695
Kenny Root85387d72010-08-26 10:13:11 -07002696 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2697 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002698 pkg.mPath = pkg.mScanPath = destCodePath;
2699 pkg.applicationInfo.sourceDir = destCodePath;
2700 pkg.applicationInfo.publicSourceDir = destResPath;
2701 }
2702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 private static String fixProcessName(String defProcessName,
2704 String processName, int uid) {
2705 if (processName == null) {
2706 return defProcessName;
2707 }
2708 return processName;
2709 }
2710
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002711 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002712 PackageParser.Package pkg) {
2713 if (pkgSetting.signatures.mSignatures != null) {
2714 // Already existing package. Make sure signatures match
2715 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2716 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002717 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002718 + " signatures do not match the previously installed version; ignoring!");
2719 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 return false;
2721 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002722 }
2723 // Check for shared user signatures
2724 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2725 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2726 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2727 Slog.e(TAG, "Package " + pkg.packageName
2728 + " has no signatures that match those in shared user "
2729 + pkgSetting.sharedUser.name + "; ignoring!");
2730 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2731 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002733 }
2734 return true;
2735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 public boolean performDexOpt(String packageName) {
2738 if (!mNoDexOpt) {
2739 return false;
2740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002741
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002742 PackageParser.Package p;
2743 synchronized (mPackages) {
2744 p = mPackages.get(packageName);
2745 if (p == null || p.mDidDexOpt) {
2746 return false;
2747 }
2748 }
2749 synchronized (mInstallLock) {
2750 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2751 }
2752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002753
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002754 static final int DEX_OPT_SKIPPED = 0;
2755 static final int DEX_OPT_PERFORMED = 1;
2756 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002757
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002758 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2759 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002760 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002761 String path = pkg.mScanPath;
2762 int ret = 0;
2763 try {
2764 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002765 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002766 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002767 pkg.mDidDexOpt = true;
2768 performed = true;
2769 }
2770 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002771 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002772 ret = -1;
2773 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002774 Slog.w(TAG, "IOException reading apk: " + path, e);
2775 ret = -1;
2776 } catch (dalvik.system.StaleDexCacheError e) {
2777 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2778 ret = -1;
2779 } catch (Exception e) {
2780 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002781 ret = -1;
2782 }
2783 if (ret < 0) {
2784 //error from installer
2785 return DEX_OPT_FAILED;
2786 }
2787 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002788
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002789 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2790 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002791
2792 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2793 return Environment.isEncryptedFilesystemEnabled() &&
2794 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2795 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002796
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002797 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2798 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002799 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002800 + " to " + newPkg.packageName
2801 + ": old package not in system partition");
2802 return false;
2803 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002804 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002805 + " to " + newPkg.packageName
2806 + ": old package still exists");
2807 return false;
2808 }
2809 return true;
2810 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002811
2812 private File getDataPathForPackage(PackageParser.Package pkg) {
2813 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2814 File dataPath;
2815 if (useEncryptedFSDir) {
2816 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2817 } else {
2818 dataPath = new File(mAppDataDir, pkg.packageName);
2819 }
2820 return dataPath;
2821 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002822
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002823 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2824 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002825 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002826 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2827 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002828 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002829 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002830 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2831 return null;
2832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 mScanningPath = scanFile;
2834 if (pkg == null) {
2835 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2836 return null;
2837 }
2838
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002839 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2840 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2841 }
2842
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002843 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 synchronized (mPackages) {
2845 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002846 Slog.w(TAG, "*************************************************");
2847 Slog.w(TAG, "Core android package being redefined. Skipping.");
2848 Slog.w(TAG, " file=" + mScanningPath);
2849 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2851 return null;
2852 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 // Set up information for our fall-back user intent resolution
2855 // activity.
2856 mPlatformPackage = pkg;
2857 pkg.mVersionCode = mSdkVersion;
2858 mAndroidApplication = pkg.applicationInfo;
2859 mResolveActivity.applicationInfo = mAndroidApplication;
2860 mResolveActivity.name = ResolverActivity.class.getName();
2861 mResolveActivity.packageName = mAndroidApplication.packageName;
2862 mResolveActivity.processName = mAndroidApplication.processName;
2863 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2864 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2865 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2866 mResolveActivity.exported = true;
2867 mResolveActivity.enabled = true;
2868 mResolveInfo.activityInfo = mResolveActivity;
2869 mResolveInfo.priority = 0;
2870 mResolveInfo.preferredOrder = 0;
2871 mResolveInfo.match = 0;
2872 mResolveComponentName = new ComponentName(
2873 mAndroidApplication.packageName, mResolveActivity.name);
2874 }
2875 }
2876
2877 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002878 TAG, "Scanning package " + pkg.packageName);
2879 if (mPackages.containsKey(pkg.packageName)
2880 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002881 Slog.w(TAG, "*************************************************");
2882 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002884 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2886 return null;
2887 }
2888
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002889 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002890 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2891 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 SharedUserSetting suid = null;
2894 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002895
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002896 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2897 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002898 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002899 pkg.mRealPackage = null;
2900 pkg.mAdoptPermissions = null;
2901 }
2902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 synchronized (mPackages) {
2904 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002905 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2906 if (mTmpSharedLibraries == null ||
2907 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2908 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2909 }
2910 int num = 0;
2911 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2912 for (int i=0; i<N; i++) {
2913 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002915 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002917 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2919 return null;
2920 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002921 mTmpSharedLibraries[num] = file;
2922 num++;
2923 }
2924 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2925 for (int i=0; i<N; i++) {
2926 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2927 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002928 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002929 + " desires unavailable shared library "
2930 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2931 } else {
2932 mTmpSharedLibraries[num] = file;
2933 num++;
2934 }
2935 }
2936 if (num > 0) {
2937 pkg.usesLibraryFiles = new String[num];
2938 System.arraycopy(mTmpSharedLibraries, 0,
2939 pkg.usesLibraryFiles, 0, num);
2940 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002941
Dianne Hackborn49237342009-08-27 20:08:01 -07002942 if (pkg.reqFeatures != null) {
2943 N = pkg.reqFeatures.size();
2944 for (int i=0; i<N; i++) {
2945 FeatureInfo fi = pkg.reqFeatures.get(i);
2946 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2947 // Don't care.
2948 continue;
2949 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002950
Dianne Hackborn49237342009-08-27 20:08:01 -07002951 if (fi.name != null) {
2952 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002953 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002954 + " requires unavailable feature "
2955 + fi.name + "; failing!");
2956 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2957 return null;
2958 }
2959 }
2960 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 }
2962 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002963
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 if (pkg.mSharedUserId != null) {
2965 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2966 pkg.applicationInfo.flags, true);
2967 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002968 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002969 + " for shared user failed");
2970 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2971 return null;
2972 }
2973 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2974 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2975 + suid.userId + "): packages=" + suid.packages);
2976 }
2977 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002978
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002979 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002980 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002981 Log.w(TAG, "WAITING FOR DEBUGGER");
2982 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002983 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2984 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002985 }
2986 }
2987
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002988 // Check if we are renaming from an original package name.
2989 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002990 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002991 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002992 // This package may need to be renamed to a previously
2993 // installed name. Let's check on that...
2994 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002995 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002996 // This package had originally been installed as the
2997 // original name, and we have already taken care of
2998 // transitioning to the new one. Just update the new
2999 // one to continue using the old name.
3000 realName = pkg.mRealPackage;
3001 if (!pkg.packageName.equals(renamed)) {
3002 // Callers into this function may have already taken
3003 // care of renaming the package; only do it here if
3004 // it is not already done.
3005 pkg.setPackageName(renamed);
3006 }
3007
Dianne Hackbornc1552392010-03-03 16:19:01 -08003008 } else {
3009 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
3010 if ((origPackage=mSettings.peekPackageLP(
3011 pkg.mOriginalPackages.get(i))) != null) {
3012 // We do have the package already installed under its
3013 // original name... should we use it?
3014 if (!verifyPackageUpdate(origPackage, pkg)) {
3015 // New package is not compatible with original.
3016 origPackage = null;
3017 continue;
3018 } else if (origPackage.sharedUser != null) {
3019 // Make sure uid is compatible between packages.
3020 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003021 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003022 + " to " + pkg.packageName + ": old uid "
3023 + origPackage.sharedUser.name
3024 + " differs from " + pkg.mSharedUserId);
3025 origPackage = null;
3026 continue;
3027 }
3028 } else {
3029 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3030 + pkg.packageName + " to old name " + origPackage.name);
3031 }
3032 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003033 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003034 }
3035 }
3036 }
3037
3038 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003039 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003040 + " was transferred to another, but its .apk remains");
3041 }
3042
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003043 // Just create the setting, don't add it yet. For already existing packages
3044 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003045 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003046 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3047 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003049 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3051 return null;
3052 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003053
3054 if (pkgSetting.origPackage != null) {
3055 // If we are first transitioning from an original package,
3056 // fix up the new package's name now. We need to do this after
3057 // looking up the package under its new name, so getPackageLP
3058 // can take care of fiddling things correctly.
3059 pkg.setPackageName(origPackage.name);
3060
3061 // File a report about this.
3062 String msg = "New package " + pkgSetting.realName
3063 + " renamed to replace old package " + pkgSetting.name;
3064 reportSettingsProblem(Log.WARN, msg);
3065
3066 // Make a note of it.
3067 mTransferedPackages.add(origPackage.name);
3068
3069 // No longer need to retain this.
3070 pkgSetting.origPackage = null;
3071 }
3072
3073 if (realName != null) {
3074 // Make a note of it.
3075 mTransferedPackages.add(pkg.packageName);
3076 }
3077
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003078 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3080 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 pkg.applicationInfo.uid = pkgSetting.userId;
3083 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003084
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003085 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003086 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 return null;
3088 }
3089 // The signature has changed, but this package is in the system
3090 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003091 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 // However... if this package is part of a shared user, but it
3093 // doesn't match the signature of the shared user, let's fail.
3094 // What this means is that you can't change the signatures
3095 // associated with an overall shared user, which doesn't seem all
3096 // that unreasonable.
3097 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003098 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3099 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3100 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3102 return null;
3103 }
3104 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003105 // File a report about this.
3106 String msg = "System package " + pkg.packageName
3107 + " signature changed; retaining data.";
3108 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003110
The Android Open Source Project10592532009-03-18 17:39:46 -07003111 // Verify that this new package doesn't have any content providers
3112 // that conflict with existing packages. Only do this if the
3113 // package isn't already installed, since we don't want to break
3114 // things that are installed.
3115 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3116 int N = pkg.providers.size();
3117 int i;
3118 for (i=0; i<N; i++) {
3119 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003120 if (p.info.authority != null) {
3121 String names[] = p.info.authority.split(";");
3122 for (int j = 0; j < names.length; j++) {
3123 if (mProviders.containsKey(names[j])) {
3124 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003125 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003126 " (in package " + pkg.applicationInfo.packageName +
3127 ") is already used by "
3128 + ((other != null && other.getComponentName() != null)
3129 ? other.getComponentName().getPackageName() : "?"));
3130 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3131 return null;
3132 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003133 }
3134 }
3135 }
3136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 }
3138
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003139 final String pkgName = pkg.packageName;
3140
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003141 if (pkg.mAdoptPermissions != null) {
3142 // This package wants to adopt ownership of permissions from
3143 // another package.
3144 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3145 String origName = pkg.mAdoptPermissions.get(i);
3146 PackageSetting orig = mSettings.peekPackageLP(origName);
3147 if (orig != null) {
3148 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003149 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003150 + origName + " to " + pkg.packageName);
3151 mSettings.transferPermissions(origName, pkg.packageName);
3152 }
3153 }
3154 }
3155 }
3156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 long scanFileTime = scanFile.lastModified();
3158 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003159 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 pkg.applicationInfo.processName = fixProcessName(
3161 pkg.applicationInfo.packageName,
3162 pkg.applicationInfo.processName,
3163 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164
3165 File dataPath;
3166 if (mPlatformPackage == pkg) {
3167 // The system package is special.
3168 dataPath = new File (Environment.getDataDirectory(), "system");
3169 pkg.applicationInfo.dataDir = dataPath.getPath();
3170 } else {
3171 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003172 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003173 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003174
3175 boolean uidError = false;
3176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 if (dataPath.exists()) {
3178 mOutPermissions[1] = 0;
3179 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003180
3181 // If we have mismatched owners for the data path, we have a
3182 // problem (unless we're running in the simulator.)
3183 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 boolean recovered = false;
3185 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3186 // If this is a system app, we can at least delete its
3187 // current data so the application will still work.
3188 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003189 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003190 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 // Old data gone!
3192 String msg = "System package " + pkg.packageName
3193 + " has changed from uid: "
3194 + mOutPermissions[1] + " to "
3195 + pkg.applicationInfo.uid + "; old data erased";
3196 reportSettingsProblem(Log.WARN, msg);
3197 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003200 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 pkg.applicationInfo.uid);
3202 if (ret == -1) {
3203 // Ack should not happen!
3204 msg = "System package " + pkg.packageName
3205 + " could not have data directory re-created after delete.";
3206 reportSettingsProblem(Log.WARN, msg);
3207 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3208 return null;
3209 }
3210 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 if (!recovered) {
3213 mHasSystemUidErrors = true;
3214 }
3215 }
3216 if (!recovered) {
3217 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3218 + pkg.applicationInfo.uid + "/fs_"
3219 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003220 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 String msg = "Package " + pkg.packageName
3222 + " has mismatched uid: "
3223 + mOutPermissions[1] + " on disk, "
3224 + pkg.applicationInfo.uid + " in settings";
3225 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003226 mSettings.mReadMessages.append(msg);
3227 mSettings.mReadMessages.append('\n');
3228 uidError = true;
3229 if (!pkgSetting.uidError) {
3230 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 }
3233 }
3234 }
3235 pkg.applicationInfo.dataDir = dataPath.getPath();
3236 } else {
3237 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3238 Log.v(TAG, "Want this data dir: " + dataPath);
3239 //invoke installer to do the actual installation
3240 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003241 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 pkg.applicationInfo.uid);
3243 if(ret < 0) {
3244 // Error from installer
3245 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3246 return null;
3247 }
3248 } else {
3249 dataPath.mkdirs();
3250 if (dataPath.exists()) {
3251 FileUtils.setPermissions(
3252 dataPath.toString(),
3253 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3254 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3255 }
3256 }
3257 if (dataPath.exists()) {
3258 pkg.applicationInfo.dataDir = dataPath.getPath();
3259 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003260 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 pkg.applicationInfo.dataDir = null;
3262 }
3263 }
Kenny Root85387d72010-08-26 10:13:11 -07003264
Kenny Root806cc132010-09-12 08:34:19 -07003265 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3266
Kenny Root85387d72010-08-26 10:13:11 -07003267 /*
3268 * Set the data dir to the default "/data/data/<package name>/lib"
3269 * if we got here without anyone telling us different (e.g., apps
3270 * stored on SD card have their native libraries stored in the ASEC
3271 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003272 *
3273 * This happens during an upgrade from a package settings file that
3274 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003275 */
Kenny Root806cc132010-09-12 08:34:19 -07003276 if (pkgSetting.nativeLibraryPathString == null && pkg.applicationInfo.dataDir != null) {
3277 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3278 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3279 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
Kenny Root85387d72010-08-26 10:13:11 -07003280 }
3281
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003282 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 }
3284
Kenny Root85387d72010-08-26 10:13:11 -07003285 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 if (mInstaller != null) {
3287 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003288 /* Note: We don't want to unpack the native binaries for
3289 * system applications, unless they have been updated
3290 * (the binaries are already under /system/lib).
3291 * Also, don't unpack libs for apps on the external card
3292 * since they should have their libraries in the ASEC
3293 * container already.
3294 *
3295 * In other words, we're going to unpack the binaries
3296 * only for non-system apps and system app upgrades.
3297 */
3298 if ((!isSystemApp(pkg) || isUpdatedSystemApp(pkg)) && !isExternal(pkg)) {
3299 Log.i(TAG, path + " changed; unpacking");
3300 File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root85387d72010-08-26 10:13:11 -07003301 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003303 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003304
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003305 if ((scanMode&SCAN_NO_DEX) == 0) {
3306 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3308 return null;
3309 }
3310 }
3311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 if (mFactoryTest && pkg.requestedPermissions.contains(
3314 android.Manifest.permission.FACTORY_TEST)) {
3315 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3316 }
3317
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003318 // Request the ActivityManager to kill the process(only for existing packages)
3319 // so that we do not end up in a confused state while the user is still using the older
3320 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003321 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003322 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003323 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003324 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003327 // We don't expect installation to fail beyond this point,
3328 if ((scanMode&SCAN_MONITOR) != 0) {
3329 mAppDirs.put(pkg.mPath, pkg);
3330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003332 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003334 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003335 // Make sure we don't accidentally delete its data.
3336 mSettings.mPackagesToBeCleaned.remove(pkgName);
3337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 int N = pkg.providers.size();
3339 StringBuilder r = null;
3340 int i;
3341 for (i=0; i<N; i++) {
3342 PackageParser.Provider p = pkg.providers.get(i);
3343 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3344 p.info.processName, pkg.applicationInfo.uid);
3345 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3346 p.info.name), p);
3347 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003348 if (p.info.authority != null) {
3349 String names[] = p.info.authority.split(";");
3350 p.info.authority = null;
3351 for (int j = 0; j < names.length; j++) {
3352 if (j == 1 && p.syncable) {
3353 // We only want the first authority for a provider to possibly be
3354 // syncable, so if we already added this provider using a different
3355 // authority clear the syncable flag. We copy the provider before
3356 // changing it because the mProviders object contains a reference
3357 // to a provider that we don't want to change.
3358 // Only do this for the second authority since the resulting provider
3359 // object can be the same for all future authorities for this provider.
3360 p = new PackageParser.Provider(p);
3361 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003362 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003363 if (!mProviders.containsKey(names[j])) {
3364 mProviders.put(names[j], p);
3365 if (p.info.authority == null) {
3366 p.info.authority = names[j];
3367 } else {
3368 p.info.authority = p.info.authority + ";" + names[j];
3369 }
3370 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3371 Log.d(TAG, "Registered content provider: " + names[j] +
3372 ", className = " + p.info.name +
3373 ", isSyncable = " + p.info.isSyncable);
3374 } else {
3375 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003376 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003377 " (in package " + pkg.applicationInfo.packageName +
3378 "): name already used by "
3379 + ((other != null && other.getComponentName() != null)
3380 ? other.getComponentName().getPackageName() : "?"));
3381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 }
3383 }
3384 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3385 if (r == null) {
3386 r = new StringBuilder(256);
3387 } else {
3388 r.append(' ');
3389 }
3390 r.append(p.info.name);
3391 }
3392 }
3393 if (r != null) {
3394 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3395 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 N = pkg.services.size();
3398 r = null;
3399 for (i=0; i<N; i++) {
3400 PackageParser.Service s = pkg.services.get(i);
3401 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3402 s.info.processName, pkg.applicationInfo.uid);
3403 mServices.addService(s);
3404 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3405 if (r == null) {
3406 r = new StringBuilder(256);
3407 } else {
3408 r.append(' ');
3409 }
3410 r.append(s.info.name);
3411 }
3412 }
3413 if (r != null) {
3414 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3415 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 N = pkg.receivers.size();
3418 r = null;
3419 for (i=0; i<N; i++) {
3420 PackageParser.Activity a = pkg.receivers.get(i);
3421 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3422 a.info.processName, pkg.applicationInfo.uid);
3423 mReceivers.addActivity(a, "receiver");
3424 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3425 if (r == null) {
3426 r = new StringBuilder(256);
3427 } else {
3428 r.append(' ');
3429 }
3430 r.append(a.info.name);
3431 }
3432 }
3433 if (r != null) {
3434 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3435 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 N = pkg.activities.size();
3438 r = null;
3439 for (i=0; i<N; i++) {
3440 PackageParser.Activity a = pkg.activities.get(i);
3441 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3442 a.info.processName, pkg.applicationInfo.uid);
3443 mActivities.addActivity(a, "activity");
3444 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3445 if (r == null) {
3446 r = new StringBuilder(256);
3447 } else {
3448 r.append(' ');
3449 }
3450 r.append(a.info.name);
3451 }
3452 }
3453 if (r != null) {
3454 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3455 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 N = pkg.permissionGroups.size();
3458 r = null;
3459 for (i=0; i<N; i++) {
3460 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3461 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3462 if (cur == null) {
3463 mPermissionGroups.put(pg.info.name, pg);
3464 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3465 if (r == null) {
3466 r = new StringBuilder(256);
3467 } else {
3468 r.append(' ');
3469 }
3470 r.append(pg.info.name);
3471 }
3472 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003473 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 + pg.info.packageName + " ignored: original from "
3475 + cur.info.packageName);
3476 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3477 if (r == null) {
3478 r = new StringBuilder(256);
3479 } else {
3480 r.append(' ');
3481 }
3482 r.append("DUP:");
3483 r.append(pg.info.name);
3484 }
3485 }
3486 }
3487 if (r != null) {
3488 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3489 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 N = pkg.permissions.size();
3492 r = null;
3493 for (i=0; i<N; i++) {
3494 PackageParser.Permission p = pkg.permissions.get(i);
3495 HashMap<String, BasePermission> permissionMap =
3496 p.tree ? mSettings.mPermissionTrees
3497 : mSettings.mPermissions;
3498 p.group = mPermissionGroups.get(p.info.group);
3499 if (p.info.group == null || p.group != null) {
3500 BasePermission bp = permissionMap.get(p.info.name);
3501 if (bp == null) {
3502 bp = new BasePermission(p.info.name, p.info.packageName,
3503 BasePermission.TYPE_NORMAL);
3504 permissionMap.put(p.info.name, bp);
3505 }
3506 if (bp.perm == null) {
3507 if (bp.sourcePackage == null
3508 || bp.sourcePackage.equals(p.info.packageName)) {
3509 BasePermission tree = findPermissionTreeLP(p.info.name);
3510 if (tree == null
3511 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003512 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 bp.perm = p;
3514 bp.uid = pkg.applicationInfo.uid;
3515 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3516 if (r == null) {
3517 r = new StringBuilder(256);
3518 } else {
3519 r.append(' ');
3520 }
3521 r.append(p.info.name);
3522 }
3523 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003524 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003525 + p.info.packageName + " ignored: base tree "
3526 + tree.name + " is from package "
3527 + tree.sourcePackage);
3528 }
3529 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003530 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 + p.info.packageName + " ignored: original from "
3532 + bp.sourcePackage);
3533 }
3534 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3535 if (r == null) {
3536 r = new StringBuilder(256);
3537 } else {
3538 r.append(' ');
3539 }
3540 r.append("DUP:");
3541 r.append(p.info.name);
3542 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003543 if (bp.perm == p) {
3544 bp.protectionLevel = p.info.protectionLevel;
3545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003547 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003548 + p.info.packageName + " ignored: no group "
3549 + p.group);
3550 }
3551 }
3552 if (r != null) {
3553 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3554 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003556 N = pkg.instrumentation.size();
3557 r = null;
3558 for (i=0; i<N; i++) {
3559 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3560 a.info.packageName = pkg.applicationInfo.packageName;
3561 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3562 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3563 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003564 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003565 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3567 if (r == null) {
3568 r = new StringBuilder(256);
3569 } else {
3570 r.append(' ');
3571 }
3572 r.append(a.info.name);
3573 }
3574 }
3575 if (r != null) {
3576 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003578
Dianne Hackborn854060af2009-07-09 18:14:31 -07003579 if (pkg.protectedBroadcasts != null) {
3580 N = pkg.protectedBroadcasts.size();
3581 for (i=0; i<N; i++) {
3582 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3583 }
3584 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 pkgSetting.setTimeStamp(scanFileTime);
3587 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 return pkg;
3590 }
3591
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003592 private void killApplication(String pkgName, int uid) {
3593 // Request the ActivityManager to kill the process(only for existing packages)
3594 // so that we do not end up in a confused state while the user is still using the older
3595 // version of the application while the new one gets installed.
3596 IActivityManager am = ActivityManagerNative.getDefault();
3597 if (am != null) {
3598 try {
3599 am.killApplicationWithUid(pkgName, uid);
3600 } catch (RemoteException e) {
3601 }
3602 }
3603 }
3604
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003605 // Return the path of the directory that will contain the native binaries
3606 // of a given installed package. This is relative to the data path.
3607 //
Kenny Root85387d72010-08-26 10:13:11 -07003608 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3609 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3610 if (nativeLibraryDir != null) {
3611 return new File(nativeLibraryDir);
3612 } else {
3613 // Fall back for old packages
3614 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3615 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003616 }
3617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003618 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3619 if (chatty && Config.LOGD) Log.d(
3620 TAG, "Removing package " + pkg.applicationInfo.packageName );
3621
3622 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003623 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 mPackages.remove(pkg.applicationInfo.packageName);
3626 if (pkg.mPath != null) {
3627 mAppDirs.remove(pkg.mPath);
3628 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003630 PackageSetting ps = (PackageSetting)pkg.mExtras;
3631 if (ps != null && ps.sharedUser != null) {
3632 // XXX don't do this until the data is removed.
3633 if (false) {
3634 ps.sharedUser.packages.remove(ps);
3635 if (ps.sharedUser.packages.size() == 0) {
3636 // Remove.
3637 }
3638 }
3639 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 int N = pkg.providers.size();
3642 StringBuilder r = null;
3643 int i;
3644 for (i=0; i<N; i++) {
3645 PackageParser.Provider p = pkg.providers.get(i);
3646 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3647 p.info.name));
3648 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 /* The is another ContentProvider with this authority when
3651 * this app was installed so this authority is null,
3652 * Ignore it as we don't have to unregister the provider.
3653 */
3654 continue;
3655 }
3656 String names[] = p.info.authority.split(";");
3657 for (int j = 0; j < names.length; j++) {
3658 if (mProviders.get(names[j]) == p) {
3659 mProviders.remove(names[j]);
3660 if (chatty && Config.LOGD) Log.d(
3661 TAG, "Unregistered content provider: " + names[j] +
3662 ", className = " + p.info.name +
3663 ", isSyncable = " + p.info.isSyncable);
3664 }
3665 }
3666 if (chatty) {
3667 if (r == null) {
3668 r = new StringBuilder(256);
3669 } else {
3670 r.append(' ');
3671 }
3672 r.append(p.info.name);
3673 }
3674 }
3675 if (r != null) {
3676 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3677 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 N = pkg.services.size();
3680 r = null;
3681 for (i=0; i<N; i++) {
3682 PackageParser.Service s = pkg.services.get(i);
3683 mServices.removeService(s);
3684 if (chatty) {
3685 if (r == null) {
3686 r = new StringBuilder(256);
3687 } else {
3688 r.append(' ');
3689 }
3690 r.append(s.info.name);
3691 }
3692 }
3693 if (r != null) {
3694 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 N = pkg.receivers.size();
3698 r = null;
3699 for (i=0; i<N; i++) {
3700 PackageParser.Activity a = pkg.receivers.get(i);
3701 mReceivers.removeActivity(a, "receiver");
3702 if (chatty) {
3703 if (r == null) {
3704 r = new StringBuilder(256);
3705 } else {
3706 r.append(' ');
3707 }
3708 r.append(a.info.name);
3709 }
3710 }
3711 if (r != null) {
3712 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 N = pkg.activities.size();
3716 r = null;
3717 for (i=0; i<N; i++) {
3718 PackageParser.Activity a = pkg.activities.get(i);
3719 mActivities.removeActivity(a, "activity");
3720 if (chatty) {
3721 if (r == null) {
3722 r = new StringBuilder(256);
3723 } else {
3724 r.append(' ');
3725 }
3726 r.append(a.info.name);
3727 }
3728 }
3729 if (r != null) {
3730 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 N = pkg.permissions.size();
3734 r = null;
3735 for (i=0; i<N; i++) {
3736 PackageParser.Permission p = pkg.permissions.get(i);
3737 boolean tree = false;
3738 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3739 if (bp == null) {
3740 tree = true;
3741 bp = mSettings.mPermissionTrees.get(p.info.name);
3742 }
3743 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003744 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 if (chatty) {
3746 if (r == null) {
3747 r = new StringBuilder(256);
3748 } else {
3749 r.append(' ');
3750 }
3751 r.append(p.info.name);
3752 }
3753 }
3754 }
3755 if (r != null) {
3756 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 N = pkg.instrumentation.size();
3760 r = null;
3761 for (i=0; i<N; i++) {
3762 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003763 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 if (chatty) {
3765 if (r == null) {
3766 r = new StringBuilder(256);
3767 } else {
3768 r.append(' ');
3769 }
3770 r.append(a.info.name);
3771 }
3772 }
3773 if (r != null) {
3774 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3775 }
3776 }
3777 }
3778
3779 private static final boolean isPackageFilename(String name) {
3780 return name != null && name.endsWith(".apk");
3781 }
3782
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003783 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3784 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3785 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3786 return true;
3787 }
3788 }
3789 return false;
3790 }
3791
3792 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003793 PackageParser.Package pkgInfo, boolean grantPermissions,
3794 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 // Make sure there are no dangling permission trees.
3796 Iterator<BasePermission> it = mSettings.mPermissionTrees
3797 .values().iterator();
3798 while (it.hasNext()) {
3799 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003800 if (bp.packageSetting == null) {
3801 // We may not yet have parsed the package, so just see if
3802 // we still know about its settings.
3803 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3804 }
3805 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003806 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 + " from package " + bp.sourcePackage);
3808 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003809 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3810 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3811 Slog.i(TAG, "Removing old permission tree: " + bp.name
3812 + " from package " + bp.sourcePackage);
3813 grantPermissions = true;
3814 it.remove();
3815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 }
3817 }
3818
3819 // Make sure all dynamic permissions have been assigned to a package,
3820 // and make sure there are no dangling permissions.
3821 it = mSettings.mPermissions.values().iterator();
3822 while (it.hasNext()) {
3823 BasePermission bp = it.next();
3824 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3825 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3826 + bp.name + " pkg=" + bp.sourcePackage
3827 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003828 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 BasePermission tree = findPermissionTreeLP(bp.name);
3830 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003831 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 bp.perm = new PackageParser.Permission(tree.perm.owner,
3833 new PermissionInfo(bp.pendingInfo));
3834 bp.perm.info.packageName = tree.perm.info.packageName;
3835 bp.perm.info.name = bp.name;
3836 bp.uid = tree.uid;
3837 }
3838 }
3839 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003840 if (bp.packageSetting == null) {
3841 // We may not yet have parsed the package, so just see if
3842 // we still know about its settings.
3843 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3844 }
3845 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003846 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 + " from package " + bp.sourcePackage);
3848 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003849 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3850 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3851 Slog.i(TAG, "Removing old permission: " + bp.name
3852 + " from package " + bp.sourcePackage);
3853 grantPermissions = true;
3854 it.remove();
3855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 }
3857 }
3858
3859 // Now update the permissions for all packages, in particular
3860 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003861 if (grantPermissions) {
3862 for (PackageParser.Package pkg : mPackages.values()) {
3863 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003864 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003865 }
3866 }
3867 }
3868
3869 if (pkgInfo != null) {
3870 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 }
3872 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3875 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3876 if (ps == null) {
3877 return;
3878 }
3879 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003880 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 if (replace) {
3883 ps.permissionsFixed = false;
3884 if (gp == ps) {
3885 gp.grantedPermissions.clear();
3886 gp.gids = mGlobalGids;
3887 }
3888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 if (gp.gids == null) {
3891 gp.gids = mGlobalGids;
3892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 final int N = pkg.requestedPermissions.size();
3895 for (int i=0; i<N; i++) {
3896 String name = pkg.requestedPermissions.get(i);
3897 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 if (false) {
3899 if (gp != ps) {
3900 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003901 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 }
3903 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003904 if (bp != null && bp.packageSetting != null) {
3905 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003907 boolean allowedSig = false;
3908 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3909 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003911 } else if (bp.packageSetting == null) {
3912 // This permission is invalid; skip it.
3913 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003914 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3915 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3916 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003917 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003918 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003920 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003921 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 // For updated system applications, the signatureOrSystem permission
3923 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003924 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3926 if(sysPs.grantedPermissions.contains(perm)) {
3927 allowed = true;
3928 } else {
3929 allowed = false;
3930 }
3931 } else {
3932 allowed = true;
3933 }
3934 }
3935 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003936 if (allowed) {
3937 allowedSig = true;
3938 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003939 } else {
3940 allowed = false;
3941 }
3942 if (false) {
3943 if (gp != ps) {
3944 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3945 }
3946 }
3947 if (allowed) {
3948 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3949 && ps.permissionsFixed) {
3950 // If this is an existing, non-system package, then
3951 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003952 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003954 // Except... if this is a permission that was added
3955 // to the platform (note: need to only do this when
3956 // updating the platform).
3957 final int NP = PackageParser.NEW_PERMISSIONS.length;
3958 for (int ip=0; ip<NP; ip++) {
3959 final PackageParser.NewPermissionInfo npi
3960 = PackageParser.NEW_PERMISSIONS[ip];
3961 if (npi.name.equals(perm)
3962 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3963 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003964 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003965 + pkg.packageName);
3966 break;
3967 }
3968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 }
3970 }
3971 if (allowed) {
3972 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003973 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 gp.grantedPermissions.add(perm);
3975 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003976 } else if (!ps.haveGids) {
3977 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 }
3979 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003980 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 + " to package " + pkg.packageName
3982 + " because it was previously installed without");
3983 }
3984 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003985 if (gp.grantedPermissions.remove(perm)) {
3986 changedPermission = true;
3987 gp.gids = removeInts(gp.gids, bp.gids);
3988 Slog.i(TAG, "Un-granting permission " + perm
3989 + " from package " + pkg.packageName
3990 + " (protectionLevel=" + bp.protectionLevel
3991 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3992 + ")");
3993 } else {
3994 Slog.w(TAG, "Not granting permission " + perm
3995 + " to package " + pkg.packageName
3996 + " (protectionLevel=" + bp.protectionLevel
3997 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3998 + ")");
3999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004000 }
4001 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004002 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 + " in package " + pkg.packageName);
4004 }
4005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004006
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004007 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004008 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4009 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 // This is the first that we have heard about this package, so the
4011 // permissions we have now selected are fixed until explicitly
4012 // changed.
4013 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004014 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004015 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004017
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 private final class ActivityIntentResolver
4019 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004020 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004022 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 }
4024
Mihai Preda074edef2009-05-18 17:13:31 +02004025 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004027 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4029 }
4030
Mihai Predaeae850c2009-05-13 10:13:48 +02004031 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4032 ArrayList<PackageParser.Activity> packageActivities) {
4033 if (packageActivities == null) {
4034 return null;
4035 }
4036 mFlags = flags;
4037 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4038 int N = packageActivities.size();
4039 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4040 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004041
4042 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004043 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004044 intentFilters = packageActivities.get(i).intents;
4045 if (intentFilters != null && intentFilters.size() > 0) {
4046 listCut.add(intentFilters);
4047 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004048 }
4049 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4050 }
4051
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004052 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004053 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 if (SHOW_INFO || Config.LOGV) Log.v(
4055 TAG, " " + type + " " +
4056 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4057 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4058 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004059 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4061 if (SHOW_INFO || Config.LOGV) {
4062 Log.v(TAG, " IntentFilter:");
4063 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4064 }
4065 if (!intent.debugCheck()) {
4066 Log.w(TAG, "==> For Activity " + a.info.name);
4067 }
4068 addFilter(intent);
4069 }
4070 }
4071
4072 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004073 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 if (SHOW_INFO || Config.LOGV) Log.v(
4075 TAG, " " + type + " " +
4076 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4077 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4078 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004079 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4081 if (SHOW_INFO || Config.LOGV) {
4082 Log.v(TAG, " IntentFilter:");
4083 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4084 }
4085 removeFilter(intent);
4086 }
4087 }
4088
4089 @Override
4090 protected boolean allowFilterResult(
4091 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4092 ActivityInfo filterAi = filter.activity.info;
4093 for (int i=dest.size()-1; i>=0; i--) {
4094 ActivityInfo destAi = dest.get(i).activityInfo;
4095 if (destAi.name == filterAi.name
4096 && destAi.packageName == filterAi.packageName) {
4097 return false;
4098 }
4099 }
4100 return true;
4101 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004104 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4105 return info.activity.owner.packageName;
4106 }
4107
4108 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4110 int match) {
4111 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4112 return null;
4113 }
4114 final PackageParser.Activity activity = info.activity;
4115 if (mSafeMode && (activity.info.applicationInfo.flags
4116 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4117 return null;
4118 }
4119 final ResolveInfo res = new ResolveInfo();
4120 res.activityInfo = PackageParser.generateActivityInfo(activity,
4121 mFlags);
4122 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4123 res.filter = info;
4124 }
4125 res.priority = info.getPriority();
4126 res.preferredOrder = activity.owner.mPreferredOrder;
4127 //System.out.println("Result: " + res.activityInfo.className +
4128 // " = " + res.priority);
4129 res.match = match;
4130 res.isDefault = info.hasDefault;
4131 res.labelRes = info.labelRes;
4132 res.nonLocalizedLabel = info.nonLocalizedLabel;
4133 res.icon = info.icon;
4134 return res;
4135 }
4136
4137 @Override
4138 protected void sortResults(List<ResolveInfo> results) {
4139 Collections.sort(results, mResolvePrioritySorter);
4140 }
4141
4142 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004143 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004145 out.print(prefix); out.print(
4146 Integer.toHexString(System.identityHashCode(filter.activity)));
4147 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004148 out.print(filter.activity.getComponentShortName());
4149 out.print(" filter ");
4150 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 }
4152
4153// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4154// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4155// final List<ResolveInfo> retList = Lists.newArrayList();
4156// while (i.hasNext()) {
4157// final ResolveInfo resolveInfo = i.next();
4158// if (isEnabledLP(resolveInfo.activityInfo)) {
4159// retList.add(resolveInfo);
4160// }
4161// }
4162// return retList;
4163// }
4164
4165 // Keys are String (activity class name), values are Activity.
4166 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4167 = new HashMap<ComponentName, PackageParser.Activity>();
4168 private int mFlags;
4169 }
4170
4171 private final class ServiceIntentResolver
4172 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004173 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004175 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 }
4177
Mihai Preda074edef2009-05-18 17:13:31 +02004178 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004179 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004180 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4182 }
4183
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004184 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4185 ArrayList<PackageParser.Service> packageServices) {
4186 if (packageServices == null) {
4187 return null;
4188 }
4189 mFlags = flags;
4190 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4191 int N = packageServices.size();
4192 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4193 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4194
4195 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4196 for (int i = 0; i < N; ++i) {
4197 intentFilters = packageServices.get(i).intents;
4198 if (intentFilters != null && intentFilters.size() > 0) {
4199 listCut.add(intentFilters);
4200 }
4201 }
4202 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4203 }
4204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004206 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 if (SHOW_INFO || Config.LOGV) Log.v(
4208 TAG, " " + (s.info.nonLocalizedLabel != null
4209 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4210 if (SHOW_INFO || Config.LOGV) Log.v(
4211 TAG, " Class=" + s.info.name);
4212 int NI = s.intents.size();
4213 int j;
4214 for (j=0; j<NI; j++) {
4215 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4216 if (SHOW_INFO || Config.LOGV) {
4217 Log.v(TAG, " IntentFilter:");
4218 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4219 }
4220 if (!intent.debugCheck()) {
4221 Log.w(TAG, "==> For Service " + s.info.name);
4222 }
4223 addFilter(intent);
4224 }
4225 }
4226
4227 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004228 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004229 if (SHOW_INFO || Config.LOGV) Log.v(
4230 TAG, " " + (s.info.nonLocalizedLabel != null
4231 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4232 if (SHOW_INFO || Config.LOGV) Log.v(
4233 TAG, " Class=" + s.info.name);
4234 int NI = s.intents.size();
4235 int j;
4236 for (j=0; j<NI; j++) {
4237 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4238 if (SHOW_INFO || Config.LOGV) {
4239 Log.v(TAG, " IntentFilter:");
4240 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4241 }
4242 removeFilter(intent);
4243 }
4244 }
4245
4246 @Override
4247 protected boolean allowFilterResult(
4248 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4249 ServiceInfo filterSi = filter.service.info;
4250 for (int i=dest.size()-1; i>=0; i--) {
4251 ServiceInfo destAi = dest.get(i).serviceInfo;
4252 if (destAi.name == filterSi.name
4253 && destAi.packageName == filterSi.packageName) {
4254 return false;
4255 }
4256 }
4257 return true;
4258 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004261 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4262 return info.service.owner.packageName;
4263 }
4264
4265 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4267 int match) {
4268 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4269 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4270 return null;
4271 }
4272 final PackageParser.Service service = info.service;
4273 if (mSafeMode && (service.info.applicationInfo.flags
4274 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4275 return null;
4276 }
4277 final ResolveInfo res = new ResolveInfo();
4278 res.serviceInfo = PackageParser.generateServiceInfo(service,
4279 mFlags);
4280 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4281 res.filter = filter;
4282 }
4283 res.priority = info.getPriority();
4284 res.preferredOrder = service.owner.mPreferredOrder;
4285 //System.out.println("Result: " + res.activityInfo.className +
4286 // " = " + res.priority);
4287 res.match = match;
4288 res.isDefault = info.hasDefault;
4289 res.labelRes = info.labelRes;
4290 res.nonLocalizedLabel = info.nonLocalizedLabel;
4291 res.icon = info.icon;
4292 return res;
4293 }
4294
4295 @Override
4296 protected void sortResults(List<ResolveInfo> results) {
4297 Collections.sort(results, mResolvePrioritySorter);
4298 }
4299
4300 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004301 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004302 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004303 out.print(prefix); out.print(
4304 Integer.toHexString(System.identityHashCode(filter.service)));
4305 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004306 out.print(filter.service.getComponentShortName());
4307 out.print(" filter ");
4308 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004309 }
4310
4311// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4312// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4313// final List<ResolveInfo> retList = Lists.newArrayList();
4314// while (i.hasNext()) {
4315// final ResolveInfo resolveInfo = (ResolveInfo) i;
4316// if (isEnabledLP(resolveInfo.serviceInfo)) {
4317// retList.add(resolveInfo);
4318// }
4319// }
4320// return retList;
4321// }
4322
4323 // Keys are String (activity class name), values are Activity.
4324 private final HashMap<ComponentName, PackageParser.Service> mServices
4325 = new HashMap<ComponentName, PackageParser.Service>();
4326 private int mFlags;
4327 };
4328
4329 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4330 new Comparator<ResolveInfo>() {
4331 public int compare(ResolveInfo r1, ResolveInfo r2) {
4332 int v1 = r1.priority;
4333 int v2 = r2.priority;
4334 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4335 if (v1 != v2) {
4336 return (v1 > v2) ? -1 : 1;
4337 }
4338 v1 = r1.preferredOrder;
4339 v2 = r2.preferredOrder;
4340 if (v1 != v2) {
4341 return (v1 > v2) ? -1 : 1;
4342 }
4343 if (r1.isDefault != r2.isDefault) {
4344 return r1.isDefault ? -1 : 1;
4345 }
4346 v1 = r1.match;
4347 v2 = r2.match;
4348 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4349 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4350 }
4351 };
4352
4353 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4354 new Comparator<ProviderInfo>() {
4355 public int compare(ProviderInfo p1, ProviderInfo p2) {
4356 final int v1 = p1.initOrder;
4357 final int v2 = p2.initOrder;
4358 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4359 }
4360 };
4361
Kenny Root93565c4b2010-06-18 15:46:06 -07004362 private static final boolean DEBUG_OBB = false;
4363
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004364 private static final void sendPackageBroadcast(String action, String pkg,
4365 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004366 IActivityManager am = ActivityManagerNative.getDefault();
4367 if (am != null) {
4368 try {
4369 final Intent intent = new Intent(action,
4370 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4371 if (extras != null) {
4372 intent.putExtras(extras);
4373 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004374 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004375 am.broadcastIntent(null, intent, null, finishedReceiver,
4376 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004377 } catch (RemoteException ex) {
4378 }
4379 }
4380 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004381
4382 public String nextPackageToClean(String lastPackage) {
4383 synchronized (mPackages) {
4384 if (!mMediaMounted) {
4385 // If the external storage is no longer mounted at this point,
4386 // the caller may not have been able to delete all of this
4387 // packages files and can not delete any more. Bail.
4388 return null;
4389 }
4390 if (lastPackage != null) {
4391 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4392 }
4393 return mSettings.mPackagesToBeCleaned.size() > 0
4394 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4395 }
4396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004397
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004398 void schedulePackageCleaning(String packageName) {
4399 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4400 }
4401
4402 void startCleaningPackages() {
4403 synchronized (mPackages) {
4404 if (!mMediaMounted) {
4405 return;
4406 }
4407 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4408 return;
4409 }
4410 }
4411 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4412 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4413 IActivityManager am = ActivityManagerNative.getDefault();
4414 if (am != null) {
4415 try {
4416 am.startService(null, intent, null);
4417 } catch (RemoteException e) {
4418 }
4419 }
4420 }
4421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422 private final class AppDirObserver extends FileObserver {
4423 public AppDirObserver(String path, int mask, boolean isrom) {
4424 super(path, mask);
4425 mRootDir = path;
4426 mIsRom = isrom;
4427 }
4428
4429 public void onEvent(int event, String path) {
4430 String removedPackage = null;
4431 int removedUid = -1;
4432 String addedPackage = null;
4433 int addedUid = -1;
4434
4435 synchronized (mInstallLock) {
4436 String fullPathStr = null;
4437 File fullPath = null;
4438 if (path != null) {
4439 fullPath = new File(mRootDir, path);
4440 fullPathStr = fullPath.getPath();
4441 }
4442
4443 if (Config.LOGV) Log.v(
4444 TAG, "File " + fullPathStr + " changed: "
4445 + Integer.toHexString(event));
4446
4447 if (!isPackageFilename(path)) {
4448 if (Config.LOGV) Log.v(
4449 TAG, "Ignoring change of non-package file: " + fullPathStr);
4450 return;
4451 }
4452
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004453 // Ignore packages that are being installed or
4454 // have just been installed.
4455 if (ignoreCodePath(fullPathStr)) {
4456 return;
4457 }
4458 PackageParser.Package p = null;
4459 synchronized (mPackages) {
4460 p = mAppDirs.get(fullPathStr);
4461 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004462 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004463 if (p != null) {
4464 removePackageLI(p, true);
4465 removedPackage = p.applicationInfo.packageName;
4466 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004467 }
4468 }
4469
4470 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004471 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004472 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004473 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4474 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004475 PackageParser.PARSE_CHATTY |
4476 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004477 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004478 if (p != null) {
4479 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004480 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004481 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004482 }
4483 addedPackage = p.applicationInfo.packageName;
4484 addedUid = p.applicationInfo.uid;
4485 }
4486 }
4487 }
4488
4489 synchronized (mPackages) {
4490 mSettings.writeLP();
4491 }
4492 }
4493
4494 if (removedPackage != null) {
4495 Bundle extras = new Bundle(1);
4496 extras.putInt(Intent.EXTRA_UID, removedUid);
4497 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004498 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4499 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 }
4501 if (addedPackage != null) {
4502 Bundle extras = new Bundle(1);
4503 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004504 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4505 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
4507 }
4508
4509 private final String mRootDir;
4510 private final boolean mIsRom;
4511 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 /* Called when a downloaded package installation has been confirmed by the user */
4514 public void installPackage(
4515 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004516 installPackage(packageURI, observer, flags, null);
4517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004518
Jacek Surazski65e13172009-04-28 15:26:38 +02004519 /* Called when a downloaded package installation has been confirmed by the user */
4520 public void installPackage(
4521 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4522 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 mContext.enforceCallingOrSelfPermission(
4524 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004525
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004526 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004527 msg.obj = new InstallParams(packageURI, observer, flags,
4528 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004529 mHandler.sendMessage(msg);
4530 }
4531
Christopher Tate1bb69062010-02-19 17:02:12 -08004532 public void finishPackageInstall(int token) {
4533 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4534 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4535 mHandler.sendMessage(msg);
4536 }
4537
Kenny Root93565c4b2010-06-18 15:46:06 -07004538 public void setPackageObbPath(String packageName, String path) {
4539 if (DEBUG_OBB)
4540 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4541 PackageSetting pkgSetting;
4542 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004543 final int permission = mContext.checkCallingPermission(
4544 android.Manifest.permission.INSTALL_PACKAGES);
4545 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004546 synchronized (mPackages) {
4547 pkgSetting = mSettings.mPackages.get(packageName);
4548 if (pkgSetting == null) {
4549 throw new IllegalArgumentException("Unknown package: " + packageName);
4550 }
4551 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4552 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4553 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4554 + pkgSetting.userId);
4555 }
4556 pkgSetting.obbPathString = path;
4557 mSettings.writeLP();
4558 }
4559 }
4560
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004561 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004562 // Queue up an async operation since the package installation may take a little while.
4563 mHandler.post(new Runnable() {
4564 public void run() {
4565 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004566 // Result object to be returned
4567 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004568 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004569 res.uid = -1;
4570 res.pkg = null;
4571 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004572 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004573 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004574 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004575 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004576 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004577 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004578 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004579
4580 // A restore should be performed at this point if (a) the install
4581 // succeeded, (b) the operation is not an update, and (c) the new
4582 // package has a backupAgent defined.
4583 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004584 boolean doRestore = (!update
4585 && res.pkg != null
4586 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004587
4588 // Set up the post-install work request bookkeeping. This will be used
4589 // and cleaned up by the post-install event handling regardless of whether
4590 // there's a restore pass performed. Token values are >= 1.
4591 int token;
4592 if (mNextInstallToken < 0) mNextInstallToken = 1;
4593 token = mNextInstallToken++;
4594
4595 PostInstallData data = new PostInstallData(args, res);
4596 mRunningInstalls.put(token, data);
4597 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4598
4599 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4600 // Pass responsibility to the Backup Manager. It will perform a
4601 // restore if appropriate, then pass responsibility back to the
4602 // Package Manager to run the post-install observer callbacks
4603 // and broadcasts.
4604 IBackupManager bm = IBackupManager.Stub.asInterface(
4605 ServiceManager.getService(Context.BACKUP_SERVICE));
4606 if (bm != null) {
4607 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4608 + " to BM for possible restore");
4609 try {
4610 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4611 } catch (RemoteException e) {
4612 // can't happen; the backup manager is local
4613 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004614 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004615 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004616 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004617 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004618 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004619 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004620 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004621 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004622
4623 if (!doRestore) {
4624 // No restore possible, or the Backup Manager was mysteriously not
4625 // available -- just fire the post-install work request directly.
4626 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4627 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4628 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630 }
4631 });
4632 }
4633
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004634 abstract class HandlerParams {
4635 final static int MAX_RETRIES = 4;
4636 int retry = 0;
4637 final void startCopy() {
4638 try {
4639 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4640 retry++;
4641 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004642 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004643 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4644 handleServiceError();
4645 return;
4646 } else {
4647 handleStartCopy();
4648 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4649 mHandler.sendEmptyMessage(MCS_UNBIND);
4650 }
4651 } catch (RemoteException e) {
4652 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4653 mHandler.sendEmptyMessage(MCS_RECONNECT);
4654 }
4655 handleReturnCode();
4656 }
4657
4658 final void serviceError() {
4659 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4660 handleServiceError();
4661 handleReturnCode();
4662 }
4663 abstract void handleStartCopy() throws RemoteException;
4664 abstract void handleServiceError();
4665 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004666 }
4667
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004668 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004669 final IPackageInstallObserver observer;
4670 int flags;
4671 final Uri packageURI;
4672 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004673 private InstallArgs mArgs;
4674 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004675 InstallParams(Uri packageURI,
4676 IPackageInstallObserver observer, int flags,
4677 String installerPackageName) {
4678 this.packageURI = packageURI;
4679 this.flags = flags;
4680 this.observer = observer;
4681 this.installerPackageName = installerPackageName;
4682 }
4683
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004684 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4685 String packageName = pkgLite.packageName;
4686 int installLocation = pkgLite.installLocation;
4687 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4688 synchronized (mPackages) {
4689 PackageParser.Package pkg = mPackages.get(packageName);
4690 if (pkg != null) {
4691 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4692 // Check for updated system application.
4693 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4694 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004695 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004696 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4697 }
4698 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4699 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004700 if (onSd) {
4701 // Install flag overrides everything.
4702 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4703 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004704 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004705 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4706 // Application explicitly specified internal.
4707 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4708 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4709 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004710 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004711 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004712 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004713 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4714 }
4715 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004716 }
4717 }
4718 } else {
4719 // Invalid install. Return error code
4720 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4721 }
4722 }
4723 }
4724 // All the special cases have been taken care of.
4725 // Return result based on recommended install location.
4726 if (onSd) {
4727 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4728 }
4729 return pkgLite.recommendedInstallLocation;
4730 }
4731
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004732 /*
4733 * Invoke remote method to get package information and install
4734 * location values. Override install location based on default
4735 * policy if needed and then create install arguments based
4736 * on the install location.
4737 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004738 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004739 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004740 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4741 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004742 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4743 if (onInt && onSd) {
4744 // Check if both bits are set.
4745 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4746 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4747 } else if (fwdLocked && onSd) {
4748 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004749 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004750 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004751 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004752 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004753 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004754 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004755 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4756 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4757 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4758 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4759 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004760 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4761 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4762 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004763 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4764 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004765 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004766 // Override with defaults if needed.
4767 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004768 if (!onSd && !onInt) {
4769 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004770 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4771 // Set the flag to install on external media.
4772 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004773 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004774 } else {
4775 // Make sure the flag for installing on external
4776 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004777 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004778 flags &= ~PackageManager.INSTALL_EXTERNAL;
4779 }
4780 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004781 }
4782 }
4783 // Create the file args now.
4784 mArgs = createInstallArgs(this);
4785 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4786 // Create copy only if we are not in an erroneous state.
4787 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004788 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004789 }
4790 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004791 }
4792
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004793 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004794 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004795 // If mArgs is null, then MCS couldn't be reached. When it
4796 // reconnects, it will try again to install. At that point, this
4797 // will succeed.
4798 if (mArgs != null) {
4799 processPendingInstall(mArgs, mRet);
4800 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004801 }
4802
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004803 @Override
4804 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004805 mArgs = createInstallArgs(this);
4806 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004807 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004808 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004809
4810 /*
4811 * Utility class used in movePackage api.
4812 * srcArgs and targetArgs are not set for invalid flags and make
4813 * sure to do null checks when invoking methods on them.
4814 * We probably want to return ErrorPrams for both failed installs
4815 * and moves.
4816 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004817 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004818 final IPackageMoveObserver observer;
4819 final int flags;
4820 final String packageName;
4821 final InstallArgs srcArgs;
4822 final InstallArgs targetArgs;
4823 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004824
4825 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4826 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004827 this.srcArgs = srcArgs;
4828 this.observer = observer;
4829 this.flags = flags;
4830 this.packageName = packageName;
4831 if (srcArgs != null) {
4832 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004833 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004834 } else {
4835 targetArgs = null;
4836 }
4837 }
4838
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004839 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004840 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4841 // Check for storage space on target medium
4842 if (!targetArgs.checkFreeStorage(mContainerService)) {
4843 Log.w(TAG, "Insufficient storage to install");
4844 return;
4845 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004846 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004847 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004848 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004849 if (DEBUG_SD_INSTALL) {
4850 StringBuilder builder = new StringBuilder();
4851 if (srcArgs != null) {
4852 builder.append("src: ");
4853 builder.append(srcArgs.getCodePath());
4854 }
4855 if (targetArgs != null) {
4856 builder.append(" target : ");
4857 builder.append(targetArgs.getCodePath());
4858 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004859 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004860 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004861 }
4862
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004863 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004864 void handleReturnCode() {
4865 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004866 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4867 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4868 currentStatus = PackageManager.MOVE_SUCCEEDED;
4869 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4870 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4871 }
4872 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004873 }
4874
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004875 @Override
4876 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004877 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004878 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004879 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004880
4881 private InstallArgs createInstallArgs(InstallParams params) {
4882 if (installOnSd(params.flags)) {
4883 return new SdInstallArgs(params);
4884 } else {
4885 return new FileInstallArgs(params);
4886 }
4887 }
4888
Kenny Root85387d72010-08-26 10:13:11 -07004889 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4890 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004891 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004892 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004893 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004894 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004895 }
4896 }
4897
Kenny Root85387d72010-08-26 10:13:11 -07004898 // Used by package mover
4899 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004900 if (installOnSd(flags)) {
4901 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4902 return new SdInstallArgs(packageURI, cid);
4903 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004904 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004905 }
4906 }
4907
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004908 static abstract class InstallArgs {
4909 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004910 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004911 final int flags;
4912 final Uri packageURI;
4913 final String installerPackageName;
4914
4915 InstallArgs(Uri packageURI,
4916 IPackageInstallObserver observer, int flags,
4917 String installerPackageName) {
4918 this.packageURI = packageURI;
4919 this.flags = flags;
4920 this.observer = observer;
4921 this.installerPackageName = installerPackageName;
4922 }
4923
4924 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004925 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004926 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004927 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004928 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004929 abstract String getCodePath();
4930 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004931 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004932 // Need installer lock especially for dex file removal.
4933 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004934 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004935 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004936 }
4937
4938 class FileInstallArgs extends InstallArgs {
4939 File installDir;
4940 String codeFileName;
4941 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004942 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004943 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004944
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004945 FileInstallArgs(InstallParams params) {
4946 super(params.packageURI, params.observer,
4947 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004948 }
4949
Kenny Root85387d72010-08-26 10:13:11 -07004950 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004951 super(null, null, 0, null);
4952 File codeFile = new File(fullCodePath);
4953 installDir = codeFile.getParentFile();
4954 codeFileName = fullCodePath;
4955 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004956 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004957 }
4958
Kenny Root85387d72010-08-26 10:13:11 -07004959 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004960 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004961 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004962 String apkName = getNextCodePath(null, pkgName, ".apk");
4963 codeFileName = new File(installDir, apkName + ".apk").getPath();
4964 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004965 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004966 }
4967
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004968 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4969 return imcs.checkFreeStorage(false, packageURI);
4970 }
4971
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004972 String getCodePath() {
4973 return codeFileName;
4974 }
4975
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004976 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004977 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004978 codeFileName = createTempPackageFile(installDir).getPath();
4979 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004980 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004981 }
4982
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004983 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004984 if (temp) {
4985 // Generate temp file name
4986 createCopyFile();
4987 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004988 // Get a ParcelFileDescriptor to write to the output file
4989 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 if (!created) {
4991 try {
4992 codeFile.createNewFile();
4993 // Set permissions
4994 if (!setPermissions()) {
4995 // Failed setting permissions.
4996 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4997 }
4998 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004999 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005000 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5001 }
5002 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005003 ParcelFileDescriptor out = null;
5004 try {
Kenny Root85387d72010-08-26 10:13:11 -07005005 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005006 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005007 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005008 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5009 }
5010 // Copy the resource now
5011 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5012 try {
5013 if (imcs.copyResource(packageURI, out)) {
5014 ret = PackageManager.INSTALL_SUCCEEDED;
5015 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005016 } finally {
5017 try { if (out != null) out.close(); } catch (IOException e) {}
5018 }
Kenny Root85387d72010-08-26 10:13:11 -07005019
5020 if (!temp) {
5021 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5022 }
5023
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005024 return ret;
5025 }
5026
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005027 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005028 if (status != PackageManager.INSTALL_SUCCEEDED) {
5029 cleanUp();
5030 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005031 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005032 }
5033
5034 boolean doRename(int status, final String pkgName, String oldCodePath) {
5035 if (status != PackageManager.INSTALL_SUCCEEDED) {
5036 cleanUp();
5037 return false;
5038 } else {
5039 // Rename based on packageName
5040 File codeFile = new File(getCodePath());
5041 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5042 File desFile = new File(installDir, apkName + ".apk");
5043 if (!codeFile.renameTo(desFile)) {
5044 return false;
5045 }
5046 // Reset paths since the file has been renamed.
5047 codeFileName = desFile.getPath();
5048 resourceFileName = getResourcePathFromCodePath();
5049 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005050 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005051 // Failed setting permissions.
5052 return false;
5053 }
5054 return true;
5055 }
5056 }
5057
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005058 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005059 if (status != PackageManager.INSTALL_SUCCEEDED) {
5060 cleanUp();
5061 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005062 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 }
5064
5065 String getResourcePath() {
5066 return resourceFileName;
5067 }
5068
5069 String getResourcePathFromCodePath() {
5070 String codePath = getCodePath();
5071 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5072 String apkNameOnly = getApkName(codePath);
5073 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5074 } else {
5075 return codePath;
5076 }
5077 }
5078
Kenny Root85387d72010-08-26 10:13:11 -07005079 @Override
5080 String getNativeLibraryPath() {
5081 return libraryPath;
5082 }
5083
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005084 private boolean cleanUp() {
5085 boolean ret = true;
5086 String sourceDir = getCodePath();
5087 String publicSourceDir = getResourcePath();
5088 if (sourceDir != null) {
5089 File sourceFile = new File(sourceDir);
5090 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005091 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005092 ret = false;
5093 }
5094 // Delete application's code and resources
5095 sourceFile.delete();
5096 }
5097 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5098 final File publicSourceFile = new File(publicSourceDir);
5099 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005100 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005101 }
5102 if (publicSourceFile.exists()) {
5103 publicSourceFile.delete();
5104 }
5105 }
5106 return ret;
5107 }
5108
5109 void cleanUpResourcesLI() {
5110 String sourceDir = getCodePath();
5111 if (cleanUp() && mInstaller != null) {
5112 int retCode = mInstaller.rmdex(sourceDir);
5113 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005114 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005115 + " at location "
5116 + sourceDir + ", retcode=" + retCode);
5117 // we don't consider this to be a failure of the core package deletion
5118 }
5119 }
Kenny Root85387d72010-08-26 10:13:11 -07005120 if (libraryPath != null) {
Kenny Root8f7cc022010-09-12 09:04:56 -07005121 NativeLibraryHelper.removeNativeBinariesLI(libraryPath);
Kenny Root85387d72010-08-26 10:13:11 -07005122 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005123 }
5124
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005125 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005126 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005127 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005128 final int filePermissions =
5129 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5130 |FileUtils.S_IROTH;
5131 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5132 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005133 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005134 getCodePath()
5135 + ". The return code was: " + retCode);
5136 // TODO Define new internal error
5137 return false;
5138 }
5139 return true;
5140 }
5141 return true;
5142 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005143
5144 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005145 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005146 cleanUpResourcesLI();
5147 return true;
5148 }
Kenny Root85387d72010-08-26 10:13:11 -07005149
5150 private boolean isFwdLocked() {
5151 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5152 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005153 }
5154
5155 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005156 static final String RES_FILE_NAME = "pkg.apk";
5157
Kenny Root85387d72010-08-26 10:13:11 -07005158 String cid;
5159 String packagePath;
5160 String libraryPath;
5161
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005162 SdInstallArgs(InstallParams params) {
5163 super(params.packageURI, params.observer,
5164 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005165 }
5166
Kenny Root85387d72010-08-26 10:13:11 -07005167 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005168 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005169 // Extract cid from fullCodePath
5170 int eidx = fullCodePath.lastIndexOf("/");
5171 String subStr1 = fullCodePath.substring(0, eidx);
5172 int sidx = subStr1.lastIndexOf("/");
5173 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005174 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005175 }
5176
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005177 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005178 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5179 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005180 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005181 }
5182
5183 SdInstallArgs(Uri packageURI, String cid) {
5184 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005185 this.cid = cid;
5186 }
5187
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005188 void createCopyFile() {
5189 cid = getTempContainerId();
5190 }
5191
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005192 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5193 return imcs.checkFreeStorage(true, packageURI);
5194 }
5195
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005196 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005197 if (temp) {
5198 createCopyFile();
5199 }
Kenny Root85387d72010-08-26 10:13:11 -07005200 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005201 packageURI, cid,
5202 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005203 if (newCachePath != null) {
5204 setCachePath(newCachePath);
5205 return PackageManager.INSTALL_SUCCEEDED;
5206 } else {
5207 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5208 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005209 }
5210
5211 @Override
5212 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005213 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005214 }
5215
5216 @Override
5217 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005218 return packagePath;
5219 }
5220
5221 @Override
5222 String getNativeLibraryPath() {
5223 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005224 }
5225
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005226 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005227 if (status != PackageManager.INSTALL_SUCCEEDED) {
5228 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005229 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005230 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005231 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005232 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005233 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5234 Process.SYSTEM_UID);
5235 if (newCachePath != null) {
5236 setCachePath(newCachePath);
5237 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005238 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5239 }
5240 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005242 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005243 }
5244
5245 boolean doRename(int status, final String pkgName,
5246 String oldCodePath) {
5247 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005248 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005249 if (PackageHelper.isContainerMounted(cid)) {
5250 // Unmount the container
5251 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005252 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005253 return false;
5254 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005255 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005256 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005257 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5258 " which might be stale. Will try to clean up.");
5259 // Clean up the stale container and proceed to recreate.
5260 if (!PackageHelper.destroySdDir(newCacheId)) {
5261 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5262 return false;
5263 }
5264 // Successfully cleaned up stale container. Try to rename again.
5265 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5266 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5267 + " inspite of cleaning it up.");
5268 return false;
5269 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005270 }
5271 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005272 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005273 newCachePath = PackageHelper.mountSdDir(newCacheId,
5274 getEncryptKey(), Process.SYSTEM_UID);
5275 } else {
5276 newCachePath = PackageHelper.getSdDir(newCacheId);
5277 }
5278 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005279 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005280 return false;
5281 }
5282 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005283 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005284 " at new path: " + newCachePath);
5285 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005286 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005287 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005288 }
5289
Kenny Root85387d72010-08-26 10:13:11 -07005290 private void setCachePath(String newCachePath) {
5291 File cachePath = new File(newCachePath);
5292 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5293 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5294 }
5295
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005296 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005297 if (status != PackageManager.INSTALL_SUCCEEDED) {
5298 cleanUp();
5299 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005300 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005301 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005302 PackageHelper.mountSdDir(cid,
5303 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005304 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005305 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005306 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005307 }
5308
5309 private void cleanUp() {
5310 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005311 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005312 }
5313
5314 void cleanUpResourcesLI() {
5315 String sourceFile = getCodePath();
5316 // Remove dex file
5317 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005318 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005319 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005320 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005321 + " at location "
5322 + sourceFile.toString() + ", retcode=" + retCode);
5323 // we don't consider this to be a failure of the core package deletion
5324 }
5325 }
5326 cleanUp();
5327 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005328
5329 boolean matchContainer(String app) {
5330 if (cid.startsWith(app)) {
5331 return true;
5332 }
5333 return false;
5334 }
5335
5336 String getPackageName() {
5337 int idx = cid.lastIndexOf("-");
5338 if (idx == -1) {
5339 return cid;
5340 }
5341 return cid.substring(0, idx);
5342 }
5343
5344 boolean doPostDeleteLI(boolean delete) {
5345 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005346 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005347 if (mounted) {
5348 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005349 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005350 }
5351 if (ret && delete) {
5352 cleanUpResourcesLI();
5353 }
5354 return ret;
5355 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005356 };
5357
5358 // Utility method used to create code paths based on package name and available index.
5359 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5360 String idxStr = "";
5361 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005362 // Fall back to default value of idx=1 if prefix is not
5363 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005364 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005365 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005366 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005367 if (subStr.endsWith(suffix)) {
5368 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005369 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005370 // If oldCodePath already contains prefix find out the
5371 // ending index to either increment or decrement.
5372 int sidx = subStr.lastIndexOf(prefix);
5373 if (sidx != -1) {
5374 subStr = subStr.substring(sidx + prefix.length());
5375 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005376 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5377 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005378 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005379 try {
5380 idx = Integer.parseInt(subStr);
5381 if (idx <= 1) {
5382 idx++;
5383 } else {
5384 idx--;
5385 }
5386 } catch(NumberFormatException e) {
5387 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005388 }
5389 }
5390 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005391 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005392 return prefix + idxStr;
5393 }
5394
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005395 // Utility method used to ignore ADD/REMOVE events
5396 // by directory observer.
5397 private static boolean ignoreCodePath(String fullPathStr) {
5398 String apkName = getApkName(fullPathStr);
5399 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5400 if (idx != -1 && ((idx+1) < apkName.length())) {
5401 // Make sure the package ends with a numeral
5402 String version = apkName.substring(idx+1);
5403 try {
5404 Integer.parseInt(version);
5405 return true;
5406 } catch (NumberFormatException e) {}
5407 }
5408 return false;
5409 }
5410
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005411 // Utility method that returns the relative package path with respect
5412 // to the installation directory. Like say for /data/data/com.test-1.apk
5413 // string com.test-1 is returned.
5414 static String getApkName(String codePath) {
5415 if (codePath == null) {
5416 return null;
5417 }
5418 int sidx = codePath.lastIndexOf("/");
5419 int eidx = codePath.lastIndexOf(".");
5420 if (eidx == -1) {
5421 eidx = codePath.length();
5422 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005423 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005424 return null;
5425 }
5426 return codePath.substring(sidx+1, eidx);
5427 }
5428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 class PackageInstalledInfo {
5430 String name;
5431 int uid;
5432 PackageParser.Package pkg;
5433 int returnCode;
5434 PackageRemovedInfo removedInfo;
5435 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005437 /*
5438 * Install a non-existing package.
5439 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005440 private void installNewPackageLI(PackageParser.Package pkg,
5441 int parseFlags,
5442 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005443 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005445 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005446
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005447 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005448 res.name = pkgName;
5449 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005450 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5451 // A package with the same name is already installed, though
5452 // it has been renamed to an older name. The package we
5453 // are trying to install should be installed as an update to
5454 // the existing one, but that has not been requested, so bail.
5455 Slog.w(TAG, "Attempt to re-install " + pkgName
5456 + " without first uninstalling package running as "
5457 + mSettings.mRenamedPackages.get(pkgName));
5458 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5459 return;
5460 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005461 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005463 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 + " without first uninstalling.");
5465 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5466 return;
5467 }
5468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005470 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005471 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005472 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005473 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5474 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5475 }
5476 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005477 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005478 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 res);
5480 // delete the partially installed application. the data directory will have to be
5481 // restored if it was already existing
5482 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5483 // remove package from internal structures. Note that we want deletePackageX to
5484 // delete the package data and cache directories that it created in
5485 // scanPackageLocked, unless those directories existed before we even tried to
5486 // install.
5487 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005488 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5490 res.removedInfo);
5491 }
5492 }
5493 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005494
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005495 private void replacePackageLI(PackageParser.Package pkg,
5496 int parseFlags,
5497 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005498 String installerPackageName, PackageInstalledInfo res) {
5499
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005500 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005501 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502 // First find the old package info and check signatures
5503 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005504 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005505 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005506 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5508 return;
5509 }
5510 }
Kenny Root85387d72010-08-26 10:13:11 -07005511 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005512 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005513 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005515 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 }
5517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005520 PackageParser.Package pkg,
5521 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005522 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 PackageParser.Package newPackage = null;
5524 String pkgName = deletedPackage.packageName;
5525 boolean deletedPkg = true;
5526 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005527
Jacek Surazski65e13172009-04-28 15:26:38 +02005528 String oldInstallerPackageName = null;
5529 synchronized (mPackages) {
5530 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5531 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005534 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 res.removedInfo)) {
5536 // If the existing package was'nt successfully deleted
5537 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5538 deletedPkg = false;
5539 } else {
5540 // Successfully deleted the old package. Now proceed with re-installation
5541 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005542 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005544 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5546 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005547 }
5548 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005549 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005550 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 res);
5552 updatedSettings = true;
5553 }
5554 }
5555
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005556 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 // remove package from internal structures. Note that we want deletePackageX to
5558 // delete the package data and cache directories that it created in
5559 // scanPackageLocked, unless those directories existed before we even tried to
5560 // install.
5561 if(updatedSettings) {
5562 deletePackageLI(
5563 pkgName, true,
5564 PackageManager.DONT_DELETE_DATA,
5565 res.removedInfo);
5566 }
5567 // Since we failed to install the new package we need to restore the old
5568 // package that we deleted.
5569 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005570 File restoreFile = new File(deletedPackage.mPath);
5571 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005572 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005573 return;
5574 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005575 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005576 boolean oldOnSd = isExternal(deletedPackage);
5577 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5578 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5579 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5580 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5581 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5582 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5583 return;
5584 }
5585 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005586 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005587 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005588 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005589 mSettings.writeLP();
5590 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005591 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005592 }
5593 }
5594 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005597 PackageParser.Package pkg,
5598 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005599 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005600 PackageParser.Package newPackage = null;
5601 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005602 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 PackageParser.PARSE_IS_SYSTEM;
5604 String packageName = deletedPackage.packageName;
5605 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5606 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005607 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005608 return;
5609 }
5610 PackageParser.Package oldPkg;
5611 PackageSetting oldPkgSetting;
5612 synchronized (mPackages) {
5613 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005614 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005615 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5616 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005617 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 return;
5619 }
5620 }
5621 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5622 res.removedInfo.removedPackage = packageName;
5623 // Remove existing system package
5624 removePackageLI(oldPkg, true);
5625 synchronized (mPackages) {
5626 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5627 }
5628
5629 // Successfully disabled the old package. Now proceed with re-installation
5630 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5631 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005632 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005633 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005634 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005635 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5636 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5637 }
5638 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005639 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 updatedSettings = true;
5641 }
5642
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005643 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 // Re installation failed. Restore old information
5645 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005646 if (newPackage != null) {
5647 removePackageLI(newPackage, true);
5648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005650 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005652 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 // Restore the old system information in Settings
5654 synchronized(mPackages) {
5655 if(updatedSettings) {
5656 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005657 mSettings.setInstallerPackageName(packageName,
5658 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 }
5660 mSettings.writeLP();
5661 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005662 } else {
5663 // If this is an update to an existing update, setup
5664 // to remove the existing update.
5665 synchronized (mPackages) {
5666 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5667 if (ps != null && ps.codePathString != null &&
5668 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5669 int installFlags = 0;
5670 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005671 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005672 }
5673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 }
5675 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005676
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005677 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005678 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005679 int retCode;
5680 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5681 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5682 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005683 if (mNoDexOpt) {
5684 /*
5685 * If we're in an engineering build, programs are lazily run
5686 * through dexopt. If the .dex file doesn't exist yet, it
5687 * will be created when the program is run next.
5688 */
5689 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5690 } else {
5691 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5692 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5693 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005694 }
5695 }
5696 return PackageManager.INSTALL_SUCCEEDED;
5697 }
5698
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005699 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005700 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005701 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 synchronized (mPackages) {
5703 //write settings. the installStatus will be incomplete at this stage.
5704 //note that the new package setting would have already been
5705 //added to mPackages. It hasn't been persisted yet.
5706 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5707 mSettings.writeLP();
5708 }
5709
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005710 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005711 != PackageManager.INSTALL_SUCCEEDED) {
5712 // Discontinue if moving dex files failed.
5713 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005714 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005715 if((res.returnCode = setPermissionsLI(newPackage))
5716 != PackageManager.INSTALL_SUCCEEDED) {
5717 if (mInstaller != null) {
5718 mInstaller.rmdex(newPackage.mScanPath);
5719 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005720 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005722 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005725 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005726 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 res.name = pkgName;
5728 res.uid = newPackage.applicationInfo.uid;
5729 res.pkg = newPackage;
5730 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005731 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5733 //to update install status
5734 mSettings.writeLP();
5735 }
5736 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005737
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005738 private void installPackageLI(InstallArgs args,
5739 boolean newInstall, PackageInstalledInfo res) {
5740 int pFlags = args.flags;
5741 String installerPackageName = args.installerPackageName;
5742 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005743 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005744 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005745 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005746 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005747 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005748 // Result object to be returned
5749 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5750
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005751 // Retrieve PackageSettings and parse package
5752 int parseFlags = PackageParser.PARSE_CHATTY |
5753 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5754 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5755 parseFlags |= mDefParseFlags;
5756 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5757 pp.setSeparateProcesses(mSeparateProcesses);
5758 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5759 null, mMetrics, parseFlags);
5760 if (pkg == null) {
5761 res.returnCode = pp.getParseError();
5762 return;
5763 }
5764 String pkgName = res.name = pkg.packageName;
5765 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5766 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5767 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5768 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005769 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005770 }
5771 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5772 res.returnCode = pp.getParseError();
5773 return;
5774 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005775 // Get rid of all references to package scan path via parser.
5776 pp = null;
5777 String oldCodePath = null;
5778 boolean systemApp = false;
5779 synchronized (mPackages) {
5780 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005781 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5782 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005783 if (pkg.mOriginalPackages != null
5784 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005785 && mPackages.containsKey(oldName)) {
5786 // This package is derived from an original package,
5787 // and this device has been updating from that original
5788 // name. We must continue using the original name, so
5789 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005790 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005791 pkgName = pkg.packageName;
5792 replace = true;
5793 } else if (mPackages.containsKey(pkgName)) {
5794 // This package, under its official name, already exists
5795 // on the device; we should replace it.
5796 replace = true;
5797 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005798 }
5799 PackageSetting ps = mSettings.mPackages.get(pkgName);
5800 if (ps != null) {
5801 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5802 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5803 systemApp = (ps.pkg.applicationInfo.flags &
5804 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005805 }
5806 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005808
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005809 if (systemApp && onSd) {
5810 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005811 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005812 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5813 return;
5814 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005815
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005816 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5817 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5818 return;
5819 }
5820 // Set application objects path explicitly after the rename
5821 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005822 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005823 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005824 replacePackageLI(pkg, parseFlags, scanMode,
5825 installerPackageName, res);
5826 } else {
5827 installNewPackageLI(pkg, parseFlags, scanMode,
5828 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005829 }
5830 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005831
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005832 private int setPermissionsLI(PackageParser.Package newPackage) {
5833 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005834 int retCode = 0;
5835 // TODO Gross hack but fix later. Ideally move this to be a post installation
5836 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005837 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005838 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 try {
5840 extractPublicFiles(newPackage, destResourceFile);
5841 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005842 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 -08005843 " forward-locked app.");
5844 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5845 } finally {
5846 //TODO clean up the extracted public files
5847 }
5848 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005849 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005850 newPackage.applicationInfo.uid);
5851 } else {
5852 final int filePermissions =
5853 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005854 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 newPackage.applicationInfo.uid);
5856 }
5857 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005858 // The permissions on the resource file was set when it was copied for
5859 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005863 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005864 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005865 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005866 // TODO Define new internal error
5867 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 }
5869 return PackageManager.INSTALL_SUCCEEDED;
5870 }
5871
Kenny Root85387d72010-08-26 10:13:11 -07005872 private static boolean isForwardLocked(PackageParser.Package pkg) {
5873 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 }
5875
Kenny Root85387d72010-08-26 10:13:11 -07005876 private static boolean isExternal(PackageParser.Package pkg) {
5877 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5878 }
5879
5880 private static boolean isSystemApp(PackageParser.Package pkg) {
5881 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5882 }
5883
5884 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5885 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005886 }
5887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 private void extractPublicFiles(PackageParser.Package newPackage,
5889 File publicZipFile) throws IOException {
5890 final ZipOutputStream publicZipOutStream =
5891 new ZipOutputStream(new FileOutputStream(publicZipFile));
5892 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5893
5894 // Copy manifest, resources.arsc and res directory to public zip
5895
5896 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5897 while (privateZipEntries.hasMoreElements()) {
5898 final ZipEntry zipEntry = privateZipEntries.nextElement();
5899 final String zipEntryName = zipEntry.getName();
5900 if ("AndroidManifest.xml".equals(zipEntryName)
5901 || "resources.arsc".equals(zipEntryName)
5902 || zipEntryName.startsWith("res/")) {
5903 try {
5904 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5905 } catch (IOException e) {
5906 try {
5907 publicZipOutStream.close();
5908 throw e;
5909 } finally {
5910 publicZipFile.delete();
5911 }
5912 }
5913 }
5914 }
5915
5916 publicZipOutStream.close();
5917 FileUtils.setPermissions(
5918 publicZipFile.getAbsolutePath(),
5919 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5920 -1, -1);
5921 }
5922
5923 private static void copyZipEntry(ZipEntry zipEntry,
5924 ZipFile inZipFile,
5925 ZipOutputStream outZipStream) throws IOException {
5926 byte[] buffer = new byte[4096];
5927 int num;
5928
5929 ZipEntry newEntry;
5930 if (zipEntry.getMethod() == ZipEntry.STORED) {
5931 // Preserve the STORED method of the input entry.
5932 newEntry = new ZipEntry(zipEntry);
5933 } else {
5934 // Create a new entry so that the compressed len is recomputed.
5935 newEntry = new ZipEntry(zipEntry.getName());
5936 }
5937 outZipStream.putNextEntry(newEntry);
5938
5939 InputStream data = inZipFile.getInputStream(zipEntry);
5940 while ((num = data.read(buffer)) > 0) {
5941 outZipStream.write(buffer, 0, num);
5942 }
5943 outZipStream.flush();
5944 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 private void deleteTempPackageFiles() {
5947 FilenameFilter filter = new FilenameFilter() {
5948 public boolean accept(File dir, String name) {
5949 return name.startsWith("vmdl") && name.endsWith(".tmp");
5950 }
5951 };
5952 String tmpFilesList[] = mAppInstallDir.list(filter);
5953 if(tmpFilesList == null) {
5954 return;
5955 }
5956 for(int i = 0; i < tmpFilesList.length; i++) {
5957 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5958 tmpFile.delete();
5959 }
5960 }
5961
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005962 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005963 File tmpPackageFile;
5964 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005965 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005966 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005967 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005968 return null;
5969 }
5970 try {
5971 FileUtils.setPermissions(
5972 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5973 -1, -1);
5974 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005975 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 return null;
5977 }
5978 return tmpPackageFile;
5979 }
5980
5981 public void deletePackage(final String packageName,
5982 final IPackageDeleteObserver observer,
5983 final int flags) {
5984 mContext.enforceCallingOrSelfPermission(
5985 android.Manifest.permission.DELETE_PACKAGES, null);
5986 // Queue up an async operation since the package deletion may take a little while.
5987 mHandler.post(new Runnable() {
5988 public void run() {
5989 mHandler.removeCallbacks(this);
5990 final boolean succeded = deletePackageX(packageName, true, true, flags);
5991 if (observer != null) {
5992 try {
5993 observer.packageDeleted(succeded);
5994 } catch (RemoteException e) {
5995 Log.i(TAG, "Observer no longer exists.");
5996 } //end catch
5997 } //end if
5998 } //end run
5999 });
6000 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 /**
6003 * This method is an internal method that could be get invoked either
6004 * to delete an installed package or to clean up a failed installation.
6005 * After deleting an installed package, a broadcast is sent to notify any
6006 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006007 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 * installation wouldn't have sent the initial broadcast either
6009 * The key steps in deleting a package are
6010 * deleting the package information in internal structures like mPackages,
6011 * deleting the packages base directories through installd
6012 * updating mSettings to reflect current status
6013 * persisting settings for later use
6014 * sending a broadcast if necessary
6015 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006016 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6017 boolean deleteCodeAndResources, int flags) {
6018 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006019 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006020
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006021 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6022 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6023 try {
6024 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006025 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006026 return false;
6027 }
6028 } catch (RemoteException e) {
6029 }
6030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006032 res = deletePackageLI(packageName, deleteCodeAndResources,
6033 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006034 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006037 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006038 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006039
6040 // If the removed package was a system update, the old system packaged
6041 // was re-enabled; we need to broadcast this information
6042 if (systemUpdate) {
6043 Bundle extras = new Bundle(1);
6044 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6045 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6046
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006047 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6048 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006050 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006051 // Force a gc here.
6052 Runtime.getRuntime().gc();
6053 // Delete the resources here after sending the broadcast to let
6054 // other processes clean up before deleting resources.
6055 if (info.args != null) {
6056 synchronized (mInstallLock) {
6057 info.args.doPostDeleteLI(deleteCodeAndResources);
6058 }
6059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 return res;
6061 }
6062
6063 static class PackageRemovedInfo {
6064 String removedPackage;
6065 int uid = -1;
6066 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006067 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006068 // Clean up resources deleted packages.
6069 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006070
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006071 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006072 Bundle extras = new Bundle(1);
6073 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6074 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6075 if (replacing) {
6076 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6077 }
6078 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006079 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006080 }
6081 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006082 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 }
6084 }
6085 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006087 /*
6088 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6089 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006090 * 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 -08006091 * delete a partially installed application.
6092 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006093 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 int flags) {
6095 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006096 if (outInfo != null) {
6097 outInfo.removedPackage = packageName;
6098 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006099 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 // Retrieve object to delete permissions for shared user later on
6101 PackageSetting deletedPs;
6102 synchronized (mPackages) {
6103 deletedPs = mSettings.mPackages.get(packageName);
6104 }
6105 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006106 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006107 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006108 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006109 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006110 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 + packageName + ", retcode=" + retCode);
6112 // we don't consider this to be a failure of the core package deletion
6113 }
6114 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006115 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 PackageParser.Package pkg = mPackages.get(packageName);
6117 File dataDir = new File(pkg.applicationInfo.dataDir);
6118 dataDir.delete();
6119 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006120 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 }
6122 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006123 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006124 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6125 if (outInfo != null) {
6126 outInfo.removedUid = mSettings.removePackageLP(packageName);
6127 }
6128 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006129 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006130 if (deletedPs.sharedUser != null) {
6131 // remove permissions associated with package
6132 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6133 }
6134 }
6135 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006136 // remove from preferred activities.
6137 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6138 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6139 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6140 removed.add(pa);
6141 }
6142 }
6143 for (PreferredActivity pa : removed) {
6144 mSettings.mPreferredActivities.removeFilter(pa);
6145 }
6146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006147 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006148 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 }
6150 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006152 /*
6153 * Tries to delete system package.
6154 */
6155 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006156 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 ApplicationInfo applicationInfo = p.applicationInfo;
6158 //applicable for non-partially installed applications only
6159 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006160 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 return false;
6162 }
6163 PackageSetting ps = null;
6164 // Confirm if the system package has been updated
6165 // An updated system app can be deleted. This will also have to restore
6166 // the system pkg from system partition
6167 synchronized (mPackages) {
6168 ps = mSettings.getDisabledSystemPkg(p.packageName);
6169 }
6170 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006171 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 return false;
6173 } else {
6174 Log.i(TAG, "Deleting system pkg from data partition");
6175 }
6176 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006177 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006178 final boolean deleteCodeAndResources;
6179 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006180 // Delete code and resources for downgrades
6181 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006182 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006183 } else {
6184 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006185 deleteCodeAndResources = false;
6186 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6189 if (!ret) {
6190 return false;
6191 }
6192 synchronized (mPackages) {
6193 // Reinstate the old system package
6194 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006195 // Remove any native libraries from the upgraded package.
6196 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 }
6198 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006199 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006201 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006204 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006205 return false;
6206 }
6207 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006208 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 mSettings.writeLP();
6210 }
6211 return true;
6212 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6215 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6216 ApplicationInfo applicationInfo = p.applicationInfo;
6217 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006218 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 return false;
6220 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006221 if (outInfo != null) {
6222 outInfo.uid = applicationInfo.uid;
6223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224
6225 // Delete package data from internal structures and also remove data if flag is set
6226 removePackageDataLI(p, outInfo, flags);
6227
6228 // Delete application code and resources
6229 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006230 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006231 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6232 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6233 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6234 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 }
6236 return true;
6237 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 /*
6240 * This method handles package deletion in general
6241 */
6242 private boolean deletePackageLI(String packageName,
6243 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6244 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006245 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 return false;
6247 }
6248 PackageParser.Package p;
6249 boolean dataOnly = false;
6250 synchronized (mPackages) {
6251 p = mPackages.get(packageName);
6252 if (p == null) {
6253 //this retrieves partially installed apps
6254 dataOnly = true;
6255 PackageSetting ps = mSettings.mPackages.get(packageName);
6256 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006257 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 return false;
6259 }
6260 p = ps.pkg;
6261 }
6262 }
6263 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006264 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 return false;
6266 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 if (dataOnly) {
6269 // Delete application data first
6270 removePackageDataLI(p, outInfo, flags);
6271 return true;
6272 }
6273 // At this point the package should have ApplicationInfo associated with it
6274 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006275 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 return false;
6277 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006278 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006279 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 Log.i(TAG, "Removing system package:"+p.packageName);
6281 // When an updated system application is deleted we delete the existing resources as well and
6282 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006283 ret = deleteSystemPackageLI(p, flags, outInfo);
6284 } else {
6285 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006286 // Kill application pre-emptively especially for apps on sd.
6287 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006288 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006290 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293 public void clearApplicationUserData(final String packageName,
6294 final IPackageDataObserver observer) {
6295 mContext.enforceCallingOrSelfPermission(
6296 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6297 // Queue up an async operation since the package deletion may take a little while.
6298 mHandler.post(new Runnable() {
6299 public void run() {
6300 mHandler.removeCallbacks(this);
6301 final boolean succeeded;
6302 synchronized (mInstallLock) {
6303 succeeded = clearApplicationUserDataLI(packageName);
6304 }
6305 if (succeeded) {
6306 // invoke DeviceStorageMonitor's update method to clear any notifications
6307 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6308 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6309 if (dsm != null) {
6310 dsm.updateMemory();
6311 }
6312 }
6313 if(observer != null) {
6314 try {
6315 observer.onRemoveCompleted(packageName, succeeded);
6316 } catch (RemoteException e) {
6317 Log.i(TAG, "Observer no longer exists.");
6318 }
6319 } //end if observer
6320 } //end run
6321 });
6322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 private boolean clearApplicationUserDataLI(String packageName) {
6325 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006326 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 return false;
6328 }
6329 PackageParser.Package p;
6330 boolean dataOnly = false;
6331 synchronized (mPackages) {
6332 p = mPackages.get(packageName);
6333 if(p == null) {
6334 dataOnly = true;
6335 PackageSetting ps = mSettings.mPackages.get(packageName);
6336 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006337 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 return false;
6339 }
6340 p = ps.pkg;
6341 }
6342 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006343 boolean useEncryptedFSDir = false;
6344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 if(!dataOnly) {
6346 //need to check this only for fully installed applications
6347 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006348 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 return false;
6350 }
6351 final ApplicationInfo applicationInfo = p.applicationInfo;
6352 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006353 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 return false;
6355 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006356 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 }
6358 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006359 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006361 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 + packageName);
6363 return false;
6364 }
6365 }
6366 return true;
6367 }
6368
6369 public void deleteApplicationCacheFiles(final String packageName,
6370 final IPackageDataObserver observer) {
6371 mContext.enforceCallingOrSelfPermission(
6372 android.Manifest.permission.DELETE_CACHE_FILES, null);
6373 // Queue up an async operation since the package deletion may take a little while.
6374 mHandler.post(new Runnable() {
6375 public void run() {
6376 mHandler.removeCallbacks(this);
6377 final boolean succeded;
6378 synchronized (mInstallLock) {
6379 succeded = deleteApplicationCacheFilesLI(packageName);
6380 }
6381 if(observer != null) {
6382 try {
6383 observer.onRemoveCompleted(packageName, succeded);
6384 } catch (RemoteException e) {
6385 Log.i(TAG, "Observer no longer exists.");
6386 }
6387 } //end if observer
6388 } //end run
6389 });
6390 }
6391
6392 private boolean deleteApplicationCacheFilesLI(String packageName) {
6393 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006394 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 return false;
6396 }
6397 PackageParser.Package p;
6398 synchronized (mPackages) {
6399 p = mPackages.get(packageName);
6400 }
6401 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006402 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 return false;
6404 }
6405 final ApplicationInfo applicationInfo = p.applicationInfo;
6406 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006407 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 return false;
6409 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006410 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006411 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006412 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006414 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006415 + packageName);
6416 return false;
6417 }
6418 }
6419 return true;
6420 }
6421
6422 public void getPackageSizeInfo(final String packageName,
6423 final IPackageStatsObserver observer) {
6424 mContext.enforceCallingOrSelfPermission(
6425 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6426 // Queue up an async operation since the package deletion may take a little while.
6427 mHandler.post(new Runnable() {
6428 public void run() {
6429 mHandler.removeCallbacks(this);
6430 PackageStats lStats = new PackageStats(packageName);
6431 final boolean succeded;
6432 synchronized (mInstallLock) {
6433 succeded = getPackageSizeInfoLI(packageName, lStats);
6434 }
6435 if(observer != null) {
6436 try {
6437 observer.onGetStatsCompleted(lStats, succeded);
6438 } catch (RemoteException e) {
6439 Log.i(TAG, "Observer no longer exists.");
6440 }
6441 } //end if observer
6442 } //end run
6443 });
6444 }
6445
6446 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6447 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006448 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 return false;
6450 }
6451 PackageParser.Package p;
6452 boolean dataOnly = false;
6453 synchronized (mPackages) {
6454 p = mPackages.get(packageName);
6455 if(p == null) {
6456 dataOnly = true;
6457 PackageSetting ps = mSettings.mPackages.get(packageName);
6458 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006459 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 return false;
6461 }
6462 p = ps.pkg;
6463 }
6464 }
6465 String publicSrcDir = null;
6466 if(!dataOnly) {
6467 final ApplicationInfo applicationInfo = p.applicationInfo;
6468 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006469 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 return false;
6471 }
6472 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6473 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006474 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 if (mInstaller != null) {
6476 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006477 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006478 if (res < 0) {
6479 return false;
6480 } else {
6481 return true;
6482 }
6483 }
6484 return true;
6485 }
6486
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006489 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 }
6491
6492 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006493 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 }
6495
6496 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006497 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 }
6499
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006500 int getUidTargetSdkVersionLockedLP(int uid) {
6501 Object obj = mSettings.getUserIdLP(uid);
6502 if (obj instanceof SharedUserSetting) {
6503 SharedUserSetting sus = (SharedUserSetting)obj;
6504 final int N = sus.packages.size();
6505 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6506 Iterator<PackageSetting> it = sus.packages.iterator();
6507 int i=0;
6508 while (it.hasNext()) {
6509 PackageSetting ps = it.next();
6510 if (ps.pkg != null) {
6511 int v = ps.pkg.applicationInfo.targetSdkVersion;
6512 if (v < vers) vers = v;
6513 }
6514 }
6515 return vers;
6516 } else if (obj instanceof PackageSetting) {
6517 PackageSetting ps = (PackageSetting)obj;
6518 if (ps.pkg != null) {
6519 return ps.pkg.applicationInfo.targetSdkVersion;
6520 }
6521 }
6522 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6523 }
6524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 public void addPreferredActivity(IntentFilter filter, int match,
6526 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006527 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006528 if (mContext.checkCallingOrSelfPermission(
6529 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6530 != PackageManager.PERMISSION_GRANTED) {
6531 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6532 < Build.VERSION_CODES.FROYO) {
6533 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6534 + Binder.getCallingUid());
6535 return;
6536 }
6537 mContext.enforceCallingOrSelfPermission(
6538 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6539 }
6540
6541 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006542 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6543 mSettings.mPreferredActivities.addFilter(
6544 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006545 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 }
6547 }
6548
Satish Sampath8dbe6122009-06-02 23:35:54 +01006549 public void replacePreferredActivity(IntentFilter filter, int match,
6550 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006551 if (filter.countActions() != 1) {
6552 throw new IllegalArgumentException(
6553 "replacePreferredActivity expects filter to have only 1 action.");
6554 }
6555 if (filter.countCategories() != 1) {
6556 throw new IllegalArgumentException(
6557 "replacePreferredActivity expects filter to have only 1 category.");
6558 }
6559 if (filter.countDataAuthorities() != 0
6560 || filter.countDataPaths() != 0
6561 || filter.countDataSchemes() != 0
6562 || filter.countDataTypes() != 0) {
6563 throw new IllegalArgumentException(
6564 "replacePreferredActivity expects filter to have no data authorities, " +
6565 "paths, schemes or types.");
6566 }
6567 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006568 if (mContext.checkCallingOrSelfPermission(
6569 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6570 != PackageManager.PERMISSION_GRANTED) {
6571 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6572 < Build.VERSION_CODES.FROYO) {
6573 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6574 + Binder.getCallingUid());
6575 return;
6576 }
6577 mContext.enforceCallingOrSelfPermission(
6578 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6579 }
6580
Satish Sampath8dbe6122009-06-02 23:35:54 +01006581 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6582 String action = filter.getAction(0);
6583 String category = filter.getCategory(0);
6584 while (it.hasNext()) {
6585 PreferredActivity pa = it.next();
6586 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6587 it.remove();
6588 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6589 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6590 }
6591 }
6592 addPreferredActivity(filter, match, set, activity);
6593 }
6594 }
6595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006597 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006598 int uid = Binder.getCallingUid();
6599 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006600 if (pkg == null || pkg.applicationInfo.uid != uid) {
6601 if (mContext.checkCallingOrSelfPermission(
6602 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6603 != PackageManager.PERMISSION_GRANTED) {
6604 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6605 < Build.VERSION_CODES.FROYO) {
6606 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6607 + Binder.getCallingUid());
6608 return;
6609 }
6610 mContext.enforceCallingOrSelfPermission(
6611 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6612 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006613 }
6614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006615 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006616 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 }
6618 }
6619 }
6620
6621 boolean clearPackagePreferredActivitiesLP(String packageName) {
6622 boolean changed = false;
6623 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6624 while (it.hasNext()) {
6625 PreferredActivity pa = it.next();
6626 if (pa.mActivity.getPackageName().equals(packageName)) {
6627 it.remove();
6628 changed = true;
6629 }
6630 }
6631 return changed;
6632 }
6633
6634 public int getPreferredActivities(List<IntentFilter> outFilters,
6635 List<ComponentName> outActivities, String packageName) {
6636
6637 int num = 0;
6638 synchronized (mPackages) {
6639 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6640 while (it.hasNext()) {
6641 PreferredActivity pa = it.next();
6642 if (packageName == null
6643 || pa.mActivity.getPackageName().equals(packageName)) {
6644 if (outFilters != null) {
6645 outFilters.add(new IntentFilter(pa));
6646 }
6647 if (outActivities != null) {
6648 outActivities.add(pa.mActivity);
6649 }
6650 }
6651 }
6652 }
6653
6654 return num;
6655 }
6656
6657 public void setApplicationEnabledSetting(String appPackageName,
6658 int newState, int flags) {
6659 setEnabledSetting(appPackageName, null, newState, flags);
6660 }
6661
6662 public void setComponentEnabledSetting(ComponentName componentName,
6663 int newState, int flags) {
6664 setEnabledSetting(componentName.getPackageName(),
6665 componentName.getClassName(), newState, flags);
6666 }
6667
6668 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006669 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006670 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6671 || newState == COMPONENT_ENABLED_STATE_ENABLED
6672 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6673 throw new IllegalArgumentException("Invalid new component state: "
6674 + newState);
6675 }
6676 PackageSetting pkgSetting;
6677 final int uid = Binder.getCallingUid();
6678 final int permission = mContext.checkCallingPermission(
6679 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6680 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006681 boolean sendNow = false;
6682 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006683 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006684 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006685 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006686 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006687 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006689 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006691 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 }
6693 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006694 "Unknown component: " + packageName
6695 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 }
6697 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6698 throw new SecurityException(
6699 "Permission Denial: attempt to change component state from pid="
6700 + Binder.getCallingPid()
6701 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6702 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006703 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006704 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006705 if (pkgSetting.enabled == newState) {
6706 // Nothing to do
6707 return;
6708 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006709 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006710 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 } else {
6712 // We're dealing with a component level state change
6713 switch (newState) {
6714 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006715 if (!pkgSetting.enableComponentLP(className)) {
6716 return;
6717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 break;
6719 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006720 if (!pkgSetting.disableComponentLP(className)) {
6721 return;
6722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006723 break;
6724 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006725 if (!pkgSetting.restoreComponentLP(className)) {
6726 return;
6727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 break;
6729 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006730 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006731 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 }
6733 }
6734 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006735 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006736 components = mPendingBroadcasts.get(packageName);
6737 boolean newPackage = components == null;
6738 if (newPackage) {
6739 components = new ArrayList<String>();
6740 }
6741 if (!components.contains(componentName)) {
6742 components.add(componentName);
6743 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006744 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6745 sendNow = true;
6746 // Purge entry from pending broadcast list if another one exists already
6747 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006748 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006749 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006750 if (newPackage) {
6751 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006752 }
6753 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6754 // Schedule a message
6755 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6756 }
6757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 long callingId = Binder.clearCallingIdentity();
6761 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006762 if (sendNow) {
6763 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006764 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 } finally {
6767 Binder.restoreCallingIdentity(callingId);
6768 }
6769 }
6770
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006771 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006772 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6773 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6774 + " components=" + componentNames);
6775 Bundle extras = new Bundle(4);
6776 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6777 String nameList[] = new String[componentNames.size()];
6778 componentNames.toArray(nameList);
6779 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006780 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6781 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006782 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006783 }
6784
Jacek Surazski65e13172009-04-28 15:26:38 +02006785 public String getInstallerPackageName(String packageName) {
6786 synchronized (mPackages) {
6787 PackageSetting pkg = mSettings.mPackages.get(packageName);
6788 if (pkg == null) {
6789 throw new IllegalArgumentException("Unknown package: " + packageName);
6790 }
6791 return pkg.installerPackageName;
6792 }
6793 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006795 public int getApplicationEnabledSetting(String appPackageName) {
6796 synchronized (mPackages) {
6797 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6798 if (pkg == null) {
6799 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6800 }
6801 return pkg.enabled;
6802 }
6803 }
6804
6805 public int getComponentEnabledSetting(ComponentName componentName) {
6806 synchronized (mPackages) {
6807 final String packageNameStr = componentName.getPackageName();
6808 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6809 if (pkg == null) {
6810 throw new IllegalArgumentException("Unknown component: " + componentName);
6811 }
6812 final String classNameStr = componentName.getClassName();
6813 return pkg.currentEnabledStateLP(classNameStr);
6814 }
6815 }
6816
6817 public void enterSafeMode() {
6818 if (!mSystemReady) {
6819 mSafeMode = true;
6820 }
6821 }
6822
6823 public void systemReady() {
6824 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006825
6826 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006827 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006828 mContext.getContentResolver(),
6829 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006830 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006831 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006832 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006834 }
6835
6836 public boolean isSafeMode() {
6837 return mSafeMode;
6838 }
6839
6840 public boolean hasSystemUidErrors() {
6841 return mHasSystemUidErrors;
6842 }
6843
6844 static String arrayToString(int[] array) {
6845 StringBuffer buf = new StringBuffer(128);
6846 buf.append('[');
6847 if (array != null) {
6848 for (int i=0; i<array.length; i++) {
6849 if (i > 0) buf.append(", ");
6850 buf.append(array[i]);
6851 }
6852 }
6853 buf.append(']');
6854 return buf.toString();
6855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 @Override
6858 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6859 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6860 != PackageManager.PERMISSION_GRANTED) {
6861 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6862 + Binder.getCallingPid()
6863 + ", uid=" + Binder.getCallingUid()
6864 + " without permission "
6865 + android.Manifest.permission.DUMP);
6866 return;
6867 }
6868
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006869 String packageName = null;
6870
6871 int opti = 0;
6872 while (opti < args.length) {
6873 String opt = args[opti];
6874 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6875 break;
6876 }
6877 opti++;
6878 if ("-a".equals(opt)) {
6879 // Right now we only know how to print all.
6880 } else if ("-h".equals(opt)) {
6881 pw.println("Package manager dump options:");
6882 pw.println(" [-h] [cmd] ...");
6883 pw.println(" cmd may be one of:");
6884 pw.println(" [package.name]: info about given package");
6885 return;
6886 } else {
6887 pw.println("Unknown argument: " + opt + "; use -h for help");
6888 }
6889 }
6890
6891 // Is the caller requesting to dump a particular piece of data?
6892 if (opti < args.length) {
6893 String cmd = args[opti];
6894 opti++;
6895 // Is this a package name?
6896 if ("android".equals(cmd) || cmd.contains(".")) {
6897 packageName = cmd;
6898 }
6899 }
6900
6901 boolean printedTitle = false;
6902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006904 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6905 printedTitle = true;
6906 }
6907 if (mReceivers.dump(pw, printedTitle
6908 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6909 " ", packageName)) {
6910 printedTitle = true;
6911 }
6912 if (mServices.dump(pw, printedTitle
6913 ? "\nService Resolver Table:" : "Service Resolver Table:",
6914 " ", packageName)) {
6915 printedTitle = true;
6916 }
6917 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6918 ? "\nPreferred Activities:" : "Preferred Activities:",
6919 " ", packageName)) {
6920 printedTitle = true;
6921 }
6922 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006923 {
6924 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006925 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6926 continue;
6927 }
6928 if (!printedSomething) {
6929 if (printedTitle) pw.println(" ");
6930 pw.println("Permissions:");
6931 printedSomething = true;
6932 printedTitle = true;
6933 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006934 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6935 pw.print(Integer.toHexString(System.identityHashCode(p)));
6936 pw.println("):");
6937 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6938 pw.print(" uid="); pw.print(p.uid);
6939 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006940 pw.print(" type="); pw.print(p.type);
6941 pw.print(" prot="); pw.println(p.protectionLevel);
6942 if (p.packageSetting != null) {
6943 pw.print(" packageSetting="); pw.println(p.packageSetting);
6944 }
6945 if (p.perm != null) {
6946 pw.print(" perm="); pw.println(p.perm);
6947 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 }
6949 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006950 printedSomething = false;
6951 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006952 {
6953 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006954 if (packageName != null && !packageName.equals(ps.realName)
6955 && !packageName.equals(ps.name)) {
6956 continue;
6957 }
6958 if (!printedSomething) {
6959 if (printedTitle) pw.println(" ");
6960 pw.println("Packages:");
6961 printedSomething = true;
6962 printedTitle = true;
6963 }
6964 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006965 pw.print(" Package [");
6966 pw.print(ps.realName != null ? ps.realName : ps.name);
6967 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006968 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6969 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006970 if (ps.realName != null) {
6971 pw.print(" compat name="); pw.println(ps.name);
6972 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006973 pw.print(" userId="); pw.print(ps.userId);
6974 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6975 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6976 pw.print(" pkg="); pw.println(ps.pkg);
6977 pw.print(" codePath="); pw.println(ps.codePathString);
6978 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07006979 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07006980 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006981 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006982 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006983 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07006984 if (ps.pkg.mOperationPending) {
6985 pw.println(" mOperationPending=true");
6986 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006987 pw.print(" supportsScreens=[");
6988 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006989 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07006990 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
6991 if (!first) pw.print(", ");
6992 first = false;
6993 pw.print("small");
6994 }
6995 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006996 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006997 if (!first) pw.print(", ");
6998 first = false;
6999 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007000 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007001 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007002 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007003 if (!first) pw.print(", ");
7004 first = false;
7005 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007007 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007008 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007009 if (!first) pw.print(", ");
7010 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007011 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007012 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007013 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007014 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007015 if (!first) pw.print(", ");
7016 first = false;
7017 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007018 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007019 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007020 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7021 if (!first) pw.print(", ");
7022 first = false;
7023 pw.print("anyDensity");
7024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007025 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007026 pw.println("]");
Kenny Root7d794fb2010-09-13 16:29:49 -07007027 pw.print(" timeStamp="); pw.println(String.valueOf(ps.timeStamp));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007028 pw.print(" signatures="); pw.println(ps.signatures);
7029 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007030 pw.print(" haveGids="); pw.println(ps.haveGids);
7031 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007032 pw.print(" installStatus="); pw.print(ps.installStatus);
7033 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 if (ps.disabledComponents.size() > 0) {
7035 pw.println(" disabledComponents:");
7036 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007037 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038 }
7039 }
7040 if (ps.enabledComponents.size() > 0) {
7041 pw.println(" enabledComponents:");
7042 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007043 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 }
7045 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007046 if (ps.grantedPermissions.size() > 0) {
7047 pw.println(" grantedPermissions:");
7048 for (String s : ps.grantedPermissions) {
7049 pw.print(" "); pw.println(s);
7050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007052 }
7053 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007054 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007055 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007056 for (HashMap.Entry<String, String> e
7057 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007058 if (packageName != null && !packageName.equals(e.getKey())
7059 && !packageName.equals(e.getValue())) {
7060 continue;
7061 }
7062 if (!printedSomething) {
7063 if (printedTitle) pw.println(" ");
7064 pw.println("Renamed packages:");
7065 printedSomething = true;
7066 printedTitle = true;
7067 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007068 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7069 pw.println(e.getValue());
7070 }
7071 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007072 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007073 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007074 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007075 if (packageName != null && !packageName.equals(ps.realName)
7076 && !packageName.equals(ps.name)) {
7077 continue;
7078 }
7079 if (!printedSomething) {
7080 if (printedTitle) pw.println(" ");
7081 pw.println("Hidden system packages:");
7082 printedSomething = true;
7083 printedTitle = true;
7084 }
7085 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007086 pw.print(ps.realName != null ? ps.realName : ps.name);
7087 pw.print("] (");
7088 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7089 pw.println("):");
7090 if (ps.realName != null) {
7091 pw.print(" compat name="); pw.println(ps.name);
7092 }
7093 pw.print(" userId="); pw.println(ps.userId);
7094 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7095 pw.print(" codePath="); pw.println(ps.codePathString);
7096 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7097 }
7098 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007099 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 {
7101 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007102 if (packageName != null && su != packageSharedUser) {
7103 continue;
7104 }
7105 if (!printedSomething) {
7106 if (printedTitle) pw.println(" ");
7107 pw.println("Shared users:");
7108 printedSomething = true;
7109 printedTitle = true;
7110 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007111 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7112 pw.print(Integer.toHexString(System.identityHashCode(su)));
7113 pw.println("):");
7114 pw.print(" userId="); pw.print(su.userId);
7115 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007116 pw.println(" grantedPermissions:");
7117 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007118 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007120 }
7121 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007122
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007123 if (packageName == null) {
7124 if (printedTitle) pw.println(" ");
7125 printedTitle = true;
7126 pw.println("Settings parse messages:");
7127 pw.println(mSettings.mReadMessages.toString());
7128
7129 pw.println(" ");
7130 pw.println("Package warning messages:");
7131 File fname = getSettingsProblemFile();
7132 FileInputStream in;
7133 try {
7134 in = new FileInputStream(fname);
7135 int avail = in.available();
7136 byte[] data = new byte[avail];
7137 in.read(data);
7138 pw.println(new String(data));
7139 } catch (FileNotFoundException e) {
7140 } catch (IOException e) {
7141 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007143 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007144
7145 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007146 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007147 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007148 if (packageName != null && !packageName.equals(p.info.packageName)) {
7149 continue;
7150 }
7151 if (!printedSomething) {
7152 if (printedTitle) pw.println(" ");
7153 pw.println("Registered ContentProviders:");
7154 printedSomething = true;
7155 printedTitle = true;
7156 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007157 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007158 pw.println(p.toString());
7159 }
7160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007161 }
7162
7163 static final class BasePermission {
7164 final static int TYPE_NORMAL = 0;
7165 final static int TYPE_BUILTIN = 1;
7166 final static int TYPE_DYNAMIC = 2;
7167
7168 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007169 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007170 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007171 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007172 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 PackageParser.Permission perm;
7174 PermissionInfo pendingInfo;
7175 int uid;
7176 int[] gids;
7177
7178 BasePermission(String _name, String _sourcePackage, int _type) {
7179 name = _name;
7180 sourcePackage = _sourcePackage;
7181 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007182 // Default to most conservative protection level.
7183 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7184 }
7185
7186 public String toString() {
7187 return "BasePermission{"
7188 + Integer.toHexString(System.identityHashCode(this))
7189 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 }
7191 }
7192
7193 static class PackageSignatures {
7194 private Signature[] mSignatures;
7195
7196 PackageSignatures(Signature[] sigs) {
7197 assignSignatures(sigs);
7198 }
7199
7200 PackageSignatures() {
7201 }
7202
7203 void writeXml(XmlSerializer serializer, String tagName,
7204 ArrayList<Signature> pastSignatures) throws IOException {
7205 if (mSignatures == null) {
7206 return;
7207 }
7208 serializer.startTag(null, tagName);
7209 serializer.attribute(null, "count",
7210 Integer.toString(mSignatures.length));
7211 for (int i=0; i<mSignatures.length; i++) {
7212 serializer.startTag(null, "cert");
7213 final Signature sig = mSignatures[i];
7214 final int sigHash = sig.hashCode();
7215 final int numPast = pastSignatures.size();
7216 int j;
7217 for (j=0; j<numPast; j++) {
7218 Signature pastSig = pastSignatures.get(j);
7219 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7220 serializer.attribute(null, "index", Integer.toString(j));
7221 break;
7222 }
7223 }
7224 if (j >= numPast) {
7225 pastSignatures.add(sig);
7226 serializer.attribute(null, "index", Integer.toString(numPast));
7227 serializer.attribute(null, "key", sig.toCharsString());
7228 }
7229 serializer.endTag(null, "cert");
7230 }
7231 serializer.endTag(null, tagName);
7232 }
7233
7234 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7235 throws IOException, XmlPullParserException {
7236 String countStr = parser.getAttributeValue(null, "count");
7237 if (countStr == null) {
7238 reportSettingsProblem(Log.WARN,
7239 "Error in package manager settings: <signatures> has"
7240 + " no count at " + parser.getPositionDescription());
7241 XmlUtils.skipCurrentTag(parser);
7242 }
7243 final int count = Integer.parseInt(countStr);
7244 mSignatures = new Signature[count];
7245 int pos = 0;
7246
7247 int outerDepth = parser.getDepth();
7248 int type;
7249 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7250 && (type != XmlPullParser.END_TAG
7251 || parser.getDepth() > outerDepth)) {
7252 if (type == XmlPullParser.END_TAG
7253 || type == XmlPullParser.TEXT) {
7254 continue;
7255 }
7256
7257 String tagName = parser.getName();
7258 if (tagName.equals("cert")) {
7259 if (pos < count) {
7260 String index = parser.getAttributeValue(null, "index");
7261 if (index != null) {
7262 try {
7263 int idx = Integer.parseInt(index);
7264 String key = parser.getAttributeValue(null, "key");
7265 if (key == null) {
7266 if (idx >= 0 && idx < pastSignatures.size()) {
7267 Signature sig = pastSignatures.get(idx);
7268 if (sig != null) {
7269 mSignatures[pos] = pastSignatures.get(idx);
7270 pos++;
7271 } else {
7272 reportSettingsProblem(Log.WARN,
7273 "Error in package manager settings: <cert> "
7274 + "index " + index + " is not defined at "
7275 + parser.getPositionDescription());
7276 }
7277 } else {
7278 reportSettingsProblem(Log.WARN,
7279 "Error in package manager settings: <cert> "
7280 + "index " + index + " is out of bounds at "
7281 + parser.getPositionDescription());
7282 }
7283 } else {
7284 while (pastSignatures.size() <= idx) {
7285 pastSignatures.add(null);
7286 }
7287 Signature sig = new Signature(key);
7288 pastSignatures.set(idx, sig);
7289 mSignatures[pos] = sig;
7290 pos++;
7291 }
7292 } catch (NumberFormatException e) {
7293 reportSettingsProblem(Log.WARN,
7294 "Error in package manager settings: <cert> "
7295 + "index " + index + " is not a number at "
7296 + parser.getPositionDescription());
7297 }
7298 } else {
7299 reportSettingsProblem(Log.WARN,
7300 "Error in package manager settings: <cert> has"
7301 + " no index at " + parser.getPositionDescription());
7302 }
7303 } else {
7304 reportSettingsProblem(Log.WARN,
7305 "Error in package manager settings: too "
7306 + "many <cert> tags, expected " + count
7307 + " at " + parser.getPositionDescription());
7308 }
7309 } else {
7310 reportSettingsProblem(Log.WARN,
7311 "Unknown element under <cert>: "
7312 + parser.getName());
7313 }
7314 XmlUtils.skipCurrentTag(parser);
7315 }
7316
7317 if (pos < count) {
7318 // Should never happen -- there is an error in the written
7319 // settings -- but if it does we don't want to generate
7320 // a bad array.
7321 Signature[] newSigs = new Signature[pos];
7322 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7323 mSignatures = newSigs;
7324 }
7325 }
7326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007327 private void assignSignatures(Signature[] sigs) {
7328 if (sigs == null) {
7329 mSignatures = null;
7330 return;
7331 }
7332 mSignatures = new Signature[sigs.length];
7333 for (int i=0; i<sigs.length; i++) {
7334 mSignatures[i] = sigs[i];
7335 }
7336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 @Override
7339 public String toString() {
7340 StringBuffer buf = new StringBuffer(128);
7341 buf.append("PackageSignatures{");
7342 buf.append(Integer.toHexString(System.identityHashCode(this)));
7343 buf.append(" [");
7344 if (mSignatures != null) {
7345 for (int i=0; i<mSignatures.length; i++) {
7346 if (i > 0) buf.append(", ");
7347 buf.append(Integer.toHexString(
7348 System.identityHashCode(mSignatures[i])));
7349 }
7350 }
7351 buf.append("]}");
7352 return buf.toString();
7353 }
7354 }
7355
7356 static class PreferredActivity extends IntentFilter {
7357 final int mMatch;
7358 final String[] mSetPackages;
7359 final String[] mSetClasses;
7360 final String[] mSetComponents;
7361 final ComponentName mActivity;
7362 final String mShortActivity;
7363 String mParseError;
7364
7365 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7366 ComponentName activity) {
7367 super(filter);
7368 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7369 mActivity = activity;
7370 mShortActivity = activity.flattenToShortString();
7371 mParseError = null;
7372 if (set != null) {
7373 final int N = set.length;
7374 String[] myPackages = new String[N];
7375 String[] myClasses = new String[N];
7376 String[] myComponents = new String[N];
7377 for (int i=0; i<N; i++) {
7378 ComponentName cn = set[i];
7379 if (cn == null) {
7380 mSetPackages = null;
7381 mSetClasses = null;
7382 mSetComponents = null;
7383 return;
7384 }
7385 myPackages[i] = cn.getPackageName().intern();
7386 myClasses[i] = cn.getClassName().intern();
7387 myComponents[i] = cn.flattenToShortString().intern();
7388 }
7389 mSetPackages = myPackages;
7390 mSetClasses = myClasses;
7391 mSetComponents = myComponents;
7392 } else {
7393 mSetPackages = null;
7394 mSetClasses = null;
7395 mSetComponents = null;
7396 }
7397 }
7398
7399 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7400 IOException {
7401 mShortActivity = parser.getAttributeValue(null, "name");
7402 mActivity = ComponentName.unflattenFromString(mShortActivity);
7403 if (mActivity == null) {
7404 mParseError = "Bad activity name " + mShortActivity;
7405 }
7406 String matchStr = parser.getAttributeValue(null, "match");
7407 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7408 String setCountStr = parser.getAttributeValue(null, "set");
7409 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7410
7411 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7412 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7413 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7414
7415 int setPos = 0;
7416
7417 int outerDepth = parser.getDepth();
7418 int type;
7419 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7420 && (type != XmlPullParser.END_TAG
7421 || parser.getDepth() > outerDepth)) {
7422 if (type == XmlPullParser.END_TAG
7423 || type == XmlPullParser.TEXT) {
7424 continue;
7425 }
7426
7427 String tagName = parser.getName();
7428 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7429 // + parser.getDepth() + " tag=" + tagName);
7430 if (tagName.equals("set")) {
7431 String name = parser.getAttributeValue(null, "name");
7432 if (name == null) {
7433 if (mParseError == null) {
7434 mParseError = "No name in set tag in preferred activity "
7435 + mShortActivity;
7436 }
7437 } else if (setPos >= setCount) {
7438 if (mParseError == null) {
7439 mParseError = "Too many set tags in preferred activity "
7440 + mShortActivity;
7441 }
7442 } else {
7443 ComponentName cn = ComponentName.unflattenFromString(name);
7444 if (cn == null) {
7445 if (mParseError == null) {
7446 mParseError = "Bad set name " + name + " in preferred activity "
7447 + mShortActivity;
7448 }
7449 } else {
7450 myPackages[setPos] = cn.getPackageName();
7451 myClasses[setPos] = cn.getClassName();
7452 myComponents[setPos] = name;
7453 setPos++;
7454 }
7455 }
7456 XmlUtils.skipCurrentTag(parser);
7457 } else if (tagName.equals("filter")) {
7458 //Log.i(TAG, "Starting to parse filter...");
7459 readFromXml(parser);
7460 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7461 // + parser.getDepth() + " tag=" + parser.getName());
7462 } else {
7463 reportSettingsProblem(Log.WARN,
7464 "Unknown element under <preferred-activities>: "
7465 + parser.getName());
7466 XmlUtils.skipCurrentTag(parser);
7467 }
7468 }
7469
7470 if (setPos != setCount) {
7471 if (mParseError == null) {
7472 mParseError = "Not enough set tags (expected " + setCount
7473 + " but found " + setPos + ") in " + mShortActivity;
7474 }
7475 }
7476
7477 mSetPackages = myPackages;
7478 mSetClasses = myClasses;
7479 mSetComponents = myComponents;
7480 }
7481
7482 public void writeToXml(XmlSerializer serializer) throws IOException {
7483 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7484 serializer.attribute(null, "name", mShortActivity);
7485 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7486 serializer.attribute(null, "set", Integer.toString(NS));
7487 for (int s=0; s<NS; s++) {
7488 serializer.startTag(null, "set");
7489 serializer.attribute(null, "name", mSetComponents[s]);
7490 serializer.endTag(null, "set");
7491 }
7492 serializer.startTag(null, "filter");
7493 super.writeToXml(serializer);
7494 serializer.endTag(null, "filter");
7495 }
7496
7497 boolean sameSet(List<ResolveInfo> query, int priority) {
7498 if (mSetPackages == null) return false;
7499 final int NQ = query.size();
7500 final int NS = mSetPackages.length;
7501 int numMatch = 0;
7502 for (int i=0; i<NQ; i++) {
7503 ResolveInfo ri = query.get(i);
7504 if (ri.priority != priority) continue;
7505 ActivityInfo ai = ri.activityInfo;
7506 boolean good = false;
7507 for (int j=0; j<NS; j++) {
7508 if (mSetPackages[j].equals(ai.packageName)
7509 && mSetClasses[j].equals(ai.name)) {
7510 numMatch++;
7511 good = true;
7512 break;
7513 }
7514 }
7515 if (!good) return false;
7516 }
7517 return numMatch == NS;
7518 }
7519 }
7520
7521 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007522 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007524 HashSet<String> grantedPermissions = new HashSet<String>();
7525 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007527 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007528 setFlags(pkgFlags);
7529 }
7530
7531 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007532 this.pkgFlags = pkgFlags & (
7533 ApplicationInfo.FLAG_SYSTEM |
7534 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007535 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007536 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 }
7538 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007540 /**
7541 * Settings base class for pending and resolved classes.
7542 */
7543 static class PackageSettingBase extends GrantedPermissions {
7544 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007545 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007546 File codePath;
7547 String codePathString;
7548 File resourcePath;
7549 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007550 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007551 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007552 long timeStamp;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007553 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007554
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007555 boolean uidError;
7556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557 PackageSignatures signatures = new PackageSignatures();
7558
7559 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007560 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 /* Explicitly disabled components */
7563 HashSet<String> disabledComponents = new HashSet<String>(0);
7564 /* Explicitly enabled components */
7565 HashSet<String> enabledComponents = new HashSet<String>(0);
7566 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7567 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007568
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007569 PackageSettingBase origPackage;
7570
Jacek Surazski65e13172009-04-28 15:26:38 +02007571 /* package name of the app that installed this package */
7572 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007574 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007575 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007576 super(pkgFlags);
7577 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007578 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007579 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007580 }
7581
Kenny Root806cc132010-09-12 08:34:19 -07007582 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7583 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 this.codePath = codePath;
7585 this.codePathString = codePath.toString();
7586 this.resourcePath = resourcePath;
7587 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007588 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007589 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 }
Kenny Root85387d72010-08-26 10:13:11 -07007591
Jacek Surazski65e13172009-04-28 15:26:38 +02007592 public void setInstallerPackageName(String packageName) {
7593 installerPackageName = packageName;
7594 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007595
Jacek Surazski65e13172009-04-28 15:26:38 +02007596 String getInstallerPackageName() {
7597 return installerPackageName;
7598 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 public void setInstallStatus(int newStatus) {
7601 installStatus = newStatus;
7602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 public int getInstallStatus() {
7605 return installStatus;
7606 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007610 }
7611
7612 public void copyFrom(PackageSettingBase base) {
7613 grantedPermissions = base.grantedPermissions;
7614 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 timeStamp = base.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617 signatures = base.signatures;
7618 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007619 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007620 disabledComponents = base.disabledComponents;
7621 enabledComponents = base.enabledComponents;
7622 enabled = base.enabled;
7623 installStatus = base.installStatus;
7624 }
7625
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007626 boolean enableComponentLP(String componentClassName) {
7627 boolean changed = disabledComponents.remove(componentClassName);
7628 changed |= enabledComponents.add(componentClassName);
7629 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007630 }
7631
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007632 boolean disableComponentLP(String componentClassName) {
7633 boolean changed = enabledComponents.remove(componentClassName);
7634 changed |= disabledComponents.add(componentClassName);
7635 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007636 }
7637
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007638 boolean restoreComponentLP(String componentClassName) {
7639 boolean changed = enabledComponents.remove(componentClassName);
7640 changed |= disabledComponents.remove(componentClassName);
7641 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642 }
7643
7644 int currentEnabledStateLP(String componentName) {
7645 if (enabledComponents.contains(componentName)) {
7646 return COMPONENT_ENABLED_STATE_ENABLED;
7647 } else if (disabledComponents.contains(componentName)) {
7648 return COMPONENT_ENABLED_STATE_DISABLED;
7649 } else {
7650 return COMPONENT_ENABLED_STATE_DEFAULT;
7651 }
7652 }
7653 }
7654
7655 /**
7656 * Settings data for a particular package we know about.
7657 */
7658 static final class PackageSetting extends PackageSettingBase {
7659 int userId;
7660 PackageParser.Package pkg;
7661 SharedUserSetting sharedUser;
7662
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007663 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007664 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7665 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7666 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 @Override
7670 public String toString() {
7671 return "PackageSetting{"
7672 + Integer.toHexString(System.identityHashCode(this))
7673 + " " + name + "/" + userId + "}";
7674 }
7675 }
7676
7677 /**
7678 * Settings data for a particular shared user ID we know about.
7679 */
7680 static final class SharedUserSetting extends GrantedPermissions {
7681 final String name;
7682 int userId;
7683 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7684 final PackageSignatures signatures = new PackageSignatures();
7685
7686 SharedUserSetting(String _name, int _pkgFlags) {
7687 super(_pkgFlags);
7688 name = _name;
7689 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007691 @Override
7692 public String toString() {
7693 return "SharedUserSetting{"
7694 + Integer.toHexString(System.identityHashCode(this))
7695 + " " + name + "/" + userId + "}";
7696 }
7697 }
7698
7699 /**
7700 * Holds information about dynamic settings.
7701 */
7702 private static final class Settings {
7703 private final File mSettingsFilename;
7704 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007705 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007706 private final HashMap<String, PackageSetting> mPackages =
7707 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007708 // List of replaced system applications
7709 final HashMap<String, PackageSetting> mDisabledSysPackages =
7710 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007711
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007712 // These are the last platform API version we were using for
7713 // the apps installed on internal and external storage. It is
7714 // used to grant newer permissions one time during a system upgrade.
7715 int mInternalSdkPlatform;
7716 int mExternalSdkPlatform;
7717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 // The user's preferred activities associated with particular intent
7719 // filters.
7720 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7721 new IntentResolver<PreferredActivity, PreferredActivity>() {
7722 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007723 protected String packageForFilter(PreferredActivity filter) {
7724 return filter.mActivity.getPackageName();
7725 }
7726 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007727 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007728 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007729 out.print(prefix); out.print(
7730 Integer.toHexString(System.identityHashCode(filter)));
7731 out.print(' ');
7732 out.print(filter.mActivity.flattenToShortString());
7733 out.print(" match=0x");
7734 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007736 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007738 out.print(prefix); out.print(" ");
7739 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 }
7741 }
7742 }
7743 };
7744 private final HashMap<String, SharedUserSetting> mSharedUsers =
7745 new HashMap<String, SharedUserSetting>();
7746 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7747 private final SparseArray<Object> mOtherUserIds =
7748 new SparseArray<Object>();
7749
7750 // For reading/writing settings file.
7751 private final ArrayList<Signature> mPastSignatures =
7752 new ArrayList<Signature>();
7753
7754 // Mapping from permission names to info about them.
7755 final HashMap<String, BasePermission> mPermissions =
7756 new HashMap<String, BasePermission>();
7757
7758 // Mapping from permission tree names to info about them.
7759 final HashMap<String, BasePermission> mPermissionTrees =
7760 new HashMap<String, BasePermission>();
7761
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007762 // Packages that have been uninstalled and still need their external
7763 // storage data deleted.
7764 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7765
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007766 // Packages that have been renamed since they were first installed.
7767 // Keys are the new names of the packages, values are the original
7768 // names. The packages appear everwhere else under their original
7769 // names.
7770 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 private final StringBuilder mReadMessages = new StringBuilder();
7773
7774 private static final class PendingPackage extends PackageSettingBase {
7775 final int sharedId;
7776
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007777 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007778 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7779 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7780 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007781 this.sharedId = sharedId;
7782 }
7783 }
7784 private final ArrayList<PendingPackage> mPendingPackages
7785 = new ArrayList<PendingPackage>();
7786
7787 Settings() {
7788 File dataDir = Environment.getDataDirectory();
7789 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007790 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7791 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007792 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007793 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007794 FileUtils.setPermissions(systemDir.toString(),
7795 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7796 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7797 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007798 FileUtils.setPermissions(systemSecureDir.toString(),
7799 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7800 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7801 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 mSettingsFilename = new File(systemDir, "packages.xml");
7803 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007804 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 }
7806
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007807 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007808 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007809 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007810 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007811 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007812 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 return p;
7814 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007815
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007816 PackageSetting peekPackageLP(String name) {
7817 return mPackages.get(name);
7818 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007819 PackageSetting p = mPackages.get(name);
7820 if (p != null && p.codePath.getPath().equals(codePath)) {
7821 return p;
7822 }
7823 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007824 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007826
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007827 void setInstallStatus(String pkgName, int status) {
7828 PackageSetting p = mPackages.get(pkgName);
7829 if(p != null) {
7830 if(p.getInstallStatus() != status) {
7831 p.setInstallStatus(status);
7832 }
7833 }
7834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007835
Jacek Surazski65e13172009-04-28 15:26:38 +02007836 void setInstallerPackageName(String pkgName,
7837 String installerPkgName) {
7838 PackageSetting p = mPackages.get(pkgName);
7839 if(p != null) {
7840 p.setInstallerPackageName(installerPkgName);
7841 }
7842 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007843
Jacek Surazski65e13172009-04-28 15:26:38 +02007844 String getInstallerPackageName(String pkgName) {
7845 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007846 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007847 }
7848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 int getInstallStatus(String pkgName) {
7850 PackageSetting p = mPackages.get(pkgName);
7851 if(p != null) {
7852 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007854 return -1;
7855 }
7856
7857 SharedUserSetting getSharedUserLP(String name,
7858 int pkgFlags, boolean create) {
7859 SharedUserSetting s = mSharedUsers.get(name);
7860 if (s == null) {
7861 if (!create) {
7862 return null;
7863 }
7864 s = new SharedUserSetting(name, pkgFlags);
7865 if (MULTIPLE_APPLICATION_UIDS) {
7866 s.userId = newUserIdLP(s);
7867 } else {
7868 s.userId = FIRST_APPLICATION_UID;
7869 }
7870 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7871 // < 0 means we couldn't assign a userid; fall out and return
7872 // s, which is currently null
7873 if (s.userId >= 0) {
7874 mSharedUsers.put(name, s);
7875 }
7876 }
7877
7878 return s;
7879 }
7880
7881 int disableSystemPackageLP(String name) {
7882 PackageSetting p = mPackages.get(name);
7883 if(p == null) {
7884 Log.w(TAG, "Package:"+name+" is not an installed package");
7885 return -1;
7886 }
7887 PackageSetting dp = mDisabledSysPackages.get(name);
7888 // always make sure the system package code and resource paths dont change
7889 if(dp == null) {
7890 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7891 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7892 }
7893 mDisabledSysPackages.put(name, p);
7894 }
7895 return removePackageLP(name);
7896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007898 PackageSetting enableSystemPackageLP(String name) {
7899 PackageSetting p = mDisabledSysPackages.get(name);
7900 if(p == null) {
7901 Log.w(TAG, "Package:"+name+" is not disabled");
7902 return null;
7903 }
7904 // Reset flag in ApplicationInfo object
7905 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7906 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7907 }
Kenny Root806cc132010-09-12 08:34:19 -07007908 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
7909 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007910 mDisabledSysPackages.remove(name);
7911 return ret;
7912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007913
Kenny Root806cc132010-09-12 08:34:19 -07007914 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
7915 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 PackageSetting p = mPackages.get(name);
7917 if (p != null) {
7918 if (p.userId == uid) {
7919 return p;
7920 }
7921 reportSettingsProblem(Log.ERROR,
7922 "Adding duplicate package, keeping first: " + name);
7923 return null;
7924 }
Kenny Root806cc132010-09-12 08:34:19 -07007925 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
7926 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 p.userId = uid;
7928 if (addUserIdLP(uid, p, name)) {
7929 mPackages.put(name, p);
7930 return p;
7931 }
7932 return null;
7933 }
7934
7935 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7936 SharedUserSetting s = mSharedUsers.get(name);
7937 if (s != null) {
7938 if (s.userId == uid) {
7939 return s;
7940 }
7941 reportSettingsProblem(Log.ERROR,
7942 "Adding duplicate shared user, keeping first: " + name);
7943 return null;
7944 }
7945 s = new SharedUserSetting(name, pkgFlags);
7946 s.userId = uid;
7947 if (addUserIdLP(uid, s, name)) {
7948 mSharedUsers.put(name, s);
7949 return s;
7950 }
7951 return null;
7952 }
7953
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007954 // Transfer ownership of permissions from one package to another.
7955 private void transferPermissions(String origPkg, String newPkg) {
7956 // Transfer ownership of permissions to the new package.
7957 for (int i=0; i<2; i++) {
7958 HashMap<String, BasePermission> permissions =
7959 i == 0 ? mPermissionTrees : mPermissions;
7960 for (BasePermission bp : permissions.values()) {
7961 if (origPkg.equals(bp.sourcePackage)) {
7962 if (DEBUG_UPGRADE) Log.v(TAG,
7963 "Moving permission " + bp.name
7964 + " from pkg " + bp.sourcePackage
7965 + " to " + newPkg);
7966 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007967 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007968 bp.perm = null;
7969 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007970 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007971 }
7972 bp.uid = 0;
7973 bp.gids = null;
7974 }
7975 }
7976 }
7977 }
7978
7979 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007980 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007981 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 PackageSetting p = mPackages.get(name);
7983 if (p != null) {
7984 if (!p.codePath.equals(codePath)) {
7985 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007986 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007987 // This is an updated system app with versions in both system
7988 // and data partition. Just let the most recent version
7989 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007990 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007991 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007992 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007993 // Just a change in the code path is not an issue, but
7994 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007995 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007996 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007998 }
7999 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008000 reportSettingsProblem(Log.WARN,
8001 "Package " + name + " shared user changed from "
8002 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8003 + " to "
8004 + (sharedUser != null ? sharedUser.name : "<nothing>")
8005 + "; replacing with new");
8006 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008007 } else {
8008 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8009 // If what we are scanning is a system package, then
8010 // make it so, regardless of whether it was previously
8011 // installed only in the data partition.
8012 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 }
8015 }
8016 if (p == null) {
8017 // Create a new PackageSettings entry. this can end up here because
8018 // of code path mismatch or user id mismatch of an updated system partition
8019 if (!create) {
8020 return null;
8021 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008022 if (origPackage != null) {
8023 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008024 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8025 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008026 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8027 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008028 // Note that we will retain the new package's signature so
8029 // that we can keep its data.
8030 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008031 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008032 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008033 p.sharedUser = origPackage.sharedUser;
8034 p.userId = origPackage.userId;
8035 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008036 mRenamedPackages.put(name, origPackage.name);
8037 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008038 // Update new package state.
8039 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008041 p = new PackageSetting(name, realName, codePath, resourcePath,
8042 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008043 p.setTimeStamp(codePath.lastModified());
8044 p.sharedUser = sharedUser;
8045 if (sharedUser != null) {
8046 p.userId = sharedUser.userId;
8047 } else if (MULTIPLE_APPLICATION_UIDS) {
8048 // Clone the setting here for disabled system packages
8049 PackageSetting dis = mDisabledSysPackages.get(name);
8050 if (dis != null) {
8051 // For disabled packages a new setting is created
8052 // from the existing user id. This still has to be
8053 // added to list of user id's
8054 // Copy signatures from previous setting
8055 if (dis.signatures.mSignatures != null) {
8056 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8057 }
8058 p.userId = dis.userId;
8059 // Clone permissions
8060 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008061 // Clone component info
8062 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8063 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8064 // Add new setting to list of user ids
8065 addUserIdLP(p.userId, p, name);
8066 } else {
8067 // Assign new user id
8068 p.userId = newUserIdLP(p);
8069 }
8070 } else {
8071 p.userId = FIRST_APPLICATION_UID;
8072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008073 }
8074 if (p.userId < 0) {
8075 reportSettingsProblem(Log.WARN,
8076 "Package " + name + " could not be assigned a valid uid");
8077 return null;
8078 }
8079 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008080 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008081 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008082 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008083 }
8084 }
8085 return p;
8086 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008087
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008088 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008089 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008090 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008091 final String codePath = pkg.applicationInfo.sourceDir;
8092 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008093 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008094 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008095 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008096 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008097 p.codePath = new File(codePath);
8098 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008099 }
8100 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008101 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008102 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008103 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008104 p.resourcePath = new File(resourcePath);
8105 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008106 }
Kenny Root85387d72010-08-26 10:13:11 -07008107 // Update the native library path if needed
8108 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8109 if (nativeLibraryPath != null
8110 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8111 p.nativeLibraryPathString = nativeLibraryPath;
8112 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008113 // Update version code if needed
8114 if (pkg.mVersionCode != p.versionCode) {
8115 p.versionCode = pkg.mVersionCode;
8116 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008117 // Update signatures if needed.
8118 if (p.signatures.mSignatures == null) {
8119 p.signatures.assignSignatures(pkg.mSignatures);
8120 }
8121 // If this app defines a shared user id initialize
8122 // the shared user signatures as well.
8123 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8124 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8125 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008126 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8127 }
8128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008129 // Utility method that adds a PackageSetting to mPackages and
8130 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008131 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008132 SharedUserSetting sharedUser) {
8133 mPackages.put(name, p);
8134 if (sharedUser != null) {
8135 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8136 reportSettingsProblem(Log.ERROR,
8137 "Package " + p.name + " was user "
8138 + p.sharedUser + " but is now " + sharedUser
8139 + "; I am not changing its files so it will probably fail!");
8140 p.sharedUser.packages.remove(p);
8141 } else if (p.userId != sharedUser.userId) {
8142 reportSettingsProblem(Log.ERROR,
8143 "Package " + p.name + " was user id " + p.userId
8144 + " but is now user " + sharedUser
8145 + " with id " + sharedUser.userId
8146 + "; I am not changing its files so it will probably fail!");
8147 }
8148
8149 sharedUser.packages.add(p);
8150 p.sharedUser = sharedUser;
8151 p.userId = sharedUser.userId;
8152 }
8153 }
8154
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008155 /*
8156 * Update the shared user setting when a package using
8157 * specifying the shared user id is removed. The gids
8158 * associated with each permission of the deleted package
8159 * are removed from the shared user's gid list only if its
8160 * not in use by other permissions of packages in the
8161 * shared user setting.
8162 */
8163 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008164 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008165 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008166 return;
8167 }
8168 // No sharedUserId
8169 if (deletedPs.sharedUser == null) {
8170 return;
8171 }
8172 SharedUserSetting sus = deletedPs.sharedUser;
8173 // Update permissions
8174 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8175 boolean used = false;
8176 if (!sus.grantedPermissions.contains (eachPerm)) {
8177 continue;
8178 }
8179 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008180 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008181 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008182 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008183 used = true;
8184 break;
8185 }
8186 }
8187 if (!used) {
8188 // can safely delete this permission from list
8189 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008190 }
8191 }
8192 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008193 int newGids[] = globalGids;
8194 for (String eachPerm : sus.grantedPermissions) {
8195 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008196 if (bp != null) {
8197 newGids = appendInts(newGids, bp.gids);
8198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 }
8200 sus.gids = newGids;
8201 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008202
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008203 private int removePackageLP(String name) {
8204 PackageSetting p = mPackages.get(name);
8205 if (p != null) {
8206 mPackages.remove(name);
8207 if (p.sharedUser != null) {
8208 p.sharedUser.packages.remove(p);
8209 if (p.sharedUser.packages.size() == 0) {
8210 mSharedUsers.remove(p.sharedUser.name);
8211 removeUserIdLP(p.sharedUser.userId);
8212 return p.sharedUser.userId;
8213 }
8214 } else {
8215 removeUserIdLP(p.userId);
8216 return p.userId;
8217 }
8218 }
8219 return -1;
8220 }
8221
8222 private boolean addUserIdLP(int uid, Object obj, Object name) {
8223 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8224 return false;
8225 }
8226
8227 if (uid >= FIRST_APPLICATION_UID) {
8228 int N = mUserIds.size();
8229 final int index = uid - FIRST_APPLICATION_UID;
8230 while (index >= N) {
8231 mUserIds.add(null);
8232 N++;
8233 }
8234 if (mUserIds.get(index) != null) {
8235 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008236 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008237 + " name=" + name);
8238 return false;
8239 }
8240 mUserIds.set(index, obj);
8241 } else {
8242 if (mOtherUserIds.get(uid) != null) {
8243 reportSettingsProblem(Log.ERROR,
8244 "Adding duplicate shared id: " + uid
8245 + " name=" + name);
8246 return false;
8247 }
8248 mOtherUserIds.put(uid, obj);
8249 }
8250 return true;
8251 }
8252
8253 public Object getUserIdLP(int uid) {
8254 if (uid >= FIRST_APPLICATION_UID) {
8255 int N = mUserIds.size();
8256 final int index = uid - FIRST_APPLICATION_UID;
8257 return index < N ? mUserIds.get(index) : null;
8258 } else {
8259 return mOtherUserIds.get(uid);
8260 }
8261 }
8262
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008263 private Set<String> findPackagesWithFlag(int flag) {
8264 Set<String> ret = new HashSet<String>();
8265 for (PackageSetting ps : mPackages.values()) {
8266 // Has to match atleast all the flag bits set on flag
8267 if ((ps.pkgFlags & flag) == flag) {
8268 ret.add(ps.name);
8269 }
8270 }
8271 return ret;
8272 }
8273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008274 private void removeUserIdLP(int uid) {
8275 if (uid >= FIRST_APPLICATION_UID) {
8276 int N = mUserIds.size();
8277 final int index = uid - FIRST_APPLICATION_UID;
8278 if (index < N) mUserIds.set(index, null);
8279 } else {
8280 mOtherUserIds.remove(uid);
8281 }
8282 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008284 void writeLP() {
8285 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8286
8287 // Keep the old settings around until we know the new ones have
8288 // been successfully written.
8289 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008290 // Presence of backup settings file indicates that we failed
8291 // to persist settings earlier. So preserve the older
8292 // backup for future reference since the current settings
8293 // might have been corrupted.
8294 if (!mBackupSettingsFilename.exists()) {
8295 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008296 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008297 return;
8298 }
8299 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008300 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008301 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008303 }
8304
8305 mPastSignatures.clear();
8306
8307 try {
Kenny Root9f306d72010-09-26 11:19:47 -07008308 BufferedOutputStream str = new BufferedOutputStream(new FileOutputStream(
8309 mSettingsFilename));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008310
8311 //XmlSerializer serializer = XmlUtils.serializerInstance();
8312 XmlSerializer serializer = new FastXmlSerializer();
8313 serializer.setOutput(str, "utf-8");
8314 serializer.startDocument(null, true);
8315 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8316
8317 serializer.startTag(null, "packages");
8318
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008319 serializer.startTag(null, "last-platform-version");
8320 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8321 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8322 serializer.endTag(null, "last-platform-version");
8323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008324 serializer.startTag(null, "permission-trees");
8325 for (BasePermission bp : mPermissionTrees.values()) {
8326 writePermission(serializer, bp);
8327 }
8328 serializer.endTag(null, "permission-trees");
8329
8330 serializer.startTag(null, "permissions");
8331 for (BasePermission bp : mPermissions.values()) {
8332 writePermission(serializer, bp);
8333 }
8334 serializer.endTag(null, "permissions");
8335
8336 for (PackageSetting pkg : mPackages.values()) {
8337 writePackage(serializer, pkg);
8338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008340 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8341 writeDisabledSysPackage(serializer, pkg);
8342 }
8343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 serializer.startTag(null, "preferred-activities");
8345 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8346 serializer.startTag(null, "item");
8347 pa.writeToXml(serializer);
8348 serializer.endTag(null, "item");
8349 }
8350 serializer.endTag(null, "preferred-activities");
8351
8352 for (SharedUserSetting usr : mSharedUsers.values()) {
8353 serializer.startTag(null, "shared-user");
8354 serializer.attribute(null, "name", usr.name);
8355 serializer.attribute(null, "userId",
8356 Integer.toString(usr.userId));
8357 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8358 serializer.startTag(null, "perms");
8359 for (String name : usr.grantedPermissions) {
8360 serializer.startTag(null, "item");
8361 serializer.attribute(null, "name", name);
8362 serializer.endTag(null, "item");
8363 }
8364 serializer.endTag(null, "perms");
8365 serializer.endTag(null, "shared-user");
8366 }
8367
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008368 if (mPackagesToBeCleaned.size() > 0) {
8369 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8370 serializer.startTag(null, "cleaning-package");
8371 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8372 serializer.endTag(null, "cleaning-package");
8373 }
8374 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008375
8376 if (mRenamedPackages.size() > 0) {
8377 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8378 serializer.startTag(null, "renamed-package");
8379 serializer.attribute(null, "new", e.getKey());
8380 serializer.attribute(null, "old", e.getValue());
8381 serializer.endTag(null, "renamed-package");
8382 }
8383 }
8384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008385 serializer.endTag(null, "packages");
8386
8387 serializer.endDocument();
8388
8389 str.flush();
8390 str.close();
8391
8392 // New settings successfully written, old ones are no longer
8393 // needed.
8394 mBackupSettingsFilename.delete();
8395 FileUtils.setPermissions(mSettingsFilename.toString(),
8396 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8397 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8398 |FileUtils.S_IROTH,
8399 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008400
8401 // Write package list file now, use a JournaledFile.
8402 //
8403 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8404 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8405
Kenny Root9f306d72010-09-26 11:19:47 -07008406 str = new BufferedOutputStream(new FileOutputStream(journal.chooseForWrite()));
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008407 try {
8408 StringBuilder sb = new StringBuilder();
8409 for (PackageSetting pkg : mPackages.values()) {
8410 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008411 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008412 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8413
8414 // Avoid any application that has a space in its path
8415 // or that is handled by the system.
8416 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8417 continue;
8418
8419 // we store on each line the following information for now:
8420 //
8421 // pkgName - package name
8422 // userId - application-specific user id
8423 // debugFlag - 0 or 1 if the package is debuggable.
8424 // dataPath - path to package's data path
8425 //
8426 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8427 //
8428 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8429 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8430 // system/core/run-as/run-as.c
8431 //
8432 sb.setLength(0);
8433 sb.append(ai.packageName);
8434 sb.append(" ");
8435 sb.append((int)ai.uid);
8436 sb.append(isDebug ? " 1 " : " 0 ");
8437 sb.append(dataPath);
8438 sb.append("\n");
8439 str.write(sb.toString().getBytes());
8440 }
8441 str.flush();
8442 str.close();
8443 journal.commit();
8444 }
8445 catch (Exception e) {
8446 journal.rollback();
8447 }
8448
8449 FileUtils.setPermissions(mPackageListFilename.toString(),
8450 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8451 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8452 |FileUtils.S_IROTH,
8453 -1, -1);
8454
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008455 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456
8457 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008458 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 -08008459 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008460 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 -08008461 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008462 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008463 if (mSettingsFilename.exists()) {
8464 if (!mSettingsFilename.delete()) {
8465 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8466 }
8467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008468 //Debug.stopMethodTracing();
8469 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008470
8471 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008472 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008473 serializer.startTag(null, "updated-package");
8474 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008475 if (pkg.realName != null) {
8476 serializer.attribute(null, "realName", pkg.realName);
8477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 serializer.attribute(null, "codePath", pkg.codePathString);
Kenny Root7d794fb2010-09-13 16:29:49 -07008479 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008480 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8482 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8483 }
Kenny Root85387d72010-08-26 10:13:11 -07008484 if (pkg.nativeLibraryPathString != null) {
8485 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008487 if (pkg.sharedUser == null) {
8488 serializer.attribute(null, "userId",
8489 Integer.toString(pkg.userId));
8490 } else {
8491 serializer.attribute(null, "sharedUserId",
8492 Integer.toString(pkg.userId));
8493 }
8494 serializer.startTag(null, "perms");
8495 if (pkg.sharedUser == null) {
8496 // If this is a shared user, the permissions will
8497 // be written there. We still need to write an
8498 // empty permissions list so permissionsFixed will
8499 // be set.
8500 for (final String name : pkg.grantedPermissions) {
8501 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008502 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 // We only need to write signature or system permissions but this wont
8504 // match the semantics of grantedPermissions. So write all permissions.
8505 serializer.startTag(null, "item");
8506 serializer.attribute(null, "name", name);
8507 serializer.endTag(null, "item");
8508 }
8509 }
8510 }
8511 serializer.endTag(null, "perms");
8512 serializer.endTag(null, "updated-package");
8513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008514
8515 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008516 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 serializer.startTag(null, "package");
8518 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008519 if (pkg.realName != null) {
8520 serializer.attribute(null, "realName", pkg.realName);
8521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008522 serializer.attribute(null, "codePath", pkg.codePathString);
8523 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8524 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8525 }
Kenny Root85387d72010-08-26 10:13:11 -07008526 if (pkg.nativeLibraryPathString != null) {
8527 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8528 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008529 serializer.attribute(null, "flags",
8530 Integer.toString(pkg.pkgFlags));
Kenny Root7d794fb2010-09-13 16:29:49 -07008531 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008532 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 if (pkg.sharedUser == null) {
8534 serializer.attribute(null, "userId",
8535 Integer.toString(pkg.userId));
8536 } else {
8537 serializer.attribute(null, "sharedUserId",
8538 Integer.toString(pkg.userId));
8539 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008540 if (pkg.uidError) {
8541 serializer.attribute(null, "uidError", "true");
8542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8544 serializer.attribute(null, "enabled",
8545 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8546 ? "true" : "false");
8547 }
8548 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8549 serializer.attribute(null, "installStatus", "false");
8550 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008551 if (pkg.installerPackageName != null) {
8552 serializer.attribute(null, "installer", pkg.installerPackageName);
8553 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008554 if (pkg.obbPathString != null) {
8555 serializer.attribute(null, "obbPath", pkg.obbPathString);
8556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008557 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8558 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8559 serializer.startTag(null, "perms");
8560 if (pkg.sharedUser == null) {
8561 // If this is a shared user, the permissions will
8562 // be written there. We still need to write an
8563 // empty permissions list so permissionsFixed will
8564 // be set.
8565 for (final String name : pkg.grantedPermissions) {
8566 serializer.startTag(null, "item");
8567 serializer.attribute(null, "name", name);
8568 serializer.endTag(null, "item");
8569 }
8570 }
8571 serializer.endTag(null, "perms");
8572 }
8573 if (pkg.disabledComponents.size() > 0) {
8574 serializer.startTag(null, "disabled-components");
8575 for (final String name : pkg.disabledComponents) {
8576 serializer.startTag(null, "item");
8577 serializer.attribute(null, "name", name);
8578 serializer.endTag(null, "item");
8579 }
8580 serializer.endTag(null, "disabled-components");
8581 }
8582 if (pkg.enabledComponents.size() > 0) {
8583 serializer.startTag(null, "enabled-components");
8584 for (final String name : pkg.enabledComponents) {
8585 serializer.startTag(null, "item");
8586 serializer.attribute(null, "name", name);
8587 serializer.endTag(null, "item");
8588 }
8589 serializer.endTag(null, "enabled-components");
8590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 serializer.endTag(null, "package");
8593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 void writePermission(XmlSerializer serializer, BasePermission bp)
8596 throws XmlPullParserException, java.io.IOException {
8597 if (bp.type != BasePermission.TYPE_BUILTIN
8598 && bp.sourcePackage != null) {
8599 serializer.startTag(null, "item");
8600 serializer.attribute(null, "name", bp.name);
8601 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008602 if (bp.protectionLevel !=
8603 PermissionInfo.PROTECTION_NORMAL) {
8604 serializer.attribute(null, "protection",
8605 Integer.toString(bp.protectionLevel));
8606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008607 if (DEBUG_SETTINGS) Log.v(TAG,
8608 "Writing perm: name=" + bp.name + " type=" + bp.type);
8609 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8610 PermissionInfo pi = bp.perm != null ? bp.perm.info
8611 : bp.pendingInfo;
8612 if (pi != null) {
8613 serializer.attribute(null, "type", "dynamic");
8614 if (pi.icon != 0) {
8615 serializer.attribute(null, "icon",
8616 Integer.toString(pi.icon));
8617 }
8618 if (pi.nonLocalizedLabel != null) {
8619 serializer.attribute(null, "label",
8620 pi.nonLocalizedLabel.toString());
8621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 }
8623 }
8624 serializer.endTag(null, "item");
8625 }
8626 }
8627
8628 String getReadMessagesLP() {
8629 return mReadMessages.toString();
8630 }
8631
Oscar Montemayora8529f62009-11-18 10:14:20 -08008632 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008633 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8634 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008635 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636 while(its.hasNext()) {
8637 String key = its.next();
8638 PackageSetting ps = mPackages.get(key);
8639 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008640 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 }
8642 }
8643 return ret;
8644 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 boolean readLP() {
8647 FileInputStream str = null;
8648 if (mBackupSettingsFilename.exists()) {
8649 try {
8650 str = new FileInputStream(mBackupSettingsFilename);
8651 mReadMessages.append("Reading from backup settings file\n");
8652 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008653 if (mSettingsFilename.exists()) {
8654 // If both the backup and settings file exist, we
8655 // ignore the settings since it might have been
8656 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008657 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008658 mSettingsFilename.delete();
8659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008660 } catch (java.io.IOException e) {
8661 // We'll try for the normal settings file.
8662 }
8663 }
8664
8665 mPastSignatures.clear();
8666
8667 try {
8668 if (str == null) {
8669 if (!mSettingsFilename.exists()) {
8670 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008671 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008672 return false;
8673 }
8674 str = new FileInputStream(mSettingsFilename);
8675 }
8676 XmlPullParser parser = Xml.newPullParser();
8677 parser.setInput(str, null);
8678
8679 int type;
8680 while ((type=parser.next()) != XmlPullParser.START_TAG
8681 && type != XmlPullParser.END_DOCUMENT) {
8682 ;
8683 }
8684
8685 if (type != XmlPullParser.START_TAG) {
8686 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008687 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 return false;
8689 }
8690
8691 int outerDepth = parser.getDepth();
8692 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8693 && (type != XmlPullParser.END_TAG
8694 || parser.getDepth() > outerDepth)) {
8695 if (type == XmlPullParser.END_TAG
8696 || type == XmlPullParser.TEXT) {
8697 continue;
8698 }
8699
8700 String tagName = parser.getName();
8701 if (tagName.equals("package")) {
8702 readPackageLP(parser);
8703 } else if (tagName.equals("permissions")) {
8704 readPermissionsLP(mPermissions, parser);
8705 } else if (tagName.equals("permission-trees")) {
8706 readPermissionsLP(mPermissionTrees, parser);
8707 } else if (tagName.equals("shared-user")) {
8708 readSharedUserLP(parser);
8709 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008710 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 } else if (tagName.equals("preferred-activities")) {
8712 readPreferredActivitiesLP(parser);
8713 } else if(tagName.equals("updated-package")) {
8714 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008715 } else if (tagName.equals("cleaning-package")) {
8716 String name = parser.getAttributeValue(null, "name");
8717 if (name != null) {
8718 mPackagesToBeCleaned.add(name);
8719 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008720 } else if (tagName.equals("renamed-package")) {
8721 String nname = parser.getAttributeValue(null, "new");
8722 String oname = parser.getAttributeValue(null, "old");
8723 if (nname != null && oname != null) {
8724 mRenamedPackages.put(nname, oname);
8725 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008726 } else if (tagName.equals("last-platform-version")) {
8727 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8728 try {
8729 String internal = parser.getAttributeValue(null, "internal");
8730 if (internal != null) {
8731 mInternalSdkPlatform = Integer.parseInt(internal);
8732 }
8733 String external = parser.getAttributeValue(null, "external");
8734 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008735 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008736 }
8737 } catch (NumberFormatException e) {
8738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008740 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008741 + parser.getName());
8742 XmlUtils.skipCurrentTag(parser);
8743 }
8744 }
8745
8746 str.close();
8747
8748 } catch(XmlPullParserException e) {
8749 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008750 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008751
8752 } catch(java.io.IOException e) {
8753 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008754 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008755
8756 }
8757
8758 int N = mPendingPackages.size();
8759 for (int i=0; i<N; i++) {
8760 final PendingPackage pp = mPendingPackages.get(i);
8761 Object idObj = getUserIdLP(pp.sharedId);
8762 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008763 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008764 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8765 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008767 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768 + pp.name);
8769 continue;
8770 }
8771 p.copyFrom(pp);
8772 } else if (idObj != null) {
8773 String msg = "Bad package setting: package " + pp.name
8774 + " has shared uid " + pp.sharedId
8775 + " that is not a shared uid\n";
8776 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008777 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778 } else {
8779 String msg = "Bad package setting: package " + pp.name
8780 + " has shared uid " + pp.sharedId
8781 + " that is not defined\n";
8782 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008783 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008784 }
8785 }
8786 mPendingPackages.clear();
8787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 mReadMessages.append("Read completed successfully: "
8789 + mPackages.size() + " packages, "
8790 + mSharedUsers.size() + " shared uids\n");
8791
8792 return true;
8793 }
8794
8795 private int readInt(XmlPullParser parser, String ns, String name,
8796 int defValue) {
8797 String v = parser.getAttributeValue(ns, name);
8798 try {
8799 if (v == null) {
8800 return defValue;
8801 }
8802 return Integer.parseInt(v);
8803 } catch (NumberFormatException e) {
8804 reportSettingsProblem(Log.WARN,
8805 "Error in package manager settings: attribute " +
8806 name + " has bad integer value " + v + " at "
8807 + parser.getPositionDescription());
8808 }
8809 return defValue;
8810 }
8811
8812 private void readPermissionsLP(HashMap<String, BasePermission> out,
8813 XmlPullParser parser)
8814 throws IOException, XmlPullParserException {
8815 int outerDepth = parser.getDepth();
8816 int type;
8817 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8818 && (type != XmlPullParser.END_TAG
8819 || parser.getDepth() > outerDepth)) {
8820 if (type == XmlPullParser.END_TAG
8821 || type == XmlPullParser.TEXT) {
8822 continue;
8823 }
8824
8825 String tagName = parser.getName();
8826 if (tagName.equals("item")) {
8827 String name = parser.getAttributeValue(null, "name");
8828 String sourcePackage = parser.getAttributeValue(null, "package");
8829 String ptype = parser.getAttributeValue(null, "type");
8830 if (name != null && sourcePackage != null) {
8831 boolean dynamic = "dynamic".equals(ptype);
8832 BasePermission bp = new BasePermission(name, sourcePackage,
8833 dynamic
8834 ? BasePermission.TYPE_DYNAMIC
8835 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008836 bp.protectionLevel = readInt(parser, null, "protection",
8837 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008838 if (dynamic) {
8839 PermissionInfo pi = new PermissionInfo();
8840 pi.packageName = sourcePackage.intern();
8841 pi.name = name.intern();
8842 pi.icon = readInt(parser, null, "icon", 0);
8843 pi.nonLocalizedLabel = parser.getAttributeValue(
8844 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008845 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008846 bp.pendingInfo = pi;
8847 }
8848 out.put(bp.name, bp);
8849 } else {
8850 reportSettingsProblem(Log.WARN,
8851 "Error in package manager settings: permissions has"
8852 + " no name at " + parser.getPositionDescription());
8853 }
8854 } else {
8855 reportSettingsProblem(Log.WARN,
8856 "Unknown element reading permissions: "
8857 + parser.getName() + " at "
8858 + parser.getPositionDescription());
8859 }
8860 XmlUtils.skipCurrentTag(parser);
8861 }
8862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008865 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008867 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868 String codePathStr = parser.getAttributeValue(null, "codePath");
8869 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07008870 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008871 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008872 resourcePathStr = codePathStr;
8873 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008874 String version = parser.getAttributeValue(null, "version");
8875 int versionCode = 0;
8876 if (version != null) {
8877 try {
8878 versionCode = Integer.parseInt(version);
8879 } catch (NumberFormatException e) {
8880 }
8881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 int pkgFlags = 0;
8884 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07008885 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
8886 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887 String timeStampStr = parser.getAttributeValue(null, "ts");
8888 if (timeStampStr != null) {
8889 try {
8890 long timeStamp = Long.parseLong(timeStampStr);
Kenny Root7d794fb2010-09-13 16:29:49 -07008891 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 } catch (NumberFormatException e) {
8893 }
8894 }
8895 String idStr = parser.getAttributeValue(null, "userId");
8896 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8897 if(ps.userId <= 0) {
8898 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8899 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8900 }
8901 int outerDepth = parser.getDepth();
8902 int type;
8903 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8904 && (type != XmlPullParser.END_TAG
8905 || parser.getDepth() > outerDepth)) {
8906 if (type == XmlPullParser.END_TAG
8907 || type == XmlPullParser.TEXT) {
8908 continue;
8909 }
8910
8911 String tagName = parser.getName();
8912 if (tagName.equals("perms")) {
8913 readGrantedPermissionsLP(parser,
8914 ps.grantedPermissions);
8915 } else {
8916 reportSettingsProblem(Log.WARN,
8917 "Unknown element under <updated-package>: "
8918 + parser.getName());
8919 XmlUtils.skipCurrentTag(parser);
8920 }
8921 }
8922 mDisabledSysPackages.put(name, ps);
8923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008925 private void readPackageLP(XmlPullParser parser)
8926 throws XmlPullParserException, IOException {
8927 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008928 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008929 String idStr = null;
8930 String sharedIdStr = null;
8931 String codePathStr = null;
8932 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07008933 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07008934 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008936 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008937 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008939 long timeStamp = 0;
8940 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008941 String version = null;
8942 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 try {
8944 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008945 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008947 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008948 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8949 codePathStr = parser.getAttributeValue(null, "codePath");
8950 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07008951 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07008952 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008953 version = parser.getAttributeValue(null, "version");
8954 if (version != null) {
8955 try {
8956 versionCode = Integer.parseInt(version);
8957 } catch (NumberFormatException e) {
8958 }
8959 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008960 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008961
8962 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008963 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008964 try {
8965 pkgFlags = Integer.parseInt(systemStr);
8966 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008967 }
8968 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008969 // For backward compatibility
8970 systemStr = parser.getAttributeValue(null, "system");
8971 if (systemStr != null) {
8972 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8973 } else {
8974 // Old settings that don't specify system... just treat
8975 // them as system, good enough.
8976 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008978 }
Kenny Root7d794fb2010-09-13 16:29:49 -07008979 final String timeStampStr = parser.getAttributeValue(null, "ts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008980 if (timeStampStr != null) {
8981 try {
8982 timeStamp = Long.parseLong(timeStampStr);
8983 } catch (NumberFormatException e) {
8984 }
8985 }
8986 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8987 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8988 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8989 if (resourcePathStr == null) {
8990 resourcePathStr = codePathStr;
8991 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008992 if (realName != null) {
8993 realName = realName.intern();
8994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008995 if (name == null) {
8996 reportSettingsProblem(Log.WARN,
8997 "Error in package manager settings: <package> has no name at "
8998 + parser.getPositionDescription());
8999 } else if (codePathStr == null) {
9000 reportSettingsProblem(Log.WARN,
9001 "Error in package manager settings: <package> has no codePath at "
9002 + parser.getPositionDescription());
9003 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009004 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9005 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9006 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009007 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9008 + ": userId=" + userId + " pkg=" + packageSetting);
9009 if (packageSetting == null) {
9010 reportSettingsProblem(Log.ERROR,
9011 "Failure adding uid " + userId
9012 + " while parsing settings at "
9013 + parser.getPositionDescription());
9014 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009015 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 }
9017 } else if (sharedIdStr != null) {
9018 userId = sharedIdStr != null
9019 ? Integer.parseInt(sharedIdStr) : 0;
9020 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009021 packageSetting = new PendingPackage(name.intern(), realName,
9022 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009023 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009024 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 mPendingPackages.add((PendingPackage) packageSetting);
9026 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9027 + ": sharedUserId=" + userId + " pkg="
9028 + packageSetting);
9029 } else {
9030 reportSettingsProblem(Log.WARN,
9031 "Error in package manager settings: package "
9032 + name + " has bad sharedId " + sharedIdStr
9033 + " at " + parser.getPositionDescription());
9034 }
9035 } else {
9036 reportSettingsProblem(Log.WARN,
9037 "Error in package manager settings: package "
9038 + name + " has bad userId " + idStr + " at "
9039 + parser.getPositionDescription());
9040 }
9041 } catch (NumberFormatException e) {
9042 reportSettingsProblem(Log.WARN,
9043 "Error in package manager settings: package "
9044 + name + " has bad userId " + idStr + " at "
9045 + parser.getPositionDescription());
9046 }
9047 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009048 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009049 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009050 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009051 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009052 final String enabledStr = parser.getAttributeValue(null, "enabled");
9053 if (enabledStr != null) {
9054 if (enabledStr.equalsIgnoreCase("true")) {
9055 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9056 } else if (enabledStr.equalsIgnoreCase("false")) {
9057 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9058 } else if (enabledStr.equalsIgnoreCase("default")) {
9059 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9060 } else {
9061 reportSettingsProblem(Log.WARN,
9062 "Error in package manager settings: package "
9063 + name + " has bad enabled value: " + idStr
9064 + " at " + parser.getPositionDescription());
9065 }
9066 } else {
9067 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9068 }
9069 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9070 if (installStatusStr != null) {
9071 if (installStatusStr.equalsIgnoreCase("false")) {
9072 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9073 } else {
9074 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9075 }
9076 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009078 int outerDepth = parser.getDepth();
9079 int type;
9080 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9081 && (type != XmlPullParser.END_TAG
9082 || parser.getDepth() > outerDepth)) {
9083 if (type == XmlPullParser.END_TAG
9084 || type == XmlPullParser.TEXT) {
9085 continue;
9086 }
9087
9088 String tagName = parser.getName();
9089 if (tagName.equals("disabled-components")) {
9090 readDisabledComponentsLP(packageSetting, parser);
9091 } else if (tagName.equals("enabled-components")) {
9092 readEnabledComponentsLP(packageSetting, parser);
9093 } else if (tagName.equals("sigs")) {
9094 packageSetting.signatures.readXml(parser, mPastSignatures);
9095 } else if (tagName.equals("perms")) {
9096 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009097 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009098 packageSetting.permissionsFixed = true;
9099 } else {
9100 reportSettingsProblem(Log.WARN,
9101 "Unknown element under <package>: "
9102 + parser.getName());
9103 XmlUtils.skipCurrentTag(parser);
9104 }
9105 }
9106 } else {
9107 XmlUtils.skipCurrentTag(parser);
9108 }
9109 }
9110
9111 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9112 XmlPullParser parser)
9113 throws IOException, XmlPullParserException {
9114 int outerDepth = parser.getDepth();
9115 int type;
9116 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9117 && (type != XmlPullParser.END_TAG
9118 || parser.getDepth() > outerDepth)) {
9119 if (type == XmlPullParser.END_TAG
9120 || type == XmlPullParser.TEXT) {
9121 continue;
9122 }
9123
9124 String tagName = parser.getName();
9125 if (tagName.equals("item")) {
9126 String name = parser.getAttributeValue(null, "name");
9127 if (name != null) {
9128 packageSetting.disabledComponents.add(name.intern());
9129 } else {
9130 reportSettingsProblem(Log.WARN,
9131 "Error in package manager settings: <disabled-components> has"
9132 + " no name at " + parser.getPositionDescription());
9133 }
9134 } else {
9135 reportSettingsProblem(Log.WARN,
9136 "Unknown element under <disabled-components>: "
9137 + parser.getName());
9138 }
9139 XmlUtils.skipCurrentTag(parser);
9140 }
9141 }
9142
9143 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9144 XmlPullParser parser)
9145 throws IOException, XmlPullParserException {
9146 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("item")) {
9158 String name = parser.getAttributeValue(null, "name");
9159 if (name != null) {
9160 packageSetting.enabledComponents.add(name.intern());
9161 } else {
9162 reportSettingsProblem(Log.WARN,
9163 "Error in package manager settings: <enabled-components> has"
9164 + " no name at " + parser.getPositionDescription());
9165 }
9166 } else {
9167 reportSettingsProblem(Log.WARN,
9168 "Unknown element under <enabled-components>: "
9169 + parser.getName());
9170 }
9171 XmlUtils.skipCurrentTag(parser);
9172 }
9173 }
9174
9175 private void readSharedUserLP(XmlPullParser parser)
9176 throws XmlPullParserException, IOException {
9177 String name = null;
9178 String idStr = null;
9179 int pkgFlags = 0;
9180 SharedUserSetting su = null;
9181 try {
9182 name = parser.getAttributeValue(null, "name");
9183 idStr = parser.getAttributeValue(null, "userId");
9184 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9185 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9186 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9187 }
9188 if (name == null) {
9189 reportSettingsProblem(Log.WARN,
9190 "Error in package manager settings: <shared-user> has no name at "
9191 + parser.getPositionDescription());
9192 } else if (userId == 0) {
9193 reportSettingsProblem(Log.WARN,
9194 "Error in package manager settings: shared-user "
9195 + name + " has bad userId " + idStr + " at "
9196 + parser.getPositionDescription());
9197 } else {
9198 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9199 reportSettingsProblem(Log.ERROR,
9200 "Occurred while parsing settings at "
9201 + parser.getPositionDescription());
9202 }
9203 }
9204 } catch (NumberFormatException e) {
9205 reportSettingsProblem(Log.WARN,
9206 "Error in package manager settings: package "
9207 + name + " has bad userId " + idStr + " at "
9208 + parser.getPositionDescription());
9209 };
9210
9211 if (su != null) {
9212 int outerDepth = parser.getDepth();
9213 int type;
9214 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9215 && (type != XmlPullParser.END_TAG
9216 || parser.getDepth() > outerDepth)) {
9217 if (type == XmlPullParser.END_TAG
9218 || type == XmlPullParser.TEXT) {
9219 continue;
9220 }
9221
9222 String tagName = parser.getName();
9223 if (tagName.equals("sigs")) {
9224 su.signatures.readXml(parser, mPastSignatures);
9225 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009226 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009227 } else {
9228 reportSettingsProblem(Log.WARN,
9229 "Unknown element under <shared-user>: "
9230 + parser.getName());
9231 XmlUtils.skipCurrentTag(parser);
9232 }
9233 }
9234
9235 } else {
9236 XmlUtils.skipCurrentTag(parser);
9237 }
9238 }
9239
9240 private void readGrantedPermissionsLP(XmlPullParser parser,
9241 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9242 int outerDepth = parser.getDepth();
9243 int type;
9244 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9245 && (type != XmlPullParser.END_TAG
9246 || parser.getDepth() > outerDepth)) {
9247 if (type == XmlPullParser.END_TAG
9248 || type == XmlPullParser.TEXT) {
9249 continue;
9250 }
9251
9252 String tagName = parser.getName();
9253 if (tagName.equals("item")) {
9254 String name = parser.getAttributeValue(null, "name");
9255 if (name != null) {
9256 outPerms.add(name.intern());
9257 } else {
9258 reportSettingsProblem(Log.WARN,
9259 "Error in package manager settings: <perms> has"
9260 + " no name at " + parser.getPositionDescription());
9261 }
9262 } else {
9263 reportSettingsProblem(Log.WARN,
9264 "Unknown element under <perms>: "
9265 + parser.getName());
9266 }
9267 XmlUtils.skipCurrentTag(parser);
9268 }
9269 }
9270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009271 private void readPreferredActivitiesLP(XmlPullParser parser)
9272 throws XmlPullParserException, IOException {
9273 int outerDepth = parser.getDepth();
9274 int type;
9275 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9276 && (type != XmlPullParser.END_TAG
9277 || parser.getDepth() > outerDepth)) {
9278 if (type == XmlPullParser.END_TAG
9279 || type == XmlPullParser.TEXT) {
9280 continue;
9281 }
9282
9283 String tagName = parser.getName();
9284 if (tagName.equals("item")) {
9285 PreferredActivity pa = new PreferredActivity(parser);
9286 if (pa.mParseError == null) {
9287 mPreferredActivities.addFilter(pa);
9288 } else {
9289 reportSettingsProblem(Log.WARN,
9290 "Error in package manager settings: <preferred-activity> "
9291 + pa.mParseError + " at "
9292 + parser.getPositionDescription());
9293 }
9294 } else {
9295 reportSettingsProblem(Log.WARN,
9296 "Unknown element under <preferred-activities>: "
9297 + parser.getName());
9298 XmlUtils.skipCurrentTag(parser);
9299 }
9300 }
9301 }
9302
9303 // Returns -1 if we could not find an available UserId to assign
9304 private int newUserIdLP(Object obj) {
9305 // Let's be stupidly inefficient for now...
9306 final int N = mUserIds.size();
9307 for (int i=0; i<N; i++) {
9308 if (mUserIds.get(i) == null) {
9309 mUserIds.set(i, obj);
9310 return FIRST_APPLICATION_UID + i;
9311 }
9312 }
9313
9314 // None left?
9315 if (N >= MAX_APPLICATION_UIDS) {
9316 return -1;
9317 }
9318
9319 mUserIds.add(obj);
9320 return FIRST_APPLICATION_UID + N;
9321 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009323 public PackageSetting getDisabledSystemPkg(String name) {
9324 synchronized(mPackages) {
9325 PackageSetting ps = mDisabledSysPackages.get(name);
9326 return ps;
9327 }
9328 }
9329
9330 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009331 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9332 return true;
9333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009334 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9335 if (Config.LOGV) {
9336 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9337 + " componentName = " + componentInfo.name);
9338 Log.v(TAG, "enabledComponents: "
9339 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9340 Log.v(TAG, "disabledComponents: "
9341 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9342 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009343 if (packageSettings == null) {
9344 if (false) {
9345 Log.w(TAG, "WAITING FOR DEBUGGER");
9346 Debug.waitForDebugger();
9347 Log.i(TAG, "We will crash!");
9348 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009349 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009350 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009351 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9352 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9353 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9354 return false;
9355 }
9356 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9357 return true;
9358 }
9359 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9360 return false;
9361 }
9362 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009363 }
9364 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009365
9366 // ------- apps on sdcard specific code -------
9367 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009368 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9369 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9370 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009371 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009372
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009373 private String getEncryptKey() {
9374 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009375 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9376 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009377 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009378 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9379 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009380 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009381 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009382 return null;
9383 }
9384 }
9385 return sdEncKey;
9386 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009387 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009388 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009389 } catch (IOException ioe) {
9390 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9391 + ioe);
9392 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009393 }
Rich Cannings8d578832010-09-09 15:12:40 -07009394
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009395 }
9396
Kenny Rootc78a8072010-07-27 15:18:38 -07009397 /* package */ static String getTempContainerId() {
9398 int tmpIdx = 1;
9399 String list[] = PackageHelper.getSecureContainerList();
9400 if (list != null) {
9401 for (final String name : list) {
9402 // Ignore null and non-temporary container entries
9403 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9404 continue;
9405 }
9406
9407 String subStr = name.substring(mTempContainerPrefix.length());
9408 try {
9409 int cid = Integer.parseInt(subStr);
9410 if (cid >= tmpIdx) {
9411 tmpIdx = cid + 1;
9412 }
9413 } catch (NumberFormatException e) {
9414 }
9415 }
9416 }
9417 return mTempContainerPrefix + tmpIdx;
9418 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009419
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009420 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009421 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009422 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009423 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9424 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9425 throw new SecurityException("Media status can only be updated by the system");
9426 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009427 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009428 Log.i(TAG, "Updating external media status from " +
9429 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9430 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009431 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9432 mediaStatus+", mMediaMounted=" + mMediaMounted);
9433 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009434 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9435 reportStatus ? 1 : 0, -1);
9436 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009437 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009438 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009439 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009440 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009441 // Queue up an async operation since the package installation may take a little while.
9442 mHandler.post(new Runnable() {
9443 public void run() {
9444 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009445 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009446 }
9447 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009448 }
9449
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009450 /*
9451 * Collect information of applications on external media, map them
9452 * against existing containers and update information based on current
9453 * mount status. Please note that we always have to report status
9454 * if reportStatus has been set to true especially when unloading packages.
9455 */
9456 private void updateExternalMediaStatusInner(boolean mediaStatus,
9457 boolean reportStatus) {
9458 // Collection of uids
9459 int uidArr[] = null;
9460 // Collection of stale containers
9461 HashSet<String> removeCids = new HashSet<String>();
9462 // Collection of packages on external media with valid containers.
9463 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9464 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009465 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009466 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009467 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009468 } else {
9469 // Process list of secure containers and categorize them
9470 // as active or stale based on their package internal state.
9471 int uidList[] = new int[list.length];
9472 int num = 0;
9473 synchronized (mPackages) {
9474 for (String cid : list) {
9475 SdInstallArgs args = new SdInstallArgs(cid);
9476 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009477 String pkgName = args.getPackageName();
9478 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009479 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9480 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009481 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009482 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009483 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9484 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009485 // The package status is changed only if the code path
9486 // matches between settings and the container id.
9487 if (ps != null && ps.codePathString != null &&
9488 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009489 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9490 " corresponds to pkg : " + pkgName +
9491 " at code path: " + ps.codePathString);
9492 // We do have a valid package installed on sdcard
9493 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009494 int uid = ps.userId;
9495 if (uid != -1) {
9496 uidList[num++] = uid;
9497 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009498 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009499 // Stale container on sdcard. Just delete
9500 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9501 removeCids.add(cid);
9502 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009503 }
9504 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009505
9506 if (num > 0) {
9507 // Sort uid list
9508 Arrays.sort(uidList, 0, num);
9509 // Throw away duplicates
9510 uidArr = new int[num];
9511 uidArr[0] = uidList[0];
9512 int di = 0;
9513 for (int i = 1; i < num; i++) {
9514 if (uidList[i-1] != uidList[i]) {
9515 uidArr[di++] = uidList[i];
9516 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009517 }
9518 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009519 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009520 // Process packages with valid entries.
9521 if (mediaStatus) {
9522 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009523 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009524 startCleaningPackages();
9525 } else {
9526 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009527 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009528 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009529 }
9530
9531 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009532 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009533 int size = pkgList.size();
9534 if (size > 0) {
9535 // Send broadcasts here
9536 Bundle extras = new Bundle();
9537 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9538 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009539 if (uidArr != null) {
9540 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9541 }
9542 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9543 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009544 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009545 }
9546 }
9547
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009548 /*
9549 * Look at potentially valid container ids from processCids
9550 * If package information doesn't match the one on record
9551 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009552 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009553 */
9554 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009555 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009556 ArrayList<String> pkgList = new ArrayList<String>();
9557 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009558 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009559 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009560 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009561 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9562 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009563 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009564 try {
9565 // Make sure there are no container errors first.
9566 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9567 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009568 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009569 " when installing from sdcard");
9570 continue;
9571 }
9572 // Check code path here.
9573 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009574 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009575 " does not match one in settings " + codePath);
9576 continue;
9577 }
9578 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009579 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009580 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009581 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009582 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9583 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009584 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009585 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009586 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009587 retCode = PackageManager.INSTALL_SUCCEEDED;
9588 pkgList.add(pkg.packageName);
9589 // Post process args
9590 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9591 }
9592 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009593 Slog.i(TAG, "Failed to install pkg from " +
9594 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009595 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009596 }
9597
9598 } finally {
9599 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9600 // Don't destroy container here. Wait till gc clears things up.
9601 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009602 }
9603 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009604 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009605 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009606 // If the platform SDK has changed since the last time we booted,
9607 // we need to re-grant app permission to catch any new ones that
9608 // appear. This is really a hack, and means that apps can in some
9609 // cases get permissions that the user didn't initially explicitly
9610 // allow... it would be nice to have some better way to handle
9611 // this situation.
9612 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9613 != mSdkVersion;
9614 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9615 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9616 + "; regranting permissions for external storage");
9617 mSettings.mExternalSdkPlatform = mSdkVersion;
9618
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009619 // Make sure group IDs have been assigned, and any permission
9620 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009621 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009622 // Persist settings
9623 mSettings.writeLP();
9624 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009625 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009626 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009627 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009628 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009629 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009630 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009631 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009632 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009633 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009634 if (removeCids != null) {
9635 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009636 if (cid.startsWith(mTempContainerPrefix)) {
9637 Log.i(TAG, "Destroying stale temporary container " + cid);
9638 PackageHelper.destroySdDir(cid);
9639 } else {
9640 Log.w(TAG, "Container " + cid + " is stale");
9641 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009642 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009643 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009644 }
9645
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009646 /*
9647 * Utility method to unload a list of specified containers
9648 */
9649 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9650 // Just unmount all valid containers.
9651 for (SdInstallArgs arg : cidArgs) {
9652 synchronized (mInstallLock) {
9653 arg.doPostDeleteLI(false);
9654 }
9655 }
9656 }
9657
9658 /*
9659 * Unload packages mounted on external media. This involves deleting
9660 * package data from internal structures, sending broadcasts about
9661 * diabled packages, gc'ing to free up references, unmounting all
9662 * secure containers corresponding to packages on external media, and
9663 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9664 * Please note that we always have to post this message if status has
9665 * been requested no matter what.
9666 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009667 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009668 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009669 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009670 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009671 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009672 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009673 for (SdInstallArgs args : keys) {
9674 String cid = args.cid;
9675 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009676 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009677 // Delete package internally
9678 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9679 synchronized (mInstallLock) {
9680 boolean res = deletePackageLI(pkgName, false,
9681 PackageManager.DONT_DELETE_DATA, outInfo);
9682 if (res) {
9683 pkgList.add(pkgName);
9684 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009685 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009686 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009687 }
9688 }
9689 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009690 // We have to absolutely send UPDATED_MEDIA_STATUS only
9691 // after confirming that all the receivers processed the ordered
9692 // broadcast when packages get disabled, force a gc to clean things up.
9693 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009694 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009695 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9696 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9697 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009698 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9699 reportStatus ? 1 : 0, 1, keys);
9700 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009701 }
9702 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009703 } else {
9704 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9705 reportStatus ? 1 : 0, -1, keys);
9706 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009707 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009708 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009709
9710 public void movePackage(final String packageName,
9711 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009712 mContext.enforceCallingOrSelfPermission(
9713 android.Manifest.permission.MOVE_PACKAGE, null);
9714 int returnCode = PackageManager.MOVE_SUCCEEDED;
9715 int currFlags = 0;
9716 int newFlags = 0;
9717 synchronized (mPackages) {
9718 PackageParser.Package pkg = mPackages.get(packageName);
9719 if (pkg == null) {
9720 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009721 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009722 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009723 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009724 Slog.w(TAG, "Cannot move system application");
9725 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009726 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009727 Slog.w(TAG, "Cannot move forward locked app.");
9728 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009729 } else if (pkg.mOperationPending) {
9730 Slog.w(TAG, "Attempt to move package which has pending operations");
9731 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009732 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009733 // Find install location first
9734 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9735 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9736 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009737 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009738 } else {
9739 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9740 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009741 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9742 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009743 if (newFlags == currFlags) {
9744 Slog.w(TAG, "No move required. Trying to move to same location");
9745 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9746 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009747 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009748 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9749 pkg.mOperationPending = true;
9750 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009751 }
9752 }
9753 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009754 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009755 } else {
9756 Message msg = mHandler.obtainMessage(INIT_COPY);
9757 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009758 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9759 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9760 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009761 msg.obj = mp;
9762 mHandler.sendMessage(msg);
9763 }
9764 }
9765 }
9766
9767 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9768 // Queue up an async operation since the package deletion may take a little while.
9769 mHandler.post(new Runnable() {
9770 public void run() {
9771 mHandler.removeCallbacks(this);
9772 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009773 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9774 int uidArr[] = null;
9775 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009776 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009777 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009778 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009779 Slog.w(TAG, " Package " + mp.packageName +
9780 " doesn't exist. Aborting move");
9781 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9782 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9783 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9784 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9785 " Aborting move and returning error");
9786 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9787 } else {
9788 uidArr = new int[] { pkg.applicationInfo.uid };
9789 pkgList = new ArrayList<String>();
9790 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009791 }
9792 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009793 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9794 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009795 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009796 // Update package code and resource paths
9797 synchronized (mInstallLock) {
9798 synchronized (mPackages) {
9799 PackageParser.Package pkg = mPackages.get(mp.packageName);
9800 // Recheck for package again.
9801 if (pkg == null ) {
9802 Slog.w(TAG, " Package " + mp.packageName +
9803 " doesn't exist. Aborting move");
9804 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9805 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9806 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9807 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9808 " Aborting move and returning error");
9809 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9810 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009811 final String oldCodePath = pkg.mPath;
9812 final String newCodePath = mp.targetArgs.getCodePath();
9813 final String newResPath = mp.targetArgs.getResourcePath();
9814 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009815 pkg.mPath = newCodePath;
9816 // Move dex files around
9817 if (moveDexFilesLI(pkg)
9818 != PackageManager.INSTALL_SUCCEEDED) {
9819 // Moving of dex files failed. Set
9820 // error code and abort move.
9821 pkg.mPath = pkg.mScanPath;
9822 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9823 } else {
9824 pkg.mScanPath = newCodePath;
9825 pkg.applicationInfo.sourceDir = newCodePath;
9826 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009827 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009828 PackageSetting ps = (PackageSetting) pkg.mExtras;
9829 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9830 ps.codePathString = ps.codePath.getPath();
9831 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9832 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009833 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009834 // Set the application info flag correctly.
9835 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9836 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9837 } else {
9838 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9839 }
9840 ps.setFlags(pkg.applicationInfo.flags);
9841 mAppDirs.remove(oldCodePath);
9842 mAppDirs.put(newCodePath, pkg);
9843 // Persist settings
9844 mSettings.writeLP();
9845 }
9846 }
9847 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009848 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009849 // Send resources available broadcast
9850 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009851 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009852 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009853 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009854 // Clean up failed installation
9855 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009856 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009857 }
9858 } else {
9859 // Force a gc to clear things up.
9860 Runtime.getRuntime().gc();
9861 // Delete older code
9862 synchronized (mInstallLock) {
9863 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009864 }
9865 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009866
9867 // Allow more operations on this file if we didn't fail because
9868 // an operation was already pending for this package.
9869 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9870 synchronized (mPackages) {
9871 PackageParser.Package pkg = mPackages.get(mp.packageName);
9872 if (pkg != null) {
9873 pkg.mOperationPending = false;
9874 }
9875 }
9876 }
9877
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009878 IPackageMoveObserver observer = mp.observer;
9879 if (observer != null) {
9880 try {
9881 observer.packageMoved(mp.packageName, returnCode);
9882 } catch (RemoteException e) {
9883 Log.i(TAG, "Observer no longer exists.");
9884 }
9885 }
9886 }
9887 });
9888 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009889
9890 public boolean setInstallLocation(int loc) {
9891 mContext.enforceCallingOrSelfPermission(
9892 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9893 if (getInstallLocation() == loc) {
9894 return true;
9895 }
9896 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9897 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9898 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9899 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9900 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9901 return true;
9902 }
9903 return false;
9904 }
9905
9906 public int getInstallLocation() {
9907 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9908 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9909 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009910}