blob: 37b4c1dba3f30c3578ed58c7a71e7294403a5767 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
145 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400146 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 private static final int FIRST_APPLICATION_UID =
148 Process.FIRST_APPLICATION_UID;
149 private static final int MAX_APPLICATION_UIDS = 1000;
150
151 private static final boolean SHOW_INFO = false;
152
153 private static final boolean GET_CERTIFICATES = true;
154
Oscar Montemayora8529f62009-11-18 10:14:20 -0800155 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private static final int REMOVE_EVENTS =
158 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
159 private static final int ADD_EVENTS =
160 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
161
162 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800163 // Suffix used during package installation when copying/moving
164 // package apks to install directory.
165 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800167 /**
168 * Indicates the state of installation. Used by PackageManager to
169 * figure out incomplete installations. Say a package is being installed
170 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
171 * the package installation is successful or unsuccesful lin which case
172 * the PackageManager will no longer maintain state information associated
173 * with the package. If some exception(like device freeze or battery being
174 * pulled out) occurs during installation of a package, the PackageManager
175 * needs this information to clean up the previously failed installation.
176 */
177 private static final int PKG_INSTALL_INCOMPLETE = 0;
178 private static final int PKG_INSTALL_COMPLETE = 1;
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final int SCAN_MONITOR = 1<<0;
181 static final int SCAN_NO_DEX = 1<<1;
182 static final int SCAN_FORCE_DEX = 1<<2;
183 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800184 static final int SCAN_NEW_INSTALL = 1<<4;
185 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700186 static final int SCAN_UPDATE_TIME = 1<<6;
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,
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700925 scanMode | SCAN_NO_DEX, 0);
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
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700933 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
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
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700941 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700942
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();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700988 scanDirLI(mAppInstallDir, 0, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989
990 mDrmAppInstallObserver = new AppDirObserver(
991 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
992 mDrmAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700993 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
994 scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800996 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800998 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1000 + " seconds");
1001
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001002 // If the platform SDK has changed since the last time we booted,
1003 // we need to re-grant app permission to catch any new ones that
1004 // appear. This is really a hack, and means that apps can in some
1005 // cases get permissions that the user didn't initially explicitly
1006 // allow... it would be nice to have some better way to handle
1007 // this situation.
1008 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1009 != mSdkVersion;
1010 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1011 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1012 + "; regranting permissions for internal storage");
1013 mSettings.mInternalSdkPlatform = mSdkVersion;
1014
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001015 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016
1017 mSettings.writeLP();
1018
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001019 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 // Now after opening every single application zip, make sure they
1023 // are all flushed. Not really needed, but keeps things nice and
1024 // tidy.
1025 Runtime.getRuntime().gc();
1026 } // synchronized (mPackages)
1027 } // synchronized (mInstallLock)
1028 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 @Override
1031 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1032 throws RemoteException {
1033 try {
1034 return super.onTransact(code, data, reply, flags);
1035 } catch (RuntimeException e) {
1036 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001037 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039 throw e;
1040 }
1041 }
1042
Dianne Hackborne6620b22010-01-22 14:46:21 -08001043 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001044 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001046 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1047 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001049 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001050 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
1052 } else {
1053 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001054 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 File dataDir = new File(pkg.applicationInfo.dataDir);
1056 dataDir.delete();
1057 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001058 if (ps.codePath != null) {
1059 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001060 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001061 }
1062 }
1063 if (ps.resourcePath != null) {
1064 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001065 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001066 }
1067 }
1068 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
1070
1071 void readPermissions() {
1072 // Read permissions from .../etc/permission directory.
1073 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1074 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001075 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 return;
1077 }
1078 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001079 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 return;
1081 }
1082
1083 // Iterate over the files in the directory and scan .xml files
1084 for (File f : libraryDir.listFiles()) {
1085 // We'll read platform.xml last
1086 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1087 continue;
1088 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001091 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 continue;
1093 }
1094 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001095 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 continue;
1097 }
1098
1099 readPermissionsFromXml(f);
1100 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1103 final File permFile = new File(Environment.getRootDirectory(),
1104 "etc/permissions/platform.xml");
1105 readPermissionsFromXml(permFile);
1106 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001107
1108 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 FileReader permReader = null;
1110 try {
1111 permReader = new FileReader(permFile);
1112 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001113 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 return;
1115 }
1116
1117 try {
1118 XmlPullParser parser = Xml.newPullParser();
1119 parser.setInput(permReader);
1120
1121 XmlUtils.beginDocument(parser, "permissions");
1122
1123 while (true) {
1124 XmlUtils.nextElement(parser);
1125 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1126 break;
1127 }
1128
1129 String name = parser.getName();
1130 if ("group".equals(name)) {
1131 String gidStr = parser.getAttributeValue(null, "gid");
1132 if (gidStr != null) {
1133 int gid = Integer.parseInt(gidStr);
1134 mGlobalGids = appendInt(mGlobalGids, gid);
1135 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001136 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 + parser.getPositionDescription());
1138 }
1139
1140 XmlUtils.skipCurrentTag(parser);
1141 continue;
1142 } else if ("permission".equals(name)) {
1143 String perm = parser.getAttributeValue(null, "name");
1144 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001145 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 + parser.getPositionDescription());
1147 XmlUtils.skipCurrentTag(parser);
1148 continue;
1149 }
1150 perm = perm.intern();
1151 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 } else if ("assign-permission".equals(name)) {
1154 String perm = parser.getAttributeValue(null, "name");
1155 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001156 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 + parser.getPositionDescription());
1158 XmlUtils.skipCurrentTag(parser);
1159 continue;
1160 }
1161 String uidStr = parser.getAttributeValue(null, "uid");
1162 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001163 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 + parser.getPositionDescription());
1165 XmlUtils.skipCurrentTag(parser);
1166 continue;
1167 }
1168 int uid = Process.getUidForName(uidStr);
1169 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001170 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 + uidStr + "\" at "
1172 + parser.getPositionDescription());
1173 XmlUtils.skipCurrentTag(parser);
1174 continue;
1175 }
1176 perm = perm.intern();
1177 HashSet<String> perms = mSystemPermissions.get(uid);
1178 if (perms == null) {
1179 perms = new HashSet<String>();
1180 mSystemPermissions.put(uid, perms);
1181 }
1182 perms.add(perm);
1183 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 } else if ("library".equals(name)) {
1186 String lname = parser.getAttributeValue(null, "name");
1187 String lfile = parser.getAttributeValue(null, "file");
1188 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001189 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 + parser.getPositionDescription());
1191 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001192 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 + parser.getPositionDescription());
1194 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001195 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001196 mSharedLibraries.put(lname, lfile);
1197 }
1198 XmlUtils.skipCurrentTag(parser);
1199 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001200
Dianne Hackborn49237342009-08-27 20:08:01 -07001201 } else if ("feature".equals(name)) {
1202 String fname = parser.getAttributeValue(null, "name");
1203 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001204 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001205 + parser.getPositionDescription());
1206 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001207 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001208 FeatureInfo fi = new FeatureInfo();
1209 fi.name = fname;
1210 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
1212 XmlUtils.skipCurrentTag(parser);
1213 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 } else {
1216 XmlUtils.skipCurrentTag(parser);
1217 continue;
1218 }
1219
1220 }
1221 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001222 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001224 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
1226 }
1227
1228 void readPermission(XmlPullParser parser, String name)
1229 throws IOException, XmlPullParserException {
1230
1231 name = name.intern();
1232
1233 BasePermission bp = mSettings.mPermissions.get(name);
1234 if (bp == null) {
1235 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1236 mSettings.mPermissions.put(name, bp);
1237 }
1238 int outerDepth = parser.getDepth();
1239 int type;
1240 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1241 && (type != XmlPullParser.END_TAG
1242 || parser.getDepth() > outerDepth)) {
1243 if (type == XmlPullParser.END_TAG
1244 || type == XmlPullParser.TEXT) {
1245 continue;
1246 }
1247
1248 String tagName = parser.getName();
1249 if ("group".equals(tagName)) {
1250 String gidStr = parser.getAttributeValue(null, "gid");
1251 if (gidStr != null) {
1252 int gid = Process.getGidForName(gidStr);
1253 bp.gids = appendInt(bp.gids, gid);
1254 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001255 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 + parser.getPositionDescription());
1257 }
1258 }
1259 XmlUtils.skipCurrentTag(parser);
1260 }
1261 }
1262
1263 static int[] appendInt(int[] cur, int val) {
1264 if (cur == null) {
1265 return new int[] { val };
1266 }
1267 final int N = cur.length;
1268 for (int i=0; i<N; i++) {
1269 if (cur[i] == val) {
1270 return cur;
1271 }
1272 }
1273 int[] ret = new int[N+1];
1274 System.arraycopy(cur, 0, ret, 0, N);
1275 ret[N] = val;
1276 return ret;
1277 }
1278
1279 static int[] appendInts(int[] cur, int[] add) {
1280 if (add == null) return cur;
1281 if (cur == null) return add;
1282 final int N = add.length;
1283 for (int i=0; i<N; i++) {
1284 cur = appendInt(cur, add[i]);
1285 }
1286 return cur;
1287 }
1288
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001289 static int[] removeInt(int[] cur, int val) {
1290 if (cur == null) {
1291 return null;
1292 }
1293 final int N = cur.length;
1294 for (int i=0; i<N; i++) {
1295 if (cur[i] == val) {
1296 int[] ret = new int[N-1];
1297 if (i > 0) {
1298 System.arraycopy(cur, 0, ret, 0, i);
1299 }
1300 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001301 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001302 }
1303 return ret;
1304 }
1305 }
1306 return cur;
1307 }
1308
1309 static int[] removeInts(int[] cur, int[] rem) {
1310 if (rem == null) return cur;
1311 if (cur == null) return cur;
1312 final int N = rem.length;
1313 for (int i=0; i<N; i++) {
1314 cur = removeInt(cur, rem[i]);
1315 }
1316 return cur;
1317 }
1318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001320 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1321 // The package has been uninstalled but has retained data and resources.
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001322 return PackageParser.generatePackageInfo(p, null, flags, 0, 0);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 final PackageSetting ps = (PackageSetting)p.mExtras;
1325 if (ps == null) {
1326 return null;
1327 }
1328 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001329 return PackageParser.generatePackageInfo(p, gp.gids, flags,
1330 ps.firstInstallTime, ps.lastUpdateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332
1333 public PackageInfo getPackageInfo(String packageName, int flags) {
1334 synchronized (mPackages) {
1335 PackageParser.Package p = mPackages.get(packageName);
1336 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001337 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 + ": " + p);
1339 if (p != null) {
1340 return generatePackageInfo(p, flags);
1341 }
1342 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1343 return generatePackageInfoFromSettingsLP(packageName, flags);
1344 }
1345 }
1346 return null;
1347 }
1348
Dianne Hackborn47096932010-02-11 15:57:09 -08001349 public String[] currentToCanonicalPackageNames(String[] names) {
1350 String[] out = new String[names.length];
1351 synchronized (mPackages) {
1352 for (int i=names.length-1; i>=0; i--) {
1353 PackageSetting ps = mSettings.mPackages.get(names[i]);
1354 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1355 }
1356 }
1357 return out;
1358 }
1359
1360 public String[] canonicalToCurrentPackageNames(String[] names) {
1361 String[] out = new String[names.length];
1362 synchronized (mPackages) {
1363 for (int i=names.length-1; i>=0; i--) {
1364 String cur = mSettings.mRenamedPackages.get(names[i]);
1365 out[i] = cur != null ? cur : names[i];
1366 }
1367 }
1368 return out;
1369 }
1370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 public int getPackageUid(String packageName) {
1372 synchronized (mPackages) {
1373 PackageParser.Package p = mPackages.get(packageName);
1374 if(p != null) {
1375 return p.applicationInfo.uid;
1376 }
1377 PackageSetting ps = mSettings.mPackages.get(packageName);
1378 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1379 return -1;
1380 }
1381 p = ps.pkg;
1382 return p != null ? p.applicationInfo.uid : -1;
1383 }
1384 }
1385
1386 public int[] getPackageGids(String packageName) {
1387 synchronized (mPackages) {
1388 PackageParser.Package p = mPackages.get(packageName);
1389 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001390 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 + ": " + p);
1392 if (p != null) {
1393 final PackageSetting ps = (PackageSetting)p.mExtras;
1394 final SharedUserSetting suid = ps.sharedUser;
1395 return suid != null ? suid.gids : ps.gids;
1396 }
1397 }
1398 // stupid thing to indicate an error.
1399 return new int[0];
1400 }
1401
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001402 static final PermissionInfo generatePermissionInfo(
1403 BasePermission bp, int flags) {
1404 if (bp.perm != null) {
1405 return PackageParser.generatePermissionInfo(bp.perm, flags);
1406 }
1407 PermissionInfo pi = new PermissionInfo();
1408 pi.name = bp.name;
1409 pi.packageName = bp.sourcePackage;
1410 pi.nonLocalizedLabel = bp.name;
1411 pi.protectionLevel = bp.protectionLevel;
1412 return pi;
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 public PermissionInfo getPermissionInfo(String name, int flags) {
1416 synchronized (mPackages) {
1417 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001418 if (p != null) {
1419 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421 return null;
1422 }
1423 }
1424
1425 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1426 synchronized (mPackages) {
1427 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1428 for (BasePermission p : mSettings.mPermissions.values()) {
1429 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001430 if (p.perm == null || p.perm.info.group == null) {
1431 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
1433 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001434 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1436 }
1437 }
1438 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 if (out.size() > 0) {
1441 return out;
1442 }
1443 return mPermissionGroups.containsKey(group) ? out : null;
1444 }
1445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1448 synchronized (mPackages) {
1449 return PackageParser.generatePermissionGroupInfo(
1450 mPermissionGroups.get(name), flags);
1451 }
1452 }
1453
1454 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1455 synchronized (mPackages) {
1456 final int N = mPermissionGroups.size();
1457 ArrayList<PermissionGroupInfo> out
1458 = new ArrayList<PermissionGroupInfo>(N);
1459 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1460 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1461 }
1462 return out;
1463 }
1464 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1467 PackageSetting ps = mSettings.mPackages.get(packageName);
1468 if(ps != null) {
1469 if(ps.pkg == null) {
1470 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1471 if(pInfo != null) {
1472 return pInfo.applicationInfo;
1473 }
1474 return null;
1475 }
1476 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1477 }
1478 return null;
1479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1482 PackageSetting ps = mSettings.mPackages.get(packageName);
1483 if(ps != null) {
1484 if(ps.pkg == null) {
1485 ps.pkg = new PackageParser.Package(packageName);
1486 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001487 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1488 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1489 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1490 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001491 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001492 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
1494 return generatePackageInfo(ps.pkg, flags);
1495 }
1496 return null;
1497 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1500 synchronized (mPackages) {
1501 PackageParser.Package p = mPackages.get(packageName);
1502 if (Config.LOGV) Log.v(
1503 TAG, "getApplicationInfo " + packageName
1504 + ": " + p);
1505 if (p != null) {
1506 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001507 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
1509 if ("android".equals(packageName)||"system".equals(packageName)) {
1510 return mAndroidApplication;
1511 }
1512 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1513 return generateApplicationInfoFromSettingsLP(packageName, flags);
1514 }
1515 }
1516 return null;
1517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001518
1519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1521 mContext.enforceCallingOrSelfPermission(
1522 android.Manifest.permission.CLEAR_APP_CACHE, null);
1523 // Queue up an async operation since clearing cache may take a little while.
1524 mHandler.post(new Runnable() {
1525 public void run() {
1526 mHandler.removeCallbacks(this);
1527 int retCode = -1;
1528 if (mInstaller != null) {
1529 retCode = mInstaller.freeCache(freeStorageSize);
1530 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001531 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 }
1533 } //end if mInstaller
1534 if (observer != null) {
1535 try {
1536 observer.onRemoveCompleted(null, (retCode >= 0));
1537 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001538 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 }
1541 }
1542 });
1543 }
1544
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001545 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001546 mContext.enforceCallingOrSelfPermission(
1547 android.Manifest.permission.CLEAR_APP_CACHE, null);
1548 // Queue up an async operation since clearing cache may take a little while.
1549 mHandler.post(new Runnable() {
1550 public void run() {
1551 mHandler.removeCallbacks(this);
1552 int retCode = -1;
1553 if (mInstaller != null) {
1554 retCode = mInstaller.freeCache(freeStorageSize);
1555 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001556 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001557 }
1558 }
1559 if(pi != null) {
1560 try {
1561 // Callback via pending intent
1562 int code = (retCode >= 0) ? 1 : 0;
1563 pi.sendIntent(null, code, null,
1564 null, null);
1565 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001566 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001567 }
1568 }
1569 }
1570 });
1571 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1574 synchronized (mPackages) {
1575 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001576
1577 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001579 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
1581 if (mResolveComponentName.equals(component)) {
1582 return mResolveActivity;
1583 }
1584 }
1585 return null;
1586 }
1587
1588 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1589 synchronized (mPackages) {
1590 PackageParser.Activity a = mReceivers.mActivities.get(component);
1591 if (Config.LOGV) Log.v(
1592 TAG, "getReceiverInfo " + component + ": " + a);
1593 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1594 return PackageParser.generateActivityInfo(a, flags);
1595 }
1596 }
1597 return null;
1598 }
1599
1600 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1601 synchronized (mPackages) {
1602 PackageParser.Service s = mServices.mServices.get(component);
1603 if (Config.LOGV) Log.v(
1604 TAG, "getServiceInfo " + component + ": " + s);
1605 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1606 return PackageParser.generateServiceInfo(s, flags);
1607 }
1608 }
1609 return null;
1610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001611
Dianne Hackborn361199b2010-08-30 17:42:07 -07001612 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1613 synchronized (mPackages) {
1614 PackageParser.Provider p = mProvidersByComponent.get(component);
1615 if (Config.LOGV) Log.v(
1616 TAG, "getProviderInfo " + component + ": " + p);
1617 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1618 return PackageParser.generateProviderInfo(p, flags);
1619 }
1620 }
1621 return null;
1622 }
1623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 public String[] getSystemSharedLibraryNames() {
1625 Set<String> libSet;
1626 synchronized (mPackages) {
1627 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001628 int size = libSet.size();
1629 if (size > 0) {
1630 String[] libs = new String[size];
1631 libSet.toArray(libs);
1632 return libs;
1633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001635 return null;
1636 }
1637
1638 public FeatureInfo[] getSystemAvailableFeatures() {
1639 Collection<FeatureInfo> featSet;
1640 synchronized (mPackages) {
1641 featSet = mAvailableFeatures.values();
1642 int size = featSet.size();
1643 if (size > 0) {
1644 FeatureInfo[] features = new FeatureInfo[size+1];
1645 featSet.toArray(features);
1646 FeatureInfo fi = new FeatureInfo();
1647 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1648 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1649 features[size] = fi;
1650 return features;
1651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 }
1653 return null;
1654 }
1655
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001656 public boolean hasSystemFeature(String name) {
1657 synchronized (mPackages) {
1658 return mAvailableFeatures.containsKey(name);
1659 }
1660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 public int checkPermission(String permName, String pkgName) {
1663 synchronized (mPackages) {
1664 PackageParser.Package p = mPackages.get(pkgName);
1665 if (p != null && p.mExtras != null) {
1666 PackageSetting ps = (PackageSetting)p.mExtras;
1667 if (ps.sharedUser != null) {
1668 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1669 return PackageManager.PERMISSION_GRANTED;
1670 }
1671 } else if (ps.grantedPermissions.contains(permName)) {
1672 return PackageManager.PERMISSION_GRANTED;
1673 }
1674 }
1675 }
1676 return PackageManager.PERMISSION_DENIED;
1677 }
1678
1679 public int checkUidPermission(String permName, int uid) {
1680 synchronized (mPackages) {
1681 Object obj = mSettings.getUserIdLP(uid);
1682 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001683 GrantedPermissions gp = (GrantedPermissions)obj;
1684 if (gp.grantedPermissions.contains(permName)) {
1685 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
1687 } else {
1688 HashSet<String> perms = mSystemPermissions.get(uid);
1689 if (perms != null && perms.contains(permName)) {
1690 return PackageManager.PERMISSION_GRANTED;
1691 }
1692 }
1693 }
1694 return PackageManager.PERMISSION_DENIED;
1695 }
1696
1697 private BasePermission findPermissionTreeLP(String permName) {
1698 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1699 if (permName.startsWith(bp.name) &&
1700 permName.length() > bp.name.length() &&
1701 permName.charAt(bp.name.length()) == '.') {
1702 return bp;
1703 }
1704 }
1705 return null;
1706 }
1707
1708 private BasePermission checkPermissionTreeLP(String permName) {
1709 if (permName != null) {
1710 BasePermission bp = findPermissionTreeLP(permName);
1711 if (bp != null) {
1712 if (bp.uid == Binder.getCallingUid()) {
1713 return bp;
1714 }
1715 throw new SecurityException("Calling uid "
1716 + Binder.getCallingUid()
1717 + " is not allowed to add to permission tree "
1718 + bp.name + " owned by uid " + bp.uid);
1719 }
1720 }
1721 throw new SecurityException("No permission tree found for " + permName);
1722 }
1723
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001724 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1725 if (s1 == null) {
1726 return s2 == null;
1727 }
1728 if (s2 == null) {
1729 return false;
1730 }
1731 if (s1.getClass() != s2.getClass()) {
1732 return false;
1733 }
1734 return s1.equals(s2);
1735 }
1736
1737 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1738 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001739 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001740 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1741 if (!compareStrings(pi1.name, pi2.name)) return false;
1742 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1743 // We'll take care of setting this one.
1744 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1745 // These are not currently stored in settings.
1746 //if (!compareStrings(pi1.group, pi2.group)) return false;
1747 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1748 //if (pi1.labelRes != pi2.labelRes) return false;
1749 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1750 return true;
1751 }
1752
1753 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1754 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1755 throw new SecurityException("Label must be specified in permission");
1756 }
1757 BasePermission tree = checkPermissionTreeLP(info.name);
1758 BasePermission bp = mSettings.mPermissions.get(info.name);
1759 boolean added = bp == null;
1760 boolean changed = true;
1761 if (added) {
1762 bp = new BasePermission(info.name, tree.sourcePackage,
1763 BasePermission.TYPE_DYNAMIC);
1764 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1765 throw new SecurityException(
1766 "Not allowed to modify non-dynamic permission "
1767 + info.name);
1768 } else {
1769 if (bp.protectionLevel == info.protectionLevel
1770 && bp.perm.owner.equals(tree.perm.owner)
1771 && bp.uid == tree.uid
1772 && comparePermissionInfos(bp.perm.info, info)) {
1773 changed = false;
1774 }
1775 }
1776 bp.protectionLevel = info.protectionLevel;
1777 bp.perm = new PackageParser.Permission(tree.perm.owner,
1778 new PermissionInfo(info));
1779 bp.perm.info.packageName = tree.perm.info.packageName;
1780 bp.uid = tree.uid;
1781 if (added) {
1782 mSettings.mPermissions.put(info.name, bp);
1783 }
1784 if (changed) {
1785 if (!async) {
1786 mSettings.writeLP();
1787 } else {
1788 scheduleWriteSettingsLocked();
1789 }
1790 }
1791 return added;
1792 }
1793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 public boolean addPermission(PermissionInfo info) {
1795 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001796 return addPermissionLocked(info, false);
1797 }
1798 }
1799
1800 public boolean addPermissionAsync(PermissionInfo info) {
1801 synchronized (mPackages) {
1802 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804 }
1805
1806 public void removePermission(String name) {
1807 synchronized (mPackages) {
1808 checkPermissionTreeLP(name);
1809 BasePermission bp = mSettings.mPermissions.get(name);
1810 if (bp != null) {
1811 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1812 throw new SecurityException(
1813 "Not allowed to modify non-dynamic permission "
1814 + name);
1815 }
1816 mSettings.mPermissions.remove(name);
1817 mSettings.writeLP();
1818 }
1819 }
1820 }
1821
Dianne Hackborn854060af2009-07-09 18:14:31 -07001822 public boolean isProtectedBroadcast(String actionName) {
1823 synchronized (mPackages) {
1824 return mProtectedBroadcasts.contains(actionName);
1825 }
1826 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 public int checkSignatures(String pkg1, String pkg2) {
1829 synchronized (mPackages) {
1830 PackageParser.Package p1 = mPackages.get(pkg1);
1831 PackageParser.Package p2 = mPackages.get(pkg2);
1832 if (p1 == null || p1.mExtras == null
1833 || p2 == null || p2.mExtras == null) {
1834 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1835 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001836 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 }
1838 }
1839
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001840 public int checkUidSignatures(int uid1, int uid2) {
1841 synchronized (mPackages) {
1842 Signature[] s1;
1843 Signature[] s2;
1844 Object obj = mSettings.getUserIdLP(uid1);
1845 if (obj != null) {
1846 if (obj instanceof SharedUserSetting) {
1847 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1848 } else if (obj instanceof PackageSetting) {
1849 s1 = ((PackageSetting)obj).signatures.mSignatures;
1850 } else {
1851 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1852 }
1853 } else {
1854 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1855 }
1856 obj = mSettings.getUserIdLP(uid2);
1857 if (obj != null) {
1858 if (obj instanceof SharedUserSetting) {
1859 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1860 } else if (obj instanceof PackageSetting) {
1861 s2 = ((PackageSetting)obj).signatures.mSignatures;
1862 } else {
1863 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1864 }
1865 } else {
1866 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1867 }
1868 return checkSignaturesLP(s1, s2);
1869 }
1870 }
1871
1872 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1873 if (s1 == null) {
1874 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1876 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1877 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001878 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1880 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001881 HashSet<Signature> set1 = new HashSet<Signature>();
1882 for (Signature sig : s1) {
1883 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001885 HashSet<Signature> set2 = new HashSet<Signature>();
1886 for (Signature sig : s2) {
1887 set2.add(sig);
1888 }
1889 // Make sure s2 contains all signatures in s1.
1890 if (set1.equals(set2)) {
1891 return PackageManager.SIGNATURE_MATCH;
1892 }
1893 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895
1896 public String[] getPackagesForUid(int uid) {
1897 synchronized (mPackages) {
1898 Object obj = mSettings.getUserIdLP(uid);
1899 if (obj instanceof SharedUserSetting) {
1900 SharedUserSetting sus = (SharedUserSetting)obj;
1901 final int N = sus.packages.size();
1902 String[] res = new String[N];
1903 Iterator<PackageSetting> it = sus.packages.iterator();
1904 int i=0;
1905 while (it.hasNext()) {
1906 res[i++] = it.next().name;
1907 }
1908 return res;
1909 } else if (obj instanceof PackageSetting) {
1910 PackageSetting ps = (PackageSetting)obj;
1911 return new String[] { ps.name };
1912 }
1913 }
1914 return null;
1915 }
1916
1917 public String getNameForUid(int uid) {
1918 synchronized (mPackages) {
1919 Object obj = mSettings.getUserIdLP(uid);
1920 if (obj instanceof SharedUserSetting) {
1921 SharedUserSetting sus = (SharedUserSetting)obj;
1922 return sus.name + ":" + sus.userId;
1923 } else if (obj instanceof PackageSetting) {
1924 PackageSetting ps = (PackageSetting)obj;
1925 return ps.name;
1926 }
1927 }
1928 return null;
1929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 public int getUidForSharedUser(String sharedUserName) {
1932 if(sharedUserName == null) {
1933 return -1;
1934 }
1935 synchronized (mPackages) {
1936 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1937 if(suid == null) {
1938 return -1;
1939 }
1940 return suid.userId;
1941 }
1942 }
1943
1944 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1945 int flags) {
1946 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001947 return chooseBestActivity(intent, resolvedType, flags, query);
1948 }
1949
Mihai Predaeae850c2009-05-13 10:13:48 +02001950 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1951 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 if (query != null) {
1953 final int N = query.size();
1954 if (N == 1) {
1955 return query.get(0);
1956 } else if (N > 1) {
1957 // If there is more than one activity with the same priority,
1958 // then let the user decide between them.
1959 ResolveInfo r0 = query.get(0);
1960 ResolveInfo r1 = query.get(1);
1961 if (false) {
1962 System.out.println(r0.activityInfo.name +
1963 "=" + r0.priority + " vs " +
1964 r1.activityInfo.name +
1965 "=" + r1.priority);
1966 }
1967 // If the first activity has a higher priority, or a different
1968 // default, then it is always desireable to pick it.
1969 if (r0.priority != r1.priority
1970 || r0.preferredOrder != r1.preferredOrder
1971 || r0.isDefault != r1.isDefault) {
1972 return query.get(0);
1973 }
1974 // If we have saved a preference for a preferred activity for
1975 // this Intent, use that.
1976 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1977 flags, query, r0.priority);
1978 if (ri != null) {
1979 return ri;
1980 }
1981 return mResolveInfo;
1982 }
1983 }
1984 return null;
1985 }
1986
1987 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1988 int flags, List<ResolveInfo> query, int priority) {
1989 synchronized (mPackages) {
1990 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1991 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001992 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1994 if (prefs != null && prefs.size() > 0) {
1995 // First figure out how good the original match set is.
1996 // We will only allow preferred activities that came
1997 // from the same match quality.
1998 int match = 0;
1999 final int N = query.size();
2000 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2001 for (int j=0; j<N; j++) {
2002 ResolveInfo ri = query.get(j);
2003 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2004 + ": 0x" + Integer.toHexString(match));
2005 if (ri.match > match) match = ri.match;
2006 }
2007 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2008 + Integer.toHexString(match));
2009 match &= IntentFilter.MATCH_CATEGORY_MASK;
2010 final int M = prefs.size();
2011 for (int i=0; i<M; i++) {
2012 PreferredActivity pa = prefs.get(i);
2013 if (pa.mMatch != match) {
2014 continue;
2015 }
2016 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2017 if (DEBUG_PREFERRED) {
2018 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002019 if (ai != null) {
2020 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2021 } else {
2022 Log.v(TAG, " null");
2023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 }
2025 if (ai != null) {
2026 for (int j=0; j<N; j++) {
2027 ResolveInfo ri = query.get(j);
2028 if (!ri.activityInfo.applicationInfo.packageName
2029 .equals(ai.applicationInfo.packageName)) {
2030 continue;
2031 }
2032 if (!ri.activityInfo.name.equals(ai.name)) {
2033 continue;
2034 }
2035
2036 // Okay we found a previously set preferred app.
2037 // If the result set is different from when this
2038 // was created, we need to clear it and re-ask the
2039 // user their preference.
2040 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002041 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 + intent + " type " + resolvedType);
2043 mSettings.mPreferredActivities.removeFilter(pa);
2044 return null;
2045 }
2046
2047 // Yay!
2048 return ri;
2049 }
2050 }
2051 }
2052 }
2053 }
2054 return null;
2055 }
2056
2057 public List<ResolveInfo> queryIntentActivities(Intent intent,
2058 String resolvedType, int flags) {
2059 ComponentName comp = intent.getComponent();
2060 if (comp != null) {
2061 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2062 ActivityInfo ai = getActivityInfo(comp, flags);
2063 if (ai != null) {
2064 ResolveInfo ri = new ResolveInfo();
2065 ri.activityInfo = ai;
2066 list.add(ri);
2067 }
2068 return list;
2069 }
2070
2071 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002072 String pkgName = intent.getPackage();
2073 if (pkgName == null) {
2074 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2075 resolvedType, flags);
2076 }
2077 PackageParser.Package pkg = mPackages.get(pkgName);
2078 if (pkg != null) {
2079 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2080 resolvedType, flags, pkg.activities);
2081 }
2082 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 }
2084 }
2085
2086 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2087 Intent[] specifics, String[] specificTypes, Intent intent,
2088 String resolvedType, int flags) {
2089 final String resultsAction = intent.getAction();
2090
2091 List<ResolveInfo> results = queryIntentActivities(
2092 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2093 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2094
2095 int specificsPos = 0;
2096 int N;
2097
2098 // todo: note that the algorithm used here is O(N^2). This
2099 // isn't a problem in our current environment, but if we start running
2100 // into situations where we have more than 5 or 10 matches then this
2101 // should probably be changed to something smarter...
2102
2103 // First we go through and resolve each of the specific items
2104 // that were supplied, taking care of removing any corresponding
2105 // duplicate items in the generic resolve list.
2106 if (specifics != null) {
2107 for (int i=0; i<specifics.length; i++) {
2108 final Intent sintent = specifics[i];
2109 if (sintent == null) {
2110 continue;
2111 }
2112
2113 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2114 String action = sintent.getAction();
2115 if (resultsAction != null && resultsAction.equals(action)) {
2116 // If this action was explicitly requested, then don't
2117 // remove things that have it.
2118 action = null;
2119 }
2120 ComponentName comp = sintent.getComponent();
2121 ResolveInfo ri = null;
2122 ActivityInfo ai = null;
2123 if (comp == null) {
2124 ri = resolveIntent(
2125 sintent,
2126 specificTypes != null ? specificTypes[i] : null,
2127 flags);
2128 if (ri == null) {
2129 continue;
2130 }
2131 if (ri == mResolveInfo) {
2132 // ACK! Must do something better with this.
2133 }
2134 ai = ri.activityInfo;
2135 comp = new ComponentName(ai.applicationInfo.packageName,
2136 ai.name);
2137 } else {
2138 ai = getActivityInfo(comp, flags);
2139 if (ai == null) {
2140 continue;
2141 }
2142 }
2143
2144 // Look for any generic query activities that are duplicates
2145 // of this specific one, and remove them from the results.
2146 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2147 N = results.size();
2148 int j;
2149 for (j=specificsPos; j<N; j++) {
2150 ResolveInfo sri = results.get(j);
2151 if ((sri.activityInfo.name.equals(comp.getClassName())
2152 && sri.activityInfo.applicationInfo.packageName.equals(
2153 comp.getPackageName()))
2154 || (action != null && sri.filter.matchAction(action))) {
2155 results.remove(j);
2156 if (Config.LOGV) Log.v(
2157 TAG, "Removing duplicate item from " + j
2158 + " due to specific " + specificsPos);
2159 if (ri == null) {
2160 ri = sri;
2161 }
2162 j--;
2163 N--;
2164 }
2165 }
2166
2167 // Add this specific item to its proper place.
2168 if (ri == null) {
2169 ri = new ResolveInfo();
2170 ri.activityInfo = ai;
2171 }
2172 results.add(specificsPos, ri);
2173 ri.specificIndex = i;
2174 specificsPos++;
2175 }
2176 }
2177
2178 // Now we go through the remaining generic results and remove any
2179 // duplicate actions that are found here.
2180 N = results.size();
2181 for (int i=specificsPos; i<N-1; i++) {
2182 final ResolveInfo rii = results.get(i);
2183 if (rii.filter == null) {
2184 continue;
2185 }
2186
2187 // Iterate over all of the actions of this result's intent
2188 // filter... typically this should be just one.
2189 final Iterator<String> it = rii.filter.actionsIterator();
2190 if (it == null) {
2191 continue;
2192 }
2193 while (it.hasNext()) {
2194 final String action = it.next();
2195 if (resultsAction != null && resultsAction.equals(action)) {
2196 // If this action was explicitly requested, then don't
2197 // remove things that have it.
2198 continue;
2199 }
2200 for (int j=i+1; j<N; j++) {
2201 final ResolveInfo rij = results.get(j);
2202 if (rij.filter != null && rij.filter.hasAction(action)) {
2203 results.remove(j);
2204 if (Config.LOGV) Log.v(
2205 TAG, "Removing duplicate item from " + j
2206 + " due to action " + action + " at " + i);
2207 j--;
2208 N--;
2209 }
2210 }
2211 }
2212
2213 // If the caller didn't request filter information, drop it now
2214 // so we don't have to marshall/unmarshall it.
2215 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2216 rii.filter = null;
2217 }
2218 }
2219
2220 // Filter out the caller activity if so requested.
2221 if (caller != null) {
2222 N = results.size();
2223 for (int i=0; i<N; i++) {
2224 ActivityInfo ainfo = results.get(i).activityInfo;
2225 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2226 && caller.getClassName().equals(ainfo.name)) {
2227 results.remove(i);
2228 break;
2229 }
2230 }
2231 }
2232
2233 // If the caller didn't request filter information,
2234 // drop them now so we don't have to
2235 // marshall/unmarshall it.
2236 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2237 N = results.size();
2238 for (int i=0; i<N; i++) {
2239 results.get(i).filter = null;
2240 }
2241 }
2242
2243 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2244 return results;
2245 }
2246
2247 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2248 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002249 ComponentName comp = intent.getComponent();
2250 if (comp != null) {
2251 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2252 ActivityInfo ai = getReceiverInfo(comp, flags);
2253 if (ai != null) {
2254 ResolveInfo ri = new ResolveInfo();
2255 ri.activityInfo = ai;
2256 list.add(ri);
2257 }
2258 return list;
2259 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002262 String pkgName = intent.getPackage();
2263 if (pkgName == null) {
2264 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2265 resolvedType, flags);
2266 }
2267 PackageParser.Package pkg = mPackages.get(pkgName);
2268 if (pkg != null) {
2269 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2270 resolvedType, flags, pkg.receivers);
2271 }
2272 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 }
2274 }
2275
2276 public ResolveInfo resolveService(Intent intent, String resolvedType,
2277 int flags) {
2278 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2279 flags);
2280 if (query != null) {
2281 if (query.size() >= 1) {
2282 // If there is more than one service with the same priority,
2283 // just arbitrarily pick the first one.
2284 return query.get(0);
2285 }
2286 }
2287 return null;
2288 }
2289
2290 public List<ResolveInfo> queryIntentServices(Intent intent,
2291 String resolvedType, int flags) {
2292 ComponentName comp = intent.getComponent();
2293 if (comp != null) {
2294 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2295 ServiceInfo si = getServiceInfo(comp, flags);
2296 if (si != null) {
2297 ResolveInfo ri = new ResolveInfo();
2298 ri.serviceInfo = si;
2299 list.add(ri);
2300 }
2301 return list;
2302 }
2303
2304 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002305 String pkgName = intent.getPackage();
2306 if (pkgName == null) {
2307 return (List<ResolveInfo>)mServices.queryIntent(intent,
2308 resolvedType, flags);
2309 }
2310 PackageParser.Package pkg = mPackages.get(pkgName);
2311 if (pkg != null) {
2312 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2313 resolvedType, flags, pkg.services);
2314 }
2315 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 }
2317 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 public List<PackageInfo> getInstalledPackages(int flags) {
2320 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2321
2322 synchronized (mPackages) {
2323 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2324 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2325 while (i.hasNext()) {
2326 final PackageSetting ps = i.next();
2327 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2328 if(psPkg != null) {
2329 finalList.add(psPkg);
2330 }
2331 }
2332 }
2333 else {
2334 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2335 while (i.hasNext()) {
2336 final PackageParser.Package p = i.next();
2337 if (p.applicationInfo != null) {
2338 PackageInfo pi = generatePackageInfo(p, flags);
2339 if(pi != null) {
2340 finalList.add(pi);
2341 }
2342 }
2343 }
2344 }
2345 }
2346 return finalList;
2347 }
2348
2349 public List<ApplicationInfo> getInstalledApplications(int flags) {
2350 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2351 synchronized(mPackages) {
2352 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2353 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2354 while (i.hasNext()) {
2355 final PackageSetting ps = i.next();
2356 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2357 if(ai != null) {
2358 finalList.add(ai);
2359 }
2360 }
2361 }
2362 else {
2363 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2364 while (i.hasNext()) {
2365 final PackageParser.Package p = i.next();
2366 if (p.applicationInfo != null) {
2367 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2368 if(ai != null) {
2369 finalList.add(ai);
2370 }
2371 }
2372 }
2373 }
2374 }
2375 return finalList;
2376 }
2377
2378 public List<ApplicationInfo> getPersistentApplications(int flags) {
2379 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2380
2381 synchronized (mPackages) {
2382 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2383 while (i.hasNext()) {
2384 PackageParser.Package p = i.next();
2385 if (p.applicationInfo != null
2386 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002387 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002388 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 }
2390 }
2391 }
2392
2393 return finalList;
2394 }
2395
2396 public ProviderInfo resolveContentProvider(String name, int flags) {
2397 synchronized (mPackages) {
2398 final PackageParser.Provider provider = mProviders.get(name);
2399 return provider != null
2400 && mSettings.isEnabledLP(provider.info, flags)
2401 && (!mSafeMode || (provider.info.applicationInfo.flags
2402 &ApplicationInfo.FLAG_SYSTEM) != 0)
2403 ? PackageParser.generateProviderInfo(provider, flags)
2404 : null;
2405 }
2406 }
2407
Fred Quintana718d8a22009-04-29 17:53:20 -07002408 /**
2409 * @deprecated
2410 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 public void querySyncProviders(List outNames, List outInfo) {
2412 synchronized (mPackages) {
2413 Iterator<Map.Entry<String, PackageParser.Provider>> i
2414 = mProviders.entrySet().iterator();
2415
2416 while (i.hasNext()) {
2417 Map.Entry<String, PackageParser.Provider> entry = i.next();
2418 PackageParser.Provider p = entry.getValue();
2419
2420 if (p.syncable
2421 && (!mSafeMode || (p.info.applicationInfo.flags
2422 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2423 outNames.add(entry.getKey());
2424 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2425 }
2426 }
2427 }
2428 }
2429
2430 public List<ProviderInfo> queryContentProviders(String processName,
2431 int uid, int flags) {
2432 ArrayList<ProviderInfo> finalList = null;
2433
2434 synchronized (mPackages) {
2435 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2436 while (i.hasNext()) {
2437 PackageParser.Provider p = i.next();
2438 if (p.info.authority != null
2439 && (processName == null ||
2440 (p.info.processName.equals(processName)
2441 && p.info.applicationInfo.uid == uid))
2442 && mSettings.isEnabledLP(p.info, flags)
2443 && (!mSafeMode || (p.info.applicationInfo.flags
2444 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2445 if (finalList == null) {
2446 finalList = new ArrayList<ProviderInfo>(3);
2447 }
2448 finalList.add(PackageParser.generateProviderInfo(p,
2449 flags));
2450 }
2451 }
2452 }
2453
2454 if (finalList != null) {
2455 Collections.sort(finalList, mProviderInitOrderSorter);
2456 }
2457
2458 return finalList;
2459 }
2460
2461 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2462 int flags) {
2463 synchronized (mPackages) {
2464 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2465 return PackageParser.generateInstrumentationInfo(i, flags);
2466 }
2467 }
2468
2469 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2470 int flags) {
2471 ArrayList<InstrumentationInfo> finalList =
2472 new ArrayList<InstrumentationInfo>();
2473
2474 synchronized (mPackages) {
2475 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2476 while (i.hasNext()) {
2477 PackageParser.Instrumentation p = i.next();
2478 if (targetPackage == null
2479 || targetPackage.equals(p.info.targetPackage)) {
2480 finalList.add(PackageParser.generateInstrumentationInfo(p,
2481 flags));
2482 }
2483 }
2484 }
2485
2486 return finalList;
2487 }
2488
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002489 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002491 if (files == null) {
2492 Log.d(TAG, "No files in app dir " + dir);
2493 return;
2494 }
2495
2496 Log.d(TAG, "Scanning app dir " + dir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497
2498 int i;
2499 for (i=0; i<files.length; i++) {
2500 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002501 if (!isPackageFilename(files[i])) {
2502 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002503 continue;
2504 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002505 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002506 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002507 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002508 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2509 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002510 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002511 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002512 file.delete();
2513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 }
2515 }
2516
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002517 private static File getSettingsProblemFile() {
2518 File dataDir = Environment.getDataDirectory();
2519 File systemDir = new File(dataDir, "system");
2520 File fname = new File(systemDir, "uiderrors.txt");
2521 return fname;
2522 }
2523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 private static void reportSettingsProblem(int priority, String msg) {
2525 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002526 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 FileOutputStream out = new FileOutputStream(fname, true);
2528 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002529 SimpleDateFormat formatter = new SimpleDateFormat();
2530 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2531 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 pw.close();
2533 FileUtils.setPermissions(
2534 fname.toString(),
2535 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2536 -1, -1);
2537 } catch (java.io.IOException e) {
2538 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002539 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 }
2541
2542 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2543 PackageParser.Package pkg, File srcFile, int parseFlags) {
2544 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002545 if (ps != null
2546 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002547 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002548 if (ps.signatures.mSignatures != null
2549 && ps.signatures.mSignatures.length != 0) {
2550 // Optimization: reuse the existing cached certificates
2551 // if the package appears to be unchanged.
2552 pkg.mSignatures = ps.signatures.mSignatures;
2553 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 }
Jeff Browne7600722010-04-07 18:28:23 -07002555
2556 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002557 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002558 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2559 }
2560
2561 if (!pp.collectCertificates(pkg, parseFlags)) {
2562 mLastScanError = pp.getParseError();
2563 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
2565 }
2566 return true;
2567 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 /*
2570 * Scan a package and return the newly parsed package.
2571 * Returns null in case of errors and the error code is stored in mLastScanError
2572 */
2573 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002574 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002576 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002578 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002581 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 if (pkg == null) {
2583 mLastScanError = pp.getParseError();
2584 return null;
2585 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002586 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 PackageSetting updatedPkg;
2588 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002589 // Look to see if we already know about this package.
2590 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002591 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002592 // This package has been renamed to its original name. Let's
2593 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002594 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002595 }
2596 // If there was no original package, see one for the real package name.
2597 if (ps == null) {
2598 ps = mSettings.peekPackageLP(pkg.packageName);
2599 }
2600 // Check to see if this package could be hiding/updating a system
2601 // package. Must look for it either under the original or real
2602 // package name depending on our state.
2603 updatedPkg = mSettings.mDisabledSysPackages.get(
2604 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002606 // First check if this is a system package that may involve an update
2607 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002608 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002609 // The path has changed from what was last scanned... check the
2610 // version of the new path against what we have stored to determine
2611 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002612 if (pkg.mVersionCode < ps.versionCode) {
2613 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002614 // Ignore entry. Skip it.
2615 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002616 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002617 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002618 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2619 return null;
2620 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002621 // The current app on the system partion is better than
2622 // what we have updated to on the data partition; switch
2623 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002624 // At this point, its safely assumed that package installation for
2625 // apps in system partition will go through. If not there won't be a working
2626 // version of the app
2627 synchronized (mPackages) {
2628 // Just remove the loaded entries from package lists.
2629 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002630 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002631 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002632 + "reverting from " + ps.codePathString
2633 + ": new version " + pkg.mVersionCode
2634 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002635 InstallArgs args = new FileInstallArgs(ps.codePathString,
2636 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002637 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002638 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 }
2641 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002642 if (updatedPkg != null) {
2643 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2644 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2645 }
2646 // Verify certificates against what was last scanned
2647 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002648 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002649 return null;
2650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 // The apk is forward locked (not public) if its code and resources
2652 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002653 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002655 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002656 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002657
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002658 String codePath = null;
2659 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002660 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2661 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002662 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002663 } else {
2664 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002665 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002666 }
2667 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002668 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002669 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002670 codePath = pkg.mScanPath;
2671 // Set application objects path explicitly.
2672 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002674 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 }
2676
Kenny Root85387d72010-08-26 10:13:11 -07002677 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2678 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002679 pkg.mPath = pkg.mScanPath = destCodePath;
2680 pkg.applicationInfo.sourceDir = destCodePath;
2681 pkg.applicationInfo.publicSourceDir = destResPath;
2682 }
2683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 private static String fixProcessName(String defProcessName,
2685 String processName, int uid) {
2686 if (processName == null) {
2687 return defProcessName;
2688 }
2689 return processName;
2690 }
2691
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002692 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002693 PackageParser.Package pkg) {
2694 if (pkgSetting.signatures.mSignatures != null) {
2695 // Already existing package. Make sure signatures match
2696 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2697 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002698 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002699 + " signatures do not match the previously installed version; ignoring!");
2700 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 return false;
2702 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002703 }
2704 // Check for shared user signatures
2705 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2706 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2707 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2708 Slog.e(TAG, "Package " + pkg.packageName
2709 + " has no signatures that match those in shared user "
2710 + pkgSetting.sharedUser.name + "; ignoring!");
2711 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2712 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 }
2715 return true;
2716 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002717
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002718 public boolean performDexOpt(String packageName) {
2719 if (!mNoDexOpt) {
2720 return false;
2721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002722
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002723 PackageParser.Package p;
2724 synchronized (mPackages) {
2725 p = mPackages.get(packageName);
2726 if (p == null || p.mDidDexOpt) {
2727 return false;
2728 }
2729 }
2730 synchronized (mInstallLock) {
2731 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2732 }
2733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002734
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002735 static final int DEX_OPT_SKIPPED = 0;
2736 static final int DEX_OPT_PERFORMED = 1;
2737 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002738
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002739 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2740 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002741 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002742 String path = pkg.mScanPath;
2743 int ret = 0;
2744 try {
2745 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002746 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002747 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002748 pkg.mDidDexOpt = true;
2749 performed = true;
2750 }
2751 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002752 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002753 ret = -1;
2754 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002755 Slog.w(TAG, "IOException reading apk: " + path, e);
2756 ret = -1;
2757 } catch (dalvik.system.StaleDexCacheError e) {
2758 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2759 ret = -1;
2760 } catch (Exception e) {
2761 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002762 ret = -1;
2763 }
2764 if (ret < 0) {
2765 //error from installer
2766 return DEX_OPT_FAILED;
2767 }
2768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002769
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002770 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2771 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002772
2773 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2774 return Environment.isEncryptedFilesystemEnabled() &&
2775 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2776 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002777
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002778 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2779 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002780 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002781 + " to " + newPkg.packageName
2782 + ": old package not in system partition");
2783 return false;
2784 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002785 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002786 + " to " + newPkg.packageName
2787 + ": old package still exists");
2788 return false;
2789 }
2790 return true;
2791 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002792
2793 private File getDataPathForPackage(PackageParser.Package pkg) {
2794 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2795 File dataPath;
2796 if (useEncryptedFSDir) {
2797 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2798 } else {
2799 dataPath = new File(mAppDataDir, pkg.packageName);
2800 }
2801 return dataPath;
2802 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002803
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002804 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002805 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002806 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002807 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2808 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002809 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002810 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002811 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2812 return null;
2813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 mScanningPath = scanFile;
2815 if (pkg == null) {
2816 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2817 return null;
2818 }
2819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2821 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2822 }
2823
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002824 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 synchronized (mPackages) {
2826 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002827 Slog.w(TAG, "*************************************************");
2828 Slog.w(TAG, "Core android package being redefined. Skipping.");
2829 Slog.w(TAG, " file=" + mScanningPath);
2830 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2832 return null;
2833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 // Set up information for our fall-back user intent resolution
2836 // activity.
2837 mPlatformPackage = pkg;
2838 pkg.mVersionCode = mSdkVersion;
2839 mAndroidApplication = pkg.applicationInfo;
2840 mResolveActivity.applicationInfo = mAndroidApplication;
2841 mResolveActivity.name = ResolverActivity.class.getName();
2842 mResolveActivity.packageName = mAndroidApplication.packageName;
2843 mResolveActivity.processName = mAndroidApplication.processName;
2844 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2845 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2846 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2847 mResolveActivity.exported = true;
2848 mResolveActivity.enabled = true;
2849 mResolveInfo.activityInfo = mResolveActivity;
2850 mResolveInfo.priority = 0;
2851 mResolveInfo.preferredOrder = 0;
2852 mResolveInfo.match = 0;
2853 mResolveComponentName = new ComponentName(
2854 mAndroidApplication.packageName, mResolveActivity.name);
2855 }
2856 }
2857
2858 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002859 TAG, "Scanning package " + pkg.packageName);
2860 if (mPackages.containsKey(pkg.packageName)
2861 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002862 Slog.w(TAG, "*************************************************");
2863 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002865 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2867 return null;
2868 }
2869
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002870 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002871 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2872 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 SharedUserSetting suid = null;
2875 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002876
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002877 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2878 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002879 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002880 pkg.mRealPackage = null;
2881 pkg.mAdoptPermissions = null;
2882 }
2883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 synchronized (mPackages) {
2885 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002886 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2887 if (mTmpSharedLibraries == null ||
2888 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2889 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2890 }
2891 int num = 0;
2892 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2893 for (int i=0; i<N; i++) {
2894 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002896 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002898 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2900 return null;
2901 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002902 mTmpSharedLibraries[num] = file;
2903 num++;
2904 }
2905 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2906 for (int i=0; i<N; i++) {
2907 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2908 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002909 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002910 + " desires unavailable shared library "
2911 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2912 } else {
2913 mTmpSharedLibraries[num] = file;
2914 num++;
2915 }
2916 }
2917 if (num > 0) {
2918 pkg.usesLibraryFiles = new String[num];
2919 System.arraycopy(mTmpSharedLibraries, 0,
2920 pkg.usesLibraryFiles, 0, num);
2921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002922
Dianne Hackborn49237342009-08-27 20:08:01 -07002923 if (pkg.reqFeatures != null) {
2924 N = pkg.reqFeatures.size();
2925 for (int i=0; i<N; i++) {
2926 FeatureInfo fi = pkg.reqFeatures.get(i);
2927 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2928 // Don't care.
2929 continue;
2930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002931
Dianne Hackborn49237342009-08-27 20:08:01 -07002932 if (fi.name != null) {
2933 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002934 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002935 + " requires unavailable feature "
2936 + fi.name + "; failing!");
2937 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2938 return null;
2939 }
2940 }
2941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 }
2943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 if (pkg.mSharedUserId != null) {
2946 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2947 pkg.applicationInfo.flags, true);
2948 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002949 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 + " for shared user failed");
2951 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2952 return null;
2953 }
2954 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2955 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2956 + suid.userId + "): packages=" + suid.packages);
2957 }
2958 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002959
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002961 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002962 Log.w(TAG, "WAITING FOR DEBUGGER");
2963 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002964 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2965 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002966 }
2967 }
2968
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002969 // Check if we are renaming from an original package name.
2970 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002971 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002972 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973 // This package may need to be renamed to a previously
2974 // installed name. Let's check on that...
2975 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002976 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002977 // This package had originally been installed as the
2978 // original name, and we have already taken care of
2979 // transitioning to the new one. Just update the new
2980 // one to continue using the old name.
2981 realName = pkg.mRealPackage;
2982 if (!pkg.packageName.equals(renamed)) {
2983 // Callers into this function may have already taken
2984 // care of renaming the package; only do it here if
2985 // it is not already done.
2986 pkg.setPackageName(renamed);
2987 }
2988
Dianne Hackbornc1552392010-03-03 16:19:01 -08002989 } else {
2990 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2991 if ((origPackage=mSettings.peekPackageLP(
2992 pkg.mOriginalPackages.get(i))) != null) {
2993 // We do have the package already installed under its
2994 // original name... should we use it?
2995 if (!verifyPackageUpdate(origPackage, pkg)) {
2996 // New package is not compatible with original.
2997 origPackage = null;
2998 continue;
2999 } else if (origPackage.sharedUser != null) {
3000 // Make sure uid is compatible between packages.
3001 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003002 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003003 + " to " + pkg.packageName + ": old uid "
3004 + origPackage.sharedUser.name
3005 + " differs from " + pkg.mSharedUserId);
3006 origPackage = null;
3007 continue;
3008 }
3009 } else {
3010 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3011 + pkg.packageName + " to old name " + origPackage.name);
3012 }
3013 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003014 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003015 }
3016 }
3017 }
3018
3019 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003020 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003021 + " was transferred to another, but its .apk remains");
3022 }
3023
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003024 // Just create the setting, don't add it yet. For already existing packages
3025 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003026 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003027 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3028 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003030 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3032 return null;
3033 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003034
3035 if (pkgSetting.origPackage != null) {
3036 // If we are first transitioning from an original package,
3037 // fix up the new package's name now. We need to do this after
3038 // looking up the package under its new name, so getPackageLP
3039 // can take care of fiddling things correctly.
3040 pkg.setPackageName(origPackage.name);
3041
3042 // File a report about this.
3043 String msg = "New package " + pkgSetting.realName
3044 + " renamed to replace old package " + pkgSetting.name;
3045 reportSettingsProblem(Log.WARN, msg);
3046
3047 // Make a note of it.
3048 mTransferedPackages.add(origPackage.name);
3049
3050 // No longer need to retain this.
3051 pkgSetting.origPackage = null;
3052 }
3053
3054 if (realName != null) {
3055 // Make a note of it.
3056 mTransferedPackages.add(pkg.packageName);
3057 }
3058
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003059 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3061 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063 pkg.applicationInfo.uid = pkgSetting.userId;
3064 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003065
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003066 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003067 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 return null;
3069 }
3070 // The signature has changed, but this package is in the system
3071 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003072 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 // However... if this package is part of a shared user, but it
3074 // doesn't match the signature of the shared user, let's fail.
3075 // What this means is that you can't change the signatures
3076 // associated with an overall shared user, which doesn't seem all
3077 // that unreasonable.
3078 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003079 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3080 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3081 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3083 return null;
3084 }
3085 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003086 // File a report about this.
3087 String msg = "System package " + pkg.packageName
3088 + " signature changed; retaining data.";
3089 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003091
The Android Open Source Project10592532009-03-18 17:39:46 -07003092 // Verify that this new package doesn't have any content providers
3093 // that conflict with existing packages. Only do this if the
3094 // package isn't already installed, since we don't want to break
3095 // things that are installed.
3096 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3097 int N = pkg.providers.size();
3098 int i;
3099 for (i=0; i<N; i++) {
3100 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003101 if (p.info.authority != null) {
3102 String names[] = p.info.authority.split(";");
3103 for (int j = 0; j < names.length; j++) {
3104 if (mProviders.containsKey(names[j])) {
3105 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003106 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003107 " (in package " + pkg.applicationInfo.packageName +
3108 ") is already used by "
3109 + ((other != null && other.getComponentName() != null)
3110 ? other.getComponentName().getPackageName() : "?"));
3111 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3112 return null;
3113 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003114 }
3115 }
3116 }
3117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 }
3119
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003120 final String pkgName = pkg.packageName;
3121
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003122 if (pkg.mAdoptPermissions != null) {
3123 // This package wants to adopt ownership of permissions from
3124 // another package.
3125 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3126 String origName = pkg.mAdoptPermissions.get(i);
3127 PackageSetting orig = mSettings.peekPackageLP(origName);
3128 if (orig != null) {
3129 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003130 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003131 + origName + " to " + pkg.packageName);
3132 mSettings.transferPermissions(origName, pkg.packageName);
3133 }
3134 }
3135 }
3136 }
3137
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003138 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003140 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 pkg.applicationInfo.processName = fixProcessName(
3142 pkg.applicationInfo.packageName,
3143 pkg.applicationInfo.processName,
3144 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145
3146 File dataPath;
3147 if (mPlatformPackage == pkg) {
3148 // The system package is special.
3149 dataPath = new File (Environment.getDataDirectory(), "system");
3150 pkg.applicationInfo.dataDir = dataPath.getPath();
3151 } else {
3152 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003153 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003154 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003155
3156 boolean uidError = false;
3157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 if (dataPath.exists()) {
3159 mOutPermissions[1] = 0;
3160 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003161
3162 // If we have mismatched owners for the data path, we have a
3163 // problem (unless we're running in the simulator.)
3164 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 boolean recovered = false;
3166 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3167 // If this is a system app, we can at least delete its
3168 // current data so the application will still work.
3169 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003170 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003171 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 // Old data gone!
3173 String msg = "System package " + pkg.packageName
3174 + " has changed from uid: "
3175 + mOutPermissions[1] + " to "
3176 + pkg.applicationInfo.uid + "; old data erased";
3177 reportSettingsProblem(Log.WARN, msg);
3178 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003181 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 pkg.applicationInfo.uid);
3183 if (ret == -1) {
3184 // Ack should not happen!
3185 msg = "System package " + pkg.packageName
3186 + " could not have data directory re-created after delete.";
3187 reportSettingsProblem(Log.WARN, msg);
3188 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3189 return null;
3190 }
3191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 if (!recovered) {
3194 mHasSystemUidErrors = true;
3195 }
3196 }
3197 if (!recovered) {
3198 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3199 + pkg.applicationInfo.uid + "/fs_"
3200 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003201 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 String msg = "Package " + pkg.packageName
3203 + " has mismatched uid: "
3204 + mOutPermissions[1] + " on disk, "
3205 + pkg.applicationInfo.uid + " in settings";
3206 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003207 mSettings.mReadMessages.append(msg);
3208 mSettings.mReadMessages.append('\n');
3209 uidError = true;
3210 if (!pkgSetting.uidError) {
3211 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 }
3214 }
3215 }
3216 pkg.applicationInfo.dataDir = dataPath.getPath();
3217 } else {
3218 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3219 Log.v(TAG, "Want this data dir: " + dataPath);
3220 //invoke installer to do the actual installation
3221 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003222 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 pkg.applicationInfo.uid);
3224 if(ret < 0) {
3225 // Error from installer
3226 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3227 return null;
3228 }
3229 } else {
3230 dataPath.mkdirs();
3231 if (dataPath.exists()) {
3232 FileUtils.setPermissions(
3233 dataPath.toString(),
3234 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3235 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3236 }
3237 }
3238 if (dataPath.exists()) {
3239 pkg.applicationInfo.dataDir = dataPath.getPath();
3240 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003241 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 pkg.applicationInfo.dataDir = null;
3243 }
3244 }
Kenny Root85387d72010-08-26 10:13:11 -07003245
3246 /*
3247 * Set the data dir to the default "/data/data/<package name>/lib"
3248 * if we got here without anyone telling us different (e.g., apps
3249 * stored on SD card have their native libraries stored in the ASEC
3250 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003251 *
3252 * This happens during an upgrade from a package settings file that
3253 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003254 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003255 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3256 if (pkgSetting.nativeLibraryPathString == null) {
3257 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3258 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3259 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3260 } else {
3261 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3262 }
Kenny Root85387d72010-08-26 10:13:11 -07003263 }
3264
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003265 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 }
3267
Kenny Root85387d72010-08-26 10:13:11 -07003268 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 if (mInstaller != null) {
3270 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003271 /* Note: We don't want to unpack the native binaries for
3272 * system applications, unless they have been updated
3273 * (the binaries are already under /system/lib).
3274 * Also, don't unpack libs for apps on the external card
3275 * since they should have their libraries in the ASEC
3276 * container already.
3277 *
3278 * In other words, we're going to unpack the binaries
3279 * only for non-system apps and system app upgrades.
3280 */
Kenny Root831baa22010-10-05 12:29:25 -07003281 if (pkg.applicationInfo.nativeLibraryDir != null) {
3282 final File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3283 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3284 /*
3285 * Upgrading from a previous version of the OS sometimes
3286 * leaves native libraries in the /data/data/<app>/lib
3287 * directory for system apps even when they shouldn't be.
3288 * Recent changes in the JNI library search path
3289 * necessitates we remove those to match previous behavior.
3290 */
3291 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(sharedLibraryDir)) {
3292 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3293 }
3294 } else if (!isExternal(pkg)) {
3295 Log.i(TAG, path + " changed; unpacking");
Kenny Root6a6b0072010-10-07 16:46:10 -07003296 mInstaller.unlinkNativeLibraryDirectory(dataPath.getPath());
Kenny Root831baa22010-10-05 12:29:25 -07003297 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003298 } else {
3299 mInstaller.linkNativeLibraryDirectory(dataPath.getPath(),
3300 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003301 }
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
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003338 // Take care of first install / last update times.
3339 if (currentTime != 0) {
3340 if (pkgSetting.firstInstallTime == 0) {
3341 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3342 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3343 pkgSetting.lastUpdateTime = currentTime;
3344 }
3345 } else if (pkgSetting.firstInstallTime == 0) {
3346 // We need *something*. Take time time stamp of the file.
3347 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3348 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3349 if (scanFileTime != pkgSetting.timeStamp) {
3350 // A package on the system image has changed; consider this
3351 // to be an update.
3352 pkgSetting.lastUpdateTime = scanFileTime;
3353 }
3354 }
3355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 int N = pkg.providers.size();
3357 StringBuilder r = null;
3358 int i;
3359 for (i=0; i<N; i++) {
3360 PackageParser.Provider p = pkg.providers.get(i);
3361 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3362 p.info.processName, pkg.applicationInfo.uid);
3363 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3364 p.info.name), p);
3365 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003366 if (p.info.authority != null) {
3367 String names[] = p.info.authority.split(";");
3368 p.info.authority = null;
3369 for (int j = 0; j < names.length; j++) {
3370 if (j == 1 && p.syncable) {
3371 // We only want the first authority for a provider to possibly be
3372 // syncable, so if we already added this provider using a different
3373 // authority clear the syncable flag. We copy the provider before
3374 // changing it because the mProviders object contains a reference
3375 // to a provider that we don't want to change.
3376 // Only do this for the second authority since the resulting provider
3377 // object can be the same for all future authorities for this provider.
3378 p = new PackageParser.Provider(p);
3379 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003381 if (!mProviders.containsKey(names[j])) {
3382 mProviders.put(names[j], p);
3383 if (p.info.authority == null) {
3384 p.info.authority = names[j];
3385 } else {
3386 p.info.authority = p.info.authority + ";" + names[j];
3387 }
3388 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3389 Log.d(TAG, "Registered content provider: " + names[j] +
3390 ", className = " + p.info.name +
3391 ", isSyncable = " + p.info.isSyncable);
3392 } else {
3393 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003394 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003395 " (in package " + pkg.applicationInfo.packageName +
3396 "): name already used by "
3397 + ((other != null && other.getComponentName() != null)
3398 ? other.getComponentName().getPackageName() : "?"));
3399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 }
3401 }
3402 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3403 if (r == null) {
3404 r = new StringBuilder(256);
3405 } else {
3406 r.append(' ');
3407 }
3408 r.append(p.info.name);
3409 }
3410 }
3411 if (r != null) {
3412 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3413 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 N = pkg.services.size();
3416 r = null;
3417 for (i=0; i<N; i++) {
3418 PackageParser.Service s = pkg.services.get(i);
3419 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3420 s.info.processName, pkg.applicationInfo.uid);
3421 mServices.addService(s);
3422 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3423 if (r == null) {
3424 r = new StringBuilder(256);
3425 } else {
3426 r.append(' ');
3427 }
3428 r.append(s.info.name);
3429 }
3430 }
3431 if (r != null) {
3432 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3433 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 N = pkg.receivers.size();
3436 r = null;
3437 for (i=0; i<N; i++) {
3438 PackageParser.Activity a = pkg.receivers.get(i);
3439 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3440 a.info.processName, pkg.applicationInfo.uid);
3441 mReceivers.addActivity(a, "receiver");
3442 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3443 if (r == null) {
3444 r = new StringBuilder(256);
3445 } else {
3446 r.append(' ');
3447 }
3448 r.append(a.info.name);
3449 }
3450 }
3451 if (r != null) {
3452 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 N = pkg.activities.size();
3456 r = null;
3457 for (i=0; i<N; i++) {
3458 PackageParser.Activity a = pkg.activities.get(i);
3459 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3460 a.info.processName, pkg.applicationInfo.uid);
3461 mActivities.addActivity(a, "activity");
3462 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3463 if (r == null) {
3464 r = new StringBuilder(256);
3465 } else {
3466 r.append(' ');
3467 }
3468 r.append(a.info.name);
3469 }
3470 }
3471 if (r != null) {
3472 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3473 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 N = pkg.permissionGroups.size();
3476 r = null;
3477 for (i=0; i<N; i++) {
3478 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3479 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3480 if (cur == null) {
3481 mPermissionGroups.put(pg.info.name, pg);
3482 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3483 if (r == null) {
3484 r = new StringBuilder(256);
3485 } else {
3486 r.append(' ');
3487 }
3488 r.append(pg.info.name);
3489 }
3490 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003491 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 + pg.info.packageName + " ignored: original from "
3493 + cur.info.packageName);
3494 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3495 if (r == null) {
3496 r = new StringBuilder(256);
3497 } else {
3498 r.append(' ');
3499 }
3500 r.append("DUP:");
3501 r.append(pg.info.name);
3502 }
3503 }
3504 }
3505 if (r != null) {
3506 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3507 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 N = pkg.permissions.size();
3510 r = null;
3511 for (i=0; i<N; i++) {
3512 PackageParser.Permission p = pkg.permissions.get(i);
3513 HashMap<String, BasePermission> permissionMap =
3514 p.tree ? mSettings.mPermissionTrees
3515 : mSettings.mPermissions;
3516 p.group = mPermissionGroups.get(p.info.group);
3517 if (p.info.group == null || p.group != null) {
3518 BasePermission bp = permissionMap.get(p.info.name);
3519 if (bp == null) {
3520 bp = new BasePermission(p.info.name, p.info.packageName,
3521 BasePermission.TYPE_NORMAL);
3522 permissionMap.put(p.info.name, bp);
3523 }
3524 if (bp.perm == null) {
3525 if (bp.sourcePackage == null
3526 || bp.sourcePackage.equals(p.info.packageName)) {
3527 BasePermission tree = findPermissionTreeLP(p.info.name);
3528 if (tree == null
3529 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003530 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 bp.perm = p;
3532 bp.uid = pkg.applicationInfo.uid;
3533 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3534 if (r == null) {
3535 r = new StringBuilder(256);
3536 } else {
3537 r.append(' ');
3538 }
3539 r.append(p.info.name);
3540 }
3541 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003542 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 + p.info.packageName + " ignored: base tree "
3544 + tree.name + " is from package "
3545 + tree.sourcePackage);
3546 }
3547 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003548 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 + p.info.packageName + " ignored: original from "
3550 + bp.sourcePackage);
3551 }
3552 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3553 if (r == null) {
3554 r = new StringBuilder(256);
3555 } else {
3556 r.append(' ');
3557 }
3558 r.append("DUP:");
3559 r.append(p.info.name);
3560 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003561 if (bp.perm == p) {
3562 bp.protectionLevel = p.info.protectionLevel;
3563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003564 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003565 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 + p.info.packageName + " ignored: no group "
3567 + p.group);
3568 }
3569 }
3570 if (r != null) {
3571 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 N = pkg.instrumentation.size();
3575 r = null;
3576 for (i=0; i<N; i++) {
3577 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3578 a.info.packageName = pkg.applicationInfo.packageName;
3579 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3580 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3581 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003582 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003583 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3585 if (r == null) {
3586 r = new StringBuilder(256);
3587 } else {
3588 r.append(' ');
3589 }
3590 r.append(a.info.name);
3591 }
3592 }
3593 if (r != null) {
3594 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003596
Dianne Hackborn854060af2009-07-09 18:14:31 -07003597 if (pkg.protectedBroadcasts != null) {
3598 N = pkg.protectedBroadcasts.size();
3599 for (i=0; i<N; i++) {
3600 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3601 }
3602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 pkgSetting.setTimeStamp(scanFileTime);
3605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 return pkg;
3608 }
3609
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003610 private void killApplication(String pkgName, int uid) {
3611 // Request the ActivityManager to kill the process(only for existing packages)
3612 // so that we do not end up in a confused state while the user is still using the older
3613 // version of the application while the new one gets installed.
3614 IActivityManager am = ActivityManagerNative.getDefault();
3615 if (am != null) {
3616 try {
3617 am.killApplicationWithUid(pkgName, uid);
3618 } catch (RemoteException e) {
3619 }
3620 }
3621 }
3622
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003623 // Return the path of the directory that will contain the native binaries
3624 // of a given installed package. This is relative to the data path.
3625 //
Kenny Root85387d72010-08-26 10:13:11 -07003626 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3627 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3628 if (nativeLibraryDir != null) {
3629 return new File(nativeLibraryDir);
3630 } else {
3631 // Fall back for old packages
3632 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3633 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003634 }
3635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3637 if (chatty && Config.LOGD) Log.d(
3638 TAG, "Removing package " + pkg.applicationInfo.packageName );
3639
3640 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 mPackages.remove(pkg.applicationInfo.packageName);
3644 if (pkg.mPath != null) {
3645 mAppDirs.remove(pkg.mPath);
3646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 PackageSetting ps = (PackageSetting)pkg.mExtras;
3649 if (ps != null && ps.sharedUser != null) {
3650 // XXX don't do this until the data is removed.
3651 if (false) {
3652 ps.sharedUser.packages.remove(ps);
3653 if (ps.sharedUser.packages.size() == 0) {
3654 // Remove.
3655 }
3656 }
3657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 int N = pkg.providers.size();
3660 StringBuilder r = null;
3661 int i;
3662 for (i=0; i<N; i++) {
3663 PackageParser.Provider p = pkg.providers.get(i);
3664 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3665 p.info.name));
3666 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 /* The is another ContentProvider with this authority when
3669 * this app was installed so this authority is null,
3670 * Ignore it as we don't have to unregister the provider.
3671 */
3672 continue;
3673 }
3674 String names[] = p.info.authority.split(";");
3675 for (int j = 0; j < names.length; j++) {
3676 if (mProviders.get(names[j]) == p) {
3677 mProviders.remove(names[j]);
3678 if (chatty && Config.LOGD) Log.d(
3679 TAG, "Unregistered content provider: " + names[j] +
3680 ", className = " + p.info.name +
3681 ", isSyncable = " + p.info.isSyncable);
3682 }
3683 }
3684 if (chatty) {
3685 if (r == null) {
3686 r = new StringBuilder(256);
3687 } else {
3688 r.append(' ');
3689 }
3690 r.append(p.info.name);
3691 }
3692 }
3693 if (r != null) {
3694 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 N = pkg.services.size();
3698 r = null;
3699 for (i=0; i<N; i++) {
3700 PackageParser.Service s = pkg.services.get(i);
3701 mServices.removeService(s);
3702 if (chatty) {
3703 if (r == null) {
3704 r = new StringBuilder(256);
3705 } else {
3706 r.append(' ');
3707 }
3708 r.append(s.info.name);
3709 }
3710 }
3711 if (r != null) {
3712 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 N = pkg.receivers.size();
3716 r = null;
3717 for (i=0; i<N; i++) {
3718 PackageParser.Activity a = pkg.receivers.get(i);
3719 mReceivers.removeActivity(a, "receiver");
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, " Receivers: " + r);
3731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 N = pkg.activities.size();
3734 r = null;
3735 for (i=0; i<N; i++) {
3736 PackageParser.Activity a = pkg.activities.get(i);
3737 mActivities.removeActivity(a, "activity");
3738 if (chatty) {
3739 if (r == null) {
3740 r = new StringBuilder(256);
3741 } else {
3742 r.append(' ');
3743 }
3744 r.append(a.info.name);
3745 }
3746 }
3747 if (r != null) {
3748 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3749 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 N = pkg.permissions.size();
3752 r = null;
3753 for (i=0; i<N; i++) {
3754 PackageParser.Permission p = pkg.permissions.get(i);
3755 boolean tree = false;
3756 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3757 if (bp == null) {
3758 tree = true;
3759 bp = mSettings.mPermissionTrees.get(p.info.name);
3760 }
3761 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003762 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 if (chatty) {
3764 if (r == null) {
3765 r = new StringBuilder(256);
3766 } else {
3767 r.append(' ');
3768 }
3769 r.append(p.info.name);
3770 }
3771 }
3772 }
3773 if (r != null) {
3774 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3775 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 N = pkg.instrumentation.size();
3778 r = null;
3779 for (i=0; i<N; i++) {
3780 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003781 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 if (chatty) {
3783 if (r == null) {
3784 r = new StringBuilder(256);
3785 } else {
3786 r.append(' ');
3787 }
3788 r.append(a.info.name);
3789 }
3790 }
3791 if (r != null) {
3792 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3793 }
3794 }
3795 }
3796
3797 private static final boolean isPackageFilename(String name) {
3798 return name != null && name.endsWith(".apk");
3799 }
3800
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003801 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3802 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3803 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3804 return true;
3805 }
3806 }
3807 return false;
3808 }
3809
3810 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003811 PackageParser.Package pkgInfo, boolean grantPermissions,
3812 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 // Make sure there are no dangling permission trees.
3814 Iterator<BasePermission> it = mSettings.mPermissionTrees
3815 .values().iterator();
3816 while (it.hasNext()) {
3817 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003818 if (bp.packageSetting == null) {
3819 // We may not yet have parsed the package, so just see if
3820 // we still know about its settings.
3821 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3822 }
3823 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003824 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 + " from package " + bp.sourcePackage);
3826 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003827 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3828 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3829 Slog.i(TAG, "Removing old permission tree: " + bp.name
3830 + " from package " + bp.sourcePackage);
3831 grantPermissions = true;
3832 it.remove();
3833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
3835 }
3836
3837 // Make sure all dynamic permissions have been assigned to a package,
3838 // and make sure there are no dangling permissions.
3839 it = mSettings.mPermissions.values().iterator();
3840 while (it.hasNext()) {
3841 BasePermission bp = it.next();
3842 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3843 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3844 + bp.name + " pkg=" + bp.sourcePackage
3845 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003846 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 BasePermission tree = findPermissionTreeLP(bp.name);
3848 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003849 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 bp.perm = new PackageParser.Permission(tree.perm.owner,
3851 new PermissionInfo(bp.pendingInfo));
3852 bp.perm.info.packageName = tree.perm.info.packageName;
3853 bp.perm.info.name = bp.name;
3854 bp.uid = tree.uid;
3855 }
3856 }
3857 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003858 if (bp.packageSetting == null) {
3859 // We may not yet have parsed the package, so just see if
3860 // we still know about its settings.
3861 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3862 }
3863 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003864 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 + " from package " + bp.sourcePackage);
3866 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003867 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3868 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3869 Slog.i(TAG, "Removing old permission: " + bp.name
3870 + " from package " + bp.sourcePackage);
3871 grantPermissions = true;
3872 it.remove();
3873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 }
3875 }
3876
3877 // Now update the permissions for all packages, in particular
3878 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003879 if (grantPermissions) {
3880 for (PackageParser.Package pkg : mPackages.values()) {
3881 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003882 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003883 }
3884 }
3885 }
3886
3887 if (pkgInfo != null) {
3888 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 }
3890 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3893 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3894 if (ps == null) {
3895 return;
3896 }
3897 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003898 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 if (replace) {
3901 ps.permissionsFixed = false;
3902 if (gp == ps) {
3903 gp.grantedPermissions.clear();
3904 gp.gids = mGlobalGids;
3905 }
3906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 if (gp.gids == null) {
3909 gp.gids = mGlobalGids;
3910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 final int N = pkg.requestedPermissions.size();
3913 for (int i=0; i<N; i++) {
3914 String name = pkg.requestedPermissions.get(i);
3915 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 if (false) {
3917 if (gp != ps) {
3918 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003919 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 }
3921 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003922 if (bp != null && bp.packageSetting != null) {
3923 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003925 boolean allowedSig = false;
3926 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3927 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003929 } else if (bp.packageSetting == null) {
3930 // This permission is invalid; skip it.
3931 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003932 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3933 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003934 allowed = (checkSignaturesLP(
3935 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003937 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003939 if (!allowed && bp.protectionLevel
3940 == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003941 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003942 // For updated system applications, the signatureOrSystem permission
3943 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003944 if (isUpdatedSystemApp(pkg)) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003945 PackageSetting sysPs = mSettings.getDisabledSystemPkg(
3946 pkg.packageName);
3947 final GrantedPermissions origGp = sysPs.sharedUser != null
3948 ? sysPs.sharedUser : sysPs;
3949 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 allowed = true;
3951 } else {
3952 allowed = false;
3953 }
3954 } else {
3955 allowed = true;
3956 }
3957 }
3958 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003959 if (allowed) {
3960 allowedSig = true;
3961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 } else {
3963 allowed = false;
3964 }
3965 if (false) {
3966 if (gp != ps) {
3967 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3968 }
3969 }
3970 if (allowed) {
3971 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3972 && ps.permissionsFixed) {
3973 // If this is an existing, non-system package, then
3974 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003975 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003977 // Except... if this is a permission that was added
3978 // to the platform (note: need to only do this when
3979 // updating the platform).
3980 final int NP = PackageParser.NEW_PERMISSIONS.length;
3981 for (int ip=0; ip<NP; ip++) {
3982 final PackageParser.NewPermissionInfo npi
3983 = PackageParser.NEW_PERMISSIONS[ip];
3984 if (npi.name.equals(perm)
3985 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3986 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003987 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003988 + pkg.packageName);
3989 break;
3990 }
3991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 }
3993 }
3994 if (allowed) {
3995 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003996 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 gp.grantedPermissions.add(perm);
3998 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003999 } else if (!ps.haveGids) {
4000 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 }
4002 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004003 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 + " to package " + pkg.packageName
4005 + " because it was previously installed without");
4006 }
4007 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004008 if (gp.grantedPermissions.remove(perm)) {
4009 changedPermission = true;
4010 gp.gids = removeInts(gp.gids, bp.gids);
4011 Slog.i(TAG, "Un-granting permission " + perm
4012 + " from package " + pkg.packageName
4013 + " (protectionLevel=" + bp.protectionLevel
4014 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4015 + ")");
4016 } else {
4017 Slog.w(TAG, "Not granting permission " + perm
4018 + " to package " + pkg.packageName
4019 + " (protectionLevel=" + bp.protectionLevel
4020 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4021 + ")");
4022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004023 }
4024 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004025 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 + " in package " + pkg.packageName);
4027 }
4028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004029
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004030 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004031 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4032 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 // This is the first that we have heard about this package, so the
4034 // permissions we have now selected are fixed until explicitly
4035 // changed.
4036 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004038 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 private final class ActivityIntentResolver
4042 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004043 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004045 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 }
4047
Mihai Preda074edef2009-05-18 17:13:31 +02004048 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004050 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4052 }
4053
Mihai Predaeae850c2009-05-13 10:13:48 +02004054 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4055 ArrayList<PackageParser.Activity> packageActivities) {
4056 if (packageActivities == null) {
4057 return null;
4058 }
4059 mFlags = flags;
4060 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4061 int N = packageActivities.size();
4062 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4063 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004064
4065 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004066 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004067 intentFilters = packageActivities.get(i).intents;
4068 if (intentFilters != null && intentFilters.size() > 0) {
4069 listCut.add(intentFilters);
4070 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004071 }
4072 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4073 }
4074
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004075 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004076 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 if (SHOW_INFO || Config.LOGV) Log.v(
4078 TAG, " " + type + " " +
4079 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4080 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4081 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004082 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004083 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4084 if (SHOW_INFO || Config.LOGV) {
4085 Log.v(TAG, " IntentFilter:");
4086 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4087 }
4088 if (!intent.debugCheck()) {
4089 Log.w(TAG, "==> For Activity " + a.info.name);
4090 }
4091 addFilter(intent);
4092 }
4093 }
4094
4095 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004096 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 if (SHOW_INFO || Config.LOGV) Log.v(
4098 TAG, " " + type + " " +
4099 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4100 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4101 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004102 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4104 if (SHOW_INFO || Config.LOGV) {
4105 Log.v(TAG, " IntentFilter:");
4106 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4107 }
4108 removeFilter(intent);
4109 }
4110 }
4111
4112 @Override
4113 protected boolean allowFilterResult(
4114 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4115 ActivityInfo filterAi = filter.activity.info;
4116 for (int i=dest.size()-1; i>=0; i--) {
4117 ActivityInfo destAi = dest.get(i).activityInfo;
4118 if (destAi.name == filterAi.name
4119 && destAi.packageName == filterAi.packageName) {
4120 return false;
4121 }
4122 }
4123 return true;
4124 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004127 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4128 return info.activity.owner.packageName;
4129 }
4130
4131 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4133 int match) {
4134 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4135 return null;
4136 }
4137 final PackageParser.Activity activity = info.activity;
4138 if (mSafeMode && (activity.info.applicationInfo.flags
4139 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4140 return null;
4141 }
4142 final ResolveInfo res = new ResolveInfo();
4143 res.activityInfo = PackageParser.generateActivityInfo(activity,
4144 mFlags);
4145 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4146 res.filter = info;
4147 }
4148 res.priority = info.getPriority();
4149 res.preferredOrder = activity.owner.mPreferredOrder;
4150 //System.out.println("Result: " + res.activityInfo.className +
4151 // " = " + res.priority);
4152 res.match = match;
4153 res.isDefault = info.hasDefault;
4154 res.labelRes = info.labelRes;
4155 res.nonLocalizedLabel = info.nonLocalizedLabel;
4156 res.icon = info.icon;
4157 return res;
4158 }
4159
4160 @Override
4161 protected void sortResults(List<ResolveInfo> results) {
4162 Collections.sort(results, mResolvePrioritySorter);
4163 }
4164
4165 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004166 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004167 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004168 out.print(prefix); out.print(
4169 Integer.toHexString(System.identityHashCode(filter.activity)));
4170 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004171 out.print(filter.activity.getComponentShortName());
4172 out.print(" filter ");
4173 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 }
4175
4176// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4177// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4178// final List<ResolveInfo> retList = Lists.newArrayList();
4179// while (i.hasNext()) {
4180// final ResolveInfo resolveInfo = i.next();
4181// if (isEnabledLP(resolveInfo.activityInfo)) {
4182// retList.add(resolveInfo);
4183// }
4184// }
4185// return retList;
4186// }
4187
4188 // Keys are String (activity class name), values are Activity.
4189 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4190 = new HashMap<ComponentName, PackageParser.Activity>();
4191 private int mFlags;
4192 }
4193
4194 private final class ServiceIntentResolver
4195 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004196 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004198 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 }
4200
Mihai Preda074edef2009-05-18 17:13:31 +02004201 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004202 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004203 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4205 }
4206
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004207 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4208 ArrayList<PackageParser.Service> packageServices) {
4209 if (packageServices == null) {
4210 return null;
4211 }
4212 mFlags = flags;
4213 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4214 int N = packageServices.size();
4215 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4216 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4217
4218 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4219 for (int i = 0; i < N; ++i) {
4220 intentFilters = packageServices.get(i).intents;
4221 if (intentFilters != null && intentFilters.size() > 0) {
4222 listCut.add(intentFilters);
4223 }
4224 }
4225 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4226 }
4227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004229 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 if (SHOW_INFO || Config.LOGV) Log.v(
4231 TAG, " " + (s.info.nonLocalizedLabel != null
4232 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4233 if (SHOW_INFO || Config.LOGV) Log.v(
4234 TAG, " Class=" + s.info.name);
4235 int NI = s.intents.size();
4236 int j;
4237 for (j=0; j<NI; j++) {
4238 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4239 if (SHOW_INFO || Config.LOGV) {
4240 Log.v(TAG, " IntentFilter:");
4241 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4242 }
4243 if (!intent.debugCheck()) {
4244 Log.w(TAG, "==> For Service " + s.info.name);
4245 }
4246 addFilter(intent);
4247 }
4248 }
4249
4250 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004251 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004252 if (SHOW_INFO || Config.LOGV) Log.v(
4253 TAG, " " + (s.info.nonLocalizedLabel != null
4254 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4255 if (SHOW_INFO || Config.LOGV) Log.v(
4256 TAG, " Class=" + s.info.name);
4257 int NI = s.intents.size();
4258 int j;
4259 for (j=0; j<NI; j++) {
4260 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4261 if (SHOW_INFO || Config.LOGV) {
4262 Log.v(TAG, " IntentFilter:");
4263 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4264 }
4265 removeFilter(intent);
4266 }
4267 }
4268
4269 @Override
4270 protected boolean allowFilterResult(
4271 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4272 ServiceInfo filterSi = filter.service.info;
4273 for (int i=dest.size()-1; i>=0; i--) {
4274 ServiceInfo destAi = dest.get(i).serviceInfo;
4275 if (destAi.name == filterSi.name
4276 && destAi.packageName == filterSi.packageName) {
4277 return false;
4278 }
4279 }
4280 return true;
4281 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004284 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4285 return info.service.owner.packageName;
4286 }
4287
4288 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004289 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4290 int match) {
4291 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4292 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4293 return null;
4294 }
4295 final PackageParser.Service service = info.service;
4296 if (mSafeMode && (service.info.applicationInfo.flags
4297 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4298 return null;
4299 }
4300 final ResolveInfo res = new ResolveInfo();
4301 res.serviceInfo = PackageParser.generateServiceInfo(service,
4302 mFlags);
4303 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4304 res.filter = filter;
4305 }
4306 res.priority = info.getPriority();
4307 res.preferredOrder = service.owner.mPreferredOrder;
4308 //System.out.println("Result: " + res.activityInfo.className +
4309 // " = " + res.priority);
4310 res.match = match;
4311 res.isDefault = info.hasDefault;
4312 res.labelRes = info.labelRes;
4313 res.nonLocalizedLabel = info.nonLocalizedLabel;
4314 res.icon = info.icon;
4315 return res;
4316 }
4317
4318 @Override
4319 protected void sortResults(List<ResolveInfo> results) {
4320 Collections.sort(results, mResolvePrioritySorter);
4321 }
4322
4323 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004324 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004325 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004326 out.print(prefix); out.print(
4327 Integer.toHexString(System.identityHashCode(filter.service)));
4328 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004329 out.print(filter.service.getComponentShortName());
4330 out.print(" filter ");
4331 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 }
4333
4334// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4335// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4336// final List<ResolveInfo> retList = Lists.newArrayList();
4337// while (i.hasNext()) {
4338// final ResolveInfo resolveInfo = (ResolveInfo) i;
4339// if (isEnabledLP(resolveInfo.serviceInfo)) {
4340// retList.add(resolveInfo);
4341// }
4342// }
4343// return retList;
4344// }
4345
4346 // Keys are String (activity class name), values are Activity.
4347 private final HashMap<ComponentName, PackageParser.Service> mServices
4348 = new HashMap<ComponentName, PackageParser.Service>();
4349 private int mFlags;
4350 };
4351
4352 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4353 new Comparator<ResolveInfo>() {
4354 public int compare(ResolveInfo r1, ResolveInfo r2) {
4355 int v1 = r1.priority;
4356 int v2 = r2.priority;
4357 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4358 if (v1 != v2) {
4359 return (v1 > v2) ? -1 : 1;
4360 }
4361 v1 = r1.preferredOrder;
4362 v2 = r2.preferredOrder;
4363 if (v1 != v2) {
4364 return (v1 > v2) ? -1 : 1;
4365 }
4366 if (r1.isDefault != r2.isDefault) {
4367 return r1.isDefault ? -1 : 1;
4368 }
4369 v1 = r1.match;
4370 v2 = r2.match;
4371 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4372 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4373 }
4374 };
4375
4376 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4377 new Comparator<ProviderInfo>() {
4378 public int compare(ProviderInfo p1, ProviderInfo p2) {
4379 final int v1 = p1.initOrder;
4380 final int v2 = p2.initOrder;
4381 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4382 }
4383 };
4384
Kenny Root93565c4b2010-06-18 15:46:06 -07004385 private static final boolean DEBUG_OBB = false;
4386
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004387 private static final void sendPackageBroadcast(String action, String pkg,
4388 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004389 IActivityManager am = ActivityManagerNative.getDefault();
4390 if (am != null) {
4391 try {
4392 final Intent intent = new Intent(action,
4393 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4394 if (extras != null) {
4395 intent.putExtras(extras);
4396 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004397 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004398 am.broadcastIntent(null, intent, null, finishedReceiver,
4399 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004400 } catch (RemoteException ex) {
4401 }
4402 }
4403 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004404
4405 public String nextPackageToClean(String lastPackage) {
4406 synchronized (mPackages) {
4407 if (!mMediaMounted) {
4408 // If the external storage is no longer mounted at this point,
4409 // the caller may not have been able to delete all of this
4410 // packages files and can not delete any more. Bail.
4411 return null;
4412 }
4413 if (lastPackage != null) {
4414 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4415 }
4416 return mSettings.mPackagesToBeCleaned.size() > 0
4417 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4418 }
4419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004421 void schedulePackageCleaning(String packageName) {
4422 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4423 }
4424
4425 void startCleaningPackages() {
4426 synchronized (mPackages) {
4427 if (!mMediaMounted) {
4428 return;
4429 }
4430 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4431 return;
4432 }
4433 }
4434 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4435 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4436 IActivityManager am = ActivityManagerNative.getDefault();
4437 if (am != null) {
4438 try {
4439 am.startService(null, intent, null);
4440 } catch (RemoteException e) {
4441 }
4442 }
4443 }
4444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 private final class AppDirObserver extends FileObserver {
4446 public AppDirObserver(String path, int mask, boolean isrom) {
4447 super(path, mask);
4448 mRootDir = path;
4449 mIsRom = isrom;
4450 }
4451
4452 public void onEvent(int event, String path) {
4453 String removedPackage = null;
4454 int removedUid = -1;
4455 String addedPackage = null;
4456 int addedUid = -1;
4457
4458 synchronized (mInstallLock) {
4459 String fullPathStr = null;
4460 File fullPath = null;
4461 if (path != null) {
4462 fullPath = new File(mRootDir, path);
4463 fullPathStr = fullPath.getPath();
4464 }
4465
4466 if (Config.LOGV) Log.v(
4467 TAG, "File " + fullPathStr + " changed: "
4468 + Integer.toHexString(event));
4469
4470 if (!isPackageFilename(path)) {
4471 if (Config.LOGV) Log.v(
4472 TAG, "Ignoring change of non-package file: " + fullPathStr);
4473 return;
4474 }
4475
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004476 // Ignore packages that are being installed or
4477 // have just been installed.
4478 if (ignoreCodePath(fullPathStr)) {
4479 return;
4480 }
4481 PackageParser.Package p = null;
4482 synchronized (mPackages) {
4483 p = mAppDirs.get(fullPathStr);
4484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004486 if (p != null) {
4487 removePackageLI(p, true);
4488 removedPackage = p.applicationInfo.packageName;
4489 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004490 }
4491 }
4492
4493 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004495 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004496 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4497 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004498 PackageParser.PARSE_CHATTY |
4499 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004500 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4501 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004502 if (p != null) {
4503 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004504 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004505 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
4507 addedPackage = p.applicationInfo.packageName;
4508 addedUid = p.applicationInfo.uid;
4509 }
4510 }
4511 }
4512
4513 synchronized (mPackages) {
4514 mSettings.writeLP();
4515 }
4516 }
4517
4518 if (removedPackage != null) {
4519 Bundle extras = new Bundle(1);
4520 extras.putInt(Intent.EXTRA_UID, removedUid);
4521 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004522 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4523 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004524 }
4525 if (addedPackage != null) {
4526 Bundle extras = new Bundle(1);
4527 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004528 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4529 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004530 }
4531 }
4532
4533 private final String mRootDir;
4534 private final boolean mIsRom;
4535 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 /* Called when a downloaded package installation has been confirmed by the user */
4538 public void installPackage(
4539 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004540 installPackage(packageURI, observer, flags, null);
4541 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004542
Jacek Surazski65e13172009-04-28 15:26:38 +02004543 /* Called when a downloaded package installation has been confirmed by the user */
4544 public void installPackage(
4545 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4546 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004547 mContext.enforceCallingOrSelfPermission(
4548 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004549
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004550 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004551 msg.obj = new InstallParams(packageURI, observer, flags,
4552 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004553 mHandler.sendMessage(msg);
4554 }
4555
Christopher Tate1bb69062010-02-19 17:02:12 -08004556 public void finishPackageInstall(int token) {
4557 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4558 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4559 mHandler.sendMessage(msg);
4560 }
4561
Kenny Root93565c4b2010-06-18 15:46:06 -07004562 public void setPackageObbPath(String packageName, String path) {
4563 if (DEBUG_OBB)
4564 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4565 PackageSetting pkgSetting;
4566 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004567 final int permission = mContext.checkCallingPermission(
4568 android.Manifest.permission.INSTALL_PACKAGES);
4569 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004570 synchronized (mPackages) {
4571 pkgSetting = mSettings.mPackages.get(packageName);
4572 if (pkgSetting == null) {
4573 throw new IllegalArgumentException("Unknown package: " + packageName);
4574 }
4575 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4576 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4577 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4578 + pkgSetting.userId);
4579 }
4580 pkgSetting.obbPathString = path;
4581 mSettings.writeLP();
4582 }
4583 }
4584
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004585 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004586 // Queue up an async operation since the package installation may take a little while.
4587 mHandler.post(new Runnable() {
4588 public void run() {
4589 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004590 // Result object to be returned
4591 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004592 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004593 res.uid = -1;
4594 res.pkg = null;
4595 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004596 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004597 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004598 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004599 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004600 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004601 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004603
4604 // A restore should be performed at this point if (a) the install
4605 // succeeded, (b) the operation is not an update, and (c) the new
4606 // package has a backupAgent defined.
4607 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004608 boolean doRestore = (!update
4609 && res.pkg != null
4610 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004611
4612 // Set up the post-install work request bookkeeping. This will be used
4613 // and cleaned up by the post-install event handling regardless of whether
4614 // there's a restore pass performed. Token values are >= 1.
4615 int token;
4616 if (mNextInstallToken < 0) mNextInstallToken = 1;
4617 token = mNextInstallToken++;
4618
4619 PostInstallData data = new PostInstallData(args, res);
4620 mRunningInstalls.put(token, data);
4621 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4622
4623 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4624 // Pass responsibility to the Backup Manager. It will perform a
4625 // restore if appropriate, then pass responsibility back to the
4626 // Package Manager to run the post-install observer callbacks
4627 // and broadcasts.
4628 IBackupManager bm = IBackupManager.Stub.asInterface(
4629 ServiceManager.getService(Context.BACKUP_SERVICE));
4630 if (bm != null) {
4631 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4632 + " to BM for possible restore");
4633 try {
4634 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4635 } catch (RemoteException e) {
4636 // can't happen; the backup manager is local
4637 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004638 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004639 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004640 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004641 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004642 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004643 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004645 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004646
4647 if (!doRestore) {
4648 // No restore possible, or the Backup Manager was mysteriously not
4649 // available -- just fire the post-install work request directly.
4650 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4651 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4652 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004654 }
4655 });
4656 }
4657
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004658 abstract class HandlerParams {
4659 final static int MAX_RETRIES = 4;
4660 int retry = 0;
4661 final void startCopy() {
4662 try {
4663 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4664 retry++;
4665 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004666 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004667 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4668 handleServiceError();
4669 return;
4670 } else {
4671 handleStartCopy();
4672 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4673 mHandler.sendEmptyMessage(MCS_UNBIND);
4674 }
4675 } catch (RemoteException e) {
4676 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4677 mHandler.sendEmptyMessage(MCS_RECONNECT);
4678 }
4679 handleReturnCode();
4680 }
4681
4682 final void serviceError() {
4683 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4684 handleServiceError();
4685 handleReturnCode();
4686 }
4687 abstract void handleStartCopy() throws RemoteException;
4688 abstract void handleServiceError();
4689 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004690 }
4691
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004692 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004693 final IPackageInstallObserver observer;
4694 int flags;
4695 final Uri packageURI;
4696 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004697 private InstallArgs mArgs;
4698 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004699 InstallParams(Uri packageURI,
4700 IPackageInstallObserver observer, int flags,
4701 String installerPackageName) {
4702 this.packageURI = packageURI;
4703 this.flags = flags;
4704 this.observer = observer;
4705 this.installerPackageName = installerPackageName;
4706 }
4707
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004708 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4709 String packageName = pkgLite.packageName;
4710 int installLocation = pkgLite.installLocation;
4711 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4712 synchronized (mPackages) {
4713 PackageParser.Package pkg = mPackages.get(packageName);
4714 if (pkg != null) {
4715 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4716 // Check for updated system application.
4717 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4718 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004719 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004720 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4721 }
4722 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4723 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004724 if (onSd) {
4725 // Install flag overrides everything.
4726 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4727 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004728 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004729 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4730 // Application explicitly specified internal.
4731 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4732 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4733 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004734 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004735 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004736 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004737 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4738 }
4739 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004740 }
4741 }
4742 } else {
4743 // Invalid install. Return error code
4744 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4745 }
4746 }
4747 }
4748 // All the special cases have been taken care of.
4749 // Return result based on recommended install location.
4750 if (onSd) {
4751 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4752 }
4753 return pkgLite.recommendedInstallLocation;
4754 }
4755
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004756 /*
4757 * Invoke remote method to get package information and install
4758 * location values. Override install location based on default
4759 * policy if needed and then create install arguments based
4760 * on the install location.
4761 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004762 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004763 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004764 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4765 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004766 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4767 if (onInt && onSd) {
4768 // Check if both bits are set.
4769 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4770 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4771 } else if (fwdLocked && onSd) {
4772 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004773 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004774 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004775 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004776 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004777 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004778 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004779 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4780 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4781 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4782 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4783 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004784 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4785 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4786 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004787 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4788 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004789 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004790 // Override with defaults if needed.
4791 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004792 if (!onSd && !onInt) {
4793 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004794 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4795 // Set the flag to install on external media.
4796 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004797 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004798 } else {
4799 // Make sure the flag for installing on external
4800 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004801 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004802 flags &= ~PackageManager.INSTALL_EXTERNAL;
4803 }
4804 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004805 }
4806 }
4807 // Create the file args now.
4808 mArgs = createInstallArgs(this);
4809 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4810 // Create copy only if we are not in an erroneous state.
4811 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004812 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004813 }
4814 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004815 }
4816
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004817 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004818 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004819 // If mArgs is null, then MCS couldn't be reached. When it
4820 // reconnects, it will try again to install. At that point, this
4821 // will succeed.
4822 if (mArgs != null) {
4823 processPendingInstall(mArgs, mRet);
4824 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004825 }
4826
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004827 @Override
4828 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004829 mArgs = createInstallArgs(this);
4830 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004831 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004832 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004833
4834 /*
4835 * Utility class used in movePackage api.
4836 * srcArgs and targetArgs are not set for invalid flags and make
4837 * sure to do null checks when invoking methods on them.
4838 * We probably want to return ErrorPrams for both failed installs
4839 * and moves.
4840 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004841 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004842 final IPackageMoveObserver observer;
4843 final int flags;
4844 final String packageName;
4845 final InstallArgs srcArgs;
4846 final InstallArgs targetArgs;
4847 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004848
4849 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4850 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004851 this.srcArgs = srcArgs;
4852 this.observer = observer;
4853 this.flags = flags;
4854 this.packageName = packageName;
4855 if (srcArgs != null) {
4856 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004857 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 } else {
4859 targetArgs = null;
4860 }
4861 }
4862
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004863 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004864 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4865 // Check for storage space on target medium
4866 if (!targetArgs.checkFreeStorage(mContainerService)) {
4867 Log.w(TAG, "Insufficient storage to install");
4868 return;
4869 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004870 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004871 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004872 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004873 if (DEBUG_SD_INSTALL) {
4874 StringBuilder builder = new StringBuilder();
4875 if (srcArgs != null) {
4876 builder.append("src: ");
4877 builder.append(srcArgs.getCodePath());
4878 }
4879 if (targetArgs != null) {
4880 builder.append(" target : ");
4881 builder.append(targetArgs.getCodePath());
4882 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004883 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004884 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004885 }
4886
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004887 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004888 void handleReturnCode() {
4889 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004890 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4891 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4892 currentStatus = PackageManager.MOVE_SUCCEEDED;
4893 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4894 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4895 }
4896 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004897 }
4898
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004899 @Override
4900 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004901 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004902 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004903 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004904
4905 private InstallArgs createInstallArgs(InstallParams params) {
4906 if (installOnSd(params.flags)) {
4907 return new SdInstallArgs(params);
4908 } else {
4909 return new FileInstallArgs(params);
4910 }
4911 }
4912
Kenny Root85387d72010-08-26 10:13:11 -07004913 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4914 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004915 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004916 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004917 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004918 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004919 }
4920 }
4921
Kenny Root85387d72010-08-26 10:13:11 -07004922 // Used by package mover
4923 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004924 if (installOnSd(flags)) {
4925 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4926 return new SdInstallArgs(packageURI, cid);
4927 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004928 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004929 }
4930 }
4931
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004932 static abstract class InstallArgs {
4933 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004934 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004935 final int flags;
4936 final Uri packageURI;
4937 final String installerPackageName;
4938
4939 InstallArgs(Uri packageURI,
4940 IPackageInstallObserver observer, int flags,
4941 String installerPackageName) {
4942 this.packageURI = packageURI;
4943 this.flags = flags;
4944 this.observer = observer;
4945 this.installerPackageName = installerPackageName;
4946 }
4947
4948 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004949 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004950 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004951 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004952 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004953 abstract String getCodePath();
4954 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004955 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004956 // Need installer lock especially for dex file removal.
4957 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004958 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004959 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004960 }
4961
4962 class FileInstallArgs extends InstallArgs {
4963 File installDir;
4964 String codeFileName;
4965 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004966 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004967 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004968
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004969 FileInstallArgs(InstallParams params) {
4970 super(params.packageURI, params.observer,
4971 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004972 }
4973
Kenny Root85387d72010-08-26 10:13:11 -07004974 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004975 super(null, null, 0, null);
4976 File codeFile = new File(fullCodePath);
4977 installDir = codeFile.getParentFile();
4978 codeFileName = fullCodePath;
4979 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004980 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004981 }
4982
Kenny Root85387d72010-08-26 10:13:11 -07004983 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004984 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004985 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004986 String apkName = getNextCodePath(null, pkgName, ".apk");
4987 codeFileName = new File(installDir, apkName + ".apk").getPath();
4988 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004989 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 }
4991
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004992 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4993 return imcs.checkFreeStorage(false, packageURI);
4994 }
4995
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004996 String getCodePath() {
4997 return codeFileName;
4998 }
4999
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005000 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005001 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005002 codeFileName = createTempPackageFile(installDir).getPath();
5003 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005004 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005005 }
5006
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005007 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005008 if (temp) {
5009 // Generate temp file name
5010 createCopyFile();
5011 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005012 // Get a ParcelFileDescriptor to write to the output file
5013 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005014 if (!created) {
5015 try {
5016 codeFile.createNewFile();
5017 // Set permissions
5018 if (!setPermissions()) {
5019 // Failed setting permissions.
5020 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5021 }
5022 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005023 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005024 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5025 }
5026 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005027 ParcelFileDescriptor out = null;
5028 try {
Kenny Root85387d72010-08-26 10:13:11 -07005029 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005030 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005031 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005032 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5033 }
5034 // Copy the resource now
5035 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5036 try {
5037 if (imcs.copyResource(packageURI, out)) {
5038 ret = PackageManager.INSTALL_SUCCEEDED;
5039 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005040 } finally {
5041 try { if (out != null) out.close(); } catch (IOException e) {}
5042 }
Kenny Root85387d72010-08-26 10:13:11 -07005043
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005044 return ret;
5045 }
5046
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005047 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005048 if (status != PackageManager.INSTALL_SUCCEEDED) {
5049 cleanUp();
5050 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005051 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005052 }
5053
5054 boolean doRename(int status, final String pkgName, String oldCodePath) {
5055 if (status != PackageManager.INSTALL_SUCCEEDED) {
5056 cleanUp();
5057 return false;
5058 } else {
5059 // Rename based on packageName
5060 File codeFile = new File(getCodePath());
5061 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5062 File desFile = new File(installDir, apkName + ".apk");
5063 if (!codeFile.renameTo(desFile)) {
5064 return false;
5065 }
5066 // Reset paths since the file has been renamed.
5067 codeFileName = desFile.getPath();
5068 resourceFileName = getResourcePathFromCodePath();
5069 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005070 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005071 // Failed setting permissions.
5072 return false;
5073 }
5074 return true;
5075 }
5076 }
5077
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005078 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005079 if (status != PackageManager.INSTALL_SUCCEEDED) {
5080 cleanUp();
5081 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005082 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005083 }
5084
5085 String getResourcePath() {
5086 return resourceFileName;
5087 }
5088
5089 String getResourcePathFromCodePath() {
5090 String codePath = getCodePath();
5091 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5092 String apkNameOnly = getApkName(codePath);
5093 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5094 } else {
5095 return codePath;
5096 }
5097 }
5098
Kenny Root85387d72010-08-26 10:13:11 -07005099 @Override
5100 String getNativeLibraryPath() {
5101 return libraryPath;
5102 }
5103
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005104 private boolean cleanUp() {
5105 boolean ret = true;
5106 String sourceDir = getCodePath();
5107 String publicSourceDir = getResourcePath();
5108 if (sourceDir != null) {
5109 File sourceFile = new File(sourceDir);
5110 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005111 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005112 ret = false;
5113 }
5114 // Delete application's code and resources
5115 sourceFile.delete();
5116 }
5117 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5118 final File publicSourceFile = new File(publicSourceDir);
5119 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005120 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005121 }
5122 if (publicSourceFile.exists()) {
5123 publicSourceFile.delete();
5124 }
5125 }
5126 return ret;
5127 }
5128
5129 void cleanUpResourcesLI() {
5130 String sourceDir = getCodePath();
5131 if (cleanUp() && mInstaller != null) {
5132 int retCode = mInstaller.rmdex(sourceDir);
5133 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005134 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005135 + " at location "
5136 + sourceDir + ", retcode=" + retCode);
5137 // we don't consider this to be a failure of the core package deletion
5138 }
5139 }
Kenny Root85387d72010-08-26 10:13:11 -07005140 if (libraryPath != null) {
Kenny Root8f7cc022010-09-12 09:04:56 -07005141 NativeLibraryHelper.removeNativeBinariesLI(libraryPath);
Kenny Root85387d72010-08-26 10:13:11 -07005142 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005143 }
5144
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005145 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005146 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005147 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005148 final int filePermissions =
5149 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5150 |FileUtils.S_IROTH;
5151 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5152 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005153 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005154 getCodePath()
5155 + ". The return code was: " + retCode);
5156 // TODO Define new internal error
5157 return false;
5158 }
5159 return true;
5160 }
5161 return true;
5162 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005163
5164 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005165 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005166 cleanUpResourcesLI();
5167 return true;
5168 }
Kenny Root85387d72010-08-26 10:13:11 -07005169
5170 private boolean isFwdLocked() {
5171 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5172 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005173 }
5174
5175 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005176 static final String RES_FILE_NAME = "pkg.apk";
5177
Kenny Root85387d72010-08-26 10:13:11 -07005178 String cid;
5179 String packagePath;
5180 String libraryPath;
5181
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005182 SdInstallArgs(InstallParams params) {
5183 super(params.packageURI, params.observer,
5184 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005185 }
5186
Kenny Root85387d72010-08-26 10:13:11 -07005187 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005188 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005189 // Extract cid from fullCodePath
5190 int eidx = fullCodePath.lastIndexOf("/");
5191 String subStr1 = fullCodePath.substring(0, eidx);
5192 int sidx = subStr1.lastIndexOf("/");
5193 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005194 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005195 }
5196
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005197 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005198 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5199 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005200 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005201 }
5202
5203 SdInstallArgs(Uri packageURI, String cid) {
5204 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005205 this.cid = cid;
5206 }
5207
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005208 void createCopyFile() {
5209 cid = getTempContainerId();
5210 }
5211
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005212 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5213 return imcs.checkFreeStorage(true, packageURI);
5214 }
5215
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005216 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005217 if (temp) {
5218 createCopyFile();
5219 }
Kenny Root85387d72010-08-26 10:13:11 -07005220 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005221 packageURI, cid,
5222 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005223 if (newCachePath != null) {
5224 setCachePath(newCachePath);
5225 return PackageManager.INSTALL_SUCCEEDED;
5226 } else {
5227 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5228 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005229 }
5230
5231 @Override
5232 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005233 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005234 }
5235
5236 @Override
5237 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005238 return packagePath;
5239 }
5240
5241 @Override
5242 String getNativeLibraryPath() {
5243 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005244 }
5245
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005246 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005247 if (status != PackageManager.INSTALL_SUCCEEDED) {
5248 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005249 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005250 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005251 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005252 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005253 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5254 Process.SYSTEM_UID);
5255 if (newCachePath != null) {
5256 setCachePath(newCachePath);
5257 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005258 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5259 }
5260 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005261 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005262 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005263 }
5264
5265 boolean doRename(int status, final String pkgName,
5266 String oldCodePath) {
5267 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005268 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005269 if (PackageHelper.isContainerMounted(cid)) {
5270 // Unmount the container
5271 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005272 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005273 return false;
5274 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005275 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005276 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005277 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5278 " which might be stale. Will try to clean up.");
5279 // Clean up the stale container and proceed to recreate.
5280 if (!PackageHelper.destroySdDir(newCacheId)) {
5281 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5282 return false;
5283 }
5284 // Successfully cleaned up stale container. Try to rename again.
5285 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5286 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5287 + " inspite of cleaning it up.");
5288 return false;
5289 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005290 }
5291 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005292 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005293 newCachePath = PackageHelper.mountSdDir(newCacheId,
5294 getEncryptKey(), Process.SYSTEM_UID);
5295 } else {
5296 newCachePath = PackageHelper.getSdDir(newCacheId);
5297 }
5298 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005299 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005300 return false;
5301 }
5302 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005303 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005304 " at new path: " + newCachePath);
5305 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005306 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005307 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005308 }
5309
Kenny Root85387d72010-08-26 10:13:11 -07005310 private void setCachePath(String newCachePath) {
5311 File cachePath = new File(newCachePath);
5312 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5313 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5314 }
5315
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005316 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005317 if (status != PackageManager.INSTALL_SUCCEEDED) {
5318 cleanUp();
5319 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005320 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005321 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005322 PackageHelper.mountSdDir(cid,
5323 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005324 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005325 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005326 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005327 }
5328
5329 private void cleanUp() {
5330 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005331 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005332 }
5333
5334 void cleanUpResourcesLI() {
5335 String sourceFile = getCodePath();
5336 // Remove dex file
5337 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005338 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005339 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005340 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005341 + " at location "
5342 + sourceFile.toString() + ", retcode=" + retCode);
5343 // we don't consider this to be a failure of the core package deletion
5344 }
5345 }
5346 cleanUp();
5347 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005348
5349 boolean matchContainer(String app) {
5350 if (cid.startsWith(app)) {
5351 return true;
5352 }
5353 return false;
5354 }
5355
5356 String getPackageName() {
5357 int idx = cid.lastIndexOf("-");
5358 if (idx == -1) {
5359 return cid;
5360 }
5361 return cid.substring(0, idx);
5362 }
5363
5364 boolean doPostDeleteLI(boolean delete) {
5365 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005366 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005367 if (mounted) {
5368 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005369 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005370 }
5371 if (ret && delete) {
5372 cleanUpResourcesLI();
5373 }
5374 return ret;
5375 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005376 };
5377
5378 // Utility method used to create code paths based on package name and available index.
5379 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5380 String idxStr = "";
5381 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005382 // Fall back to default value of idx=1 if prefix is not
5383 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005384 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005385 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005386 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005387 if (subStr.endsWith(suffix)) {
5388 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005389 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005390 // If oldCodePath already contains prefix find out the
5391 // ending index to either increment or decrement.
5392 int sidx = subStr.lastIndexOf(prefix);
5393 if (sidx != -1) {
5394 subStr = subStr.substring(sidx + prefix.length());
5395 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005396 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5397 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005398 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005399 try {
5400 idx = Integer.parseInt(subStr);
5401 if (idx <= 1) {
5402 idx++;
5403 } else {
5404 idx--;
5405 }
5406 } catch(NumberFormatException e) {
5407 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005408 }
5409 }
5410 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005411 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005412 return prefix + idxStr;
5413 }
5414
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005415 // Utility method used to ignore ADD/REMOVE events
5416 // by directory observer.
5417 private static boolean ignoreCodePath(String fullPathStr) {
5418 String apkName = getApkName(fullPathStr);
5419 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5420 if (idx != -1 && ((idx+1) < apkName.length())) {
5421 // Make sure the package ends with a numeral
5422 String version = apkName.substring(idx+1);
5423 try {
5424 Integer.parseInt(version);
5425 return true;
5426 } catch (NumberFormatException e) {}
5427 }
5428 return false;
5429 }
5430
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005431 // Utility method that returns the relative package path with respect
5432 // to the installation directory. Like say for /data/data/com.test-1.apk
5433 // string com.test-1 is returned.
5434 static String getApkName(String codePath) {
5435 if (codePath == null) {
5436 return null;
5437 }
5438 int sidx = codePath.lastIndexOf("/");
5439 int eidx = codePath.lastIndexOf(".");
5440 if (eidx == -1) {
5441 eidx = codePath.length();
5442 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005443 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005444 return null;
5445 }
5446 return codePath.substring(sidx+1, eidx);
5447 }
5448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005449 class PackageInstalledInfo {
5450 String name;
5451 int uid;
5452 PackageParser.Package pkg;
5453 int returnCode;
5454 PackageRemovedInfo removedInfo;
5455 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005457 /*
5458 * Install a non-existing package.
5459 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005460 private void installNewPackageLI(PackageParser.Package pkg,
5461 int parseFlags,
5462 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005463 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005464 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005465 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005466
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005467 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 res.name = pkgName;
5469 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005470 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5471 // A package with the same name is already installed, though
5472 // it has been renamed to an older name. The package we
5473 // are trying to install should be installed as an update to
5474 // the existing one, but that has not been requested, so bail.
5475 Slog.w(TAG, "Attempt to re-install " + pkgName
5476 + " without first uninstalling package running as "
5477 + mSettings.mRenamedPackages.get(pkgName));
5478 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5479 return;
5480 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005481 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005482 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005483 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 + " without first uninstalling.");
5485 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5486 return;
5487 }
5488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005490 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5491 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005492 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005493 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5495 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5496 }
5497 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005498 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005499 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 res);
5501 // delete the partially installed application. the data directory will have to be
5502 // restored if it was already existing
5503 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5504 // remove package from internal structures. Note that we want deletePackageX to
5505 // delete the package data and cache directories that it created in
5506 // scanPackageLocked, unless those directories existed before we even tried to
5507 // install.
5508 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005509 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005511 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 }
5513 }
5514 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005515
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005516 private void replacePackageLI(PackageParser.Package pkg,
5517 int parseFlags,
5518 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005519 String installerPackageName, PackageInstalledInfo res) {
5520
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005521 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005522 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 // First find the old package info and check signatures
5524 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005525 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005526 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005527 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5529 return;
5530 }
5531 }
Kenny Root85387d72010-08-26 10:13:11 -07005532 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005533 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005534 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005536 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 }
5538 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005539
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005541 PackageParser.Package pkg,
5542 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005543 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 PackageParser.Package newPackage = null;
5545 String pkgName = deletedPackage.packageName;
5546 boolean deletedPkg = true;
5547 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005548
Jacek Surazski65e13172009-04-28 15:26:38 +02005549 String oldInstallerPackageName = null;
5550 synchronized (mPackages) {
5551 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5552 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005553
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005554 long origUpdateTime;
5555 if (pkg.mExtras != null) {
5556 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5557 } else {
5558 origUpdateTime = 0;
5559 }
5560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005562 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005563 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005564 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5566 deletedPkg = false;
5567 } else {
5568 // Successfully deleted the old package. Now proceed with re-installation
5569 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005570 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5571 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005572 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005573 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5575 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005576 }
5577 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005578 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005579 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005580 res);
5581 updatedSettings = true;
5582 }
5583 }
5584
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005585 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 // remove package from internal structures. Note that we want deletePackageX to
5587 // delete the package data and cache directories that it created in
5588 // scanPackageLocked, unless those directories existed before we even tried to
5589 // install.
5590 if(updatedSettings) {
5591 deletePackageLI(
5592 pkgName, true,
5593 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005594 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 }
5596 // Since we failed to install the new package we need to restore the old
5597 // package that we deleted.
5598 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005599 File restoreFile = new File(deletedPackage.mPath);
5600 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005601 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005602 return;
5603 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005604 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005605 boolean oldOnSd = isExternal(deletedPackage);
5606 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5607 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5608 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005609 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5610 | SCAN_UPDATE_TIME;
5611 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5612 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005613 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5614 return;
5615 }
5616 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005617 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005618 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005619 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005620 mSettings.writeLP();
5621 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005622 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 }
5624 }
5625 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005628 PackageParser.Package pkg,
5629 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005630 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005631 PackageParser.Package newPackage = null;
5632 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005633 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 PackageParser.PARSE_IS_SYSTEM;
5635 String packageName = deletedPackage.packageName;
5636 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5637 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005638 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 return;
5640 }
5641 PackageParser.Package oldPkg;
5642 PackageSetting oldPkgSetting;
5643 synchronized (mPackages) {
5644 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005645 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5647 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005648 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 return;
5650 }
5651 }
5652 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5653 res.removedInfo.removedPackage = packageName;
5654 // Remove existing system package
5655 removePackageLI(oldPkg, true);
5656 synchronized (mPackages) {
5657 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5658 }
5659
5660 // Successfully disabled the old package. Now proceed with re-installation
5661 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5662 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005663 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005665 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005666 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5667 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5668 }
5669 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005670 if (newPackage.mExtras != null) {
5671 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5672 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5673 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5674 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005675 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 updatedSettings = true;
5677 }
5678
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005679 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 // Re installation failed. Restore old information
5681 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005682 if (newPackage != null) {
5683 removePackageLI(newPackage, true);
5684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005686 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005687 // Restore the old system information in Settings
5688 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005689 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005690 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005691 mSettings.setInstallerPackageName(packageName,
5692 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005693 }
5694 mSettings.writeLP();
5695 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005696 } else {
5697 // If this is an update to an existing update, setup
5698 // to remove the existing update.
5699 synchronized (mPackages) {
5700 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5701 if (ps != null && ps.codePathString != null &&
5702 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005703 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005704 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005705 }
5706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 }
5708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005709
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005710 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005711 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005712 int retCode;
5713 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5714 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5715 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005716 if (mNoDexOpt) {
5717 /*
5718 * If we're in an engineering build, programs are lazily run
5719 * through dexopt. If the .dex file doesn't exist yet, it
5720 * will be created when the program is run next.
5721 */
5722 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5723 } else {
5724 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5725 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5726 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005727 }
5728 }
5729 return PackageManager.INSTALL_SUCCEEDED;
5730 }
5731
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005732 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005733 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005734 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005735 synchronized (mPackages) {
5736 //write settings. the installStatus will be incomplete at this stage.
5737 //note that the new package setting would have already been
5738 //added to mPackages. It hasn't been persisted yet.
5739 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5740 mSettings.writeLP();
5741 }
5742
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005743 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005744 != PackageManager.INSTALL_SUCCEEDED) {
5745 // Discontinue if moving dex files failed.
5746 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005747 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005748 if((res.returnCode = setPermissionsLI(newPackage))
5749 != PackageManager.INSTALL_SUCCEEDED) {
5750 if (mInstaller != null) {
5751 mInstaller.rmdex(newPackage.mScanPath);
5752 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005753 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005754 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005755 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005757 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005758 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005759 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 res.name = pkgName;
5761 res.uid = newPackage.applicationInfo.uid;
5762 res.pkg = newPackage;
5763 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005764 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5766 //to update install status
5767 mSettings.writeLP();
5768 }
5769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005770
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005771 private void installPackageLI(InstallArgs args,
5772 boolean newInstall, PackageInstalledInfo res) {
5773 int pFlags = args.flags;
5774 String installerPackageName = args.installerPackageName;
5775 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005776 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005777 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005778 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005779 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005780 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005781 // Result object to be returned
5782 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5783
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005784 // Retrieve PackageSettings and parse package
5785 int parseFlags = PackageParser.PARSE_CHATTY |
5786 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5787 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5788 parseFlags |= mDefParseFlags;
5789 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5790 pp.setSeparateProcesses(mSeparateProcesses);
5791 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5792 null, mMetrics, parseFlags);
5793 if (pkg == null) {
5794 res.returnCode = pp.getParseError();
5795 return;
5796 }
5797 String pkgName = res.name = pkg.packageName;
5798 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5799 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5800 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5801 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005802 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005803 }
5804 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5805 res.returnCode = pp.getParseError();
5806 return;
5807 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005808 // Get rid of all references to package scan path via parser.
5809 pp = null;
5810 String oldCodePath = null;
5811 boolean systemApp = false;
5812 synchronized (mPackages) {
5813 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005814 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5815 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005816 if (pkg.mOriginalPackages != null
5817 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005818 && mPackages.containsKey(oldName)) {
5819 // This package is derived from an original package,
5820 // and this device has been updating from that original
5821 // name. We must continue using the original name, so
5822 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005823 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005824 pkgName = pkg.packageName;
5825 replace = true;
5826 } else if (mPackages.containsKey(pkgName)) {
5827 // This package, under its official name, already exists
5828 // on the device; we should replace it.
5829 replace = true;
5830 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005831 }
5832 PackageSetting ps = mSettings.mPackages.get(pkgName);
5833 if (ps != null) {
5834 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5835 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5836 systemApp = (ps.pkg.applicationInfo.flags &
5837 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005838 }
5839 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005840 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005841
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005842 if (systemApp && onSd) {
5843 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005844 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005845 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5846 return;
5847 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005848
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005849 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5850 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5851 return;
5852 }
5853 // Set application objects path explicitly after the rename
5854 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005855 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005856 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005857 replacePackageLI(pkg, parseFlags, scanMode,
5858 installerPackageName, res);
5859 } else {
5860 installNewPackageLI(pkg, parseFlags, scanMode,
5861 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 }
5863 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005864
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005865 private int setPermissionsLI(PackageParser.Package newPackage) {
5866 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005867 int retCode = 0;
5868 // TODO Gross hack but fix later. Ideally move this to be a post installation
5869 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005870 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005871 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 try {
5873 extractPublicFiles(newPackage, destResourceFile);
5874 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005875 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 -08005876 " forward-locked app.");
5877 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5878 } finally {
5879 //TODO clean up the extracted public files
5880 }
5881 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005882 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 newPackage.applicationInfo.uid);
5884 } else {
5885 final int filePermissions =
5886 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005887 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 newPackage.applicationInfo.uid);
5889 }
5890 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005891 // The permissions on the resource file was set when it was copied for
5892 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005896 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005897 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005899 // TODO Define new internal error
5900 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005901 }
5902 return PackageManager.INSTALL_SUCCEEDED;
5903 }
5904
Kenny Root85387d72010-08-26 10:13:11 -07005905 private static boolean isForwardLocked(PackageParser.Package pkg) {
5906 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005907 }
5908
Kenny Root85387d72010-08-26 10:13:11 -07005909 private static boolean isExternal(PackageParser.Package pkg) {
5910 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5911 }
5912
5913 private static boolean isSystemApp(PackageParser.Package pkg) {
5914 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5915 }
5916
5917 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5918 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005919 }
5920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 private void extractPublicFiles(PackageParser.Package newPackage,
5922 File publicZipFile) throws IOException {
5923 final ZipOutputStream publicZipOutStream =
5924 new ZipOutputStream(new FileOutputStream(publicZipFile));
5925 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5926
5927 // Copy manifest, resources.arsc and res directory to public zip
5928
5929 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5930 while (privateZipEntries.hasMoreElements()) {
5931 final ZipEntry zipEntry = privateZipEntries.nextElement();
5932 final String zipEntryName = zipEntry.getName();
5933 if ("AndroidManifest.xml".equals(zipEntryName)
5934 || "resources.arsc".equals(zipEntryName)
5935 || zipEntryName.startsWith("res/")) {
5936 try {
5937 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5938 } catch (IOException e) {
5939 try {
5940 publicZipOutStream.close();
5941 throw e;
5942 } finally {
5943 publicZipFile.delete();
5944 }
5945 }
5946 }
5947 }
5948
5949 publicZipOutStream.close();
5950 FileUtils.setPermissions(
5951 publicZipFile.getAbsolutePath(),
5952 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5953 -1, -1);
5954 }
5955
5956 private static void copyZipEntry(ZipEntry zipEntry,
5957 ZipFile inZipFile,
5958 ZipOutputStream outZipStream) throws IOException {
5959 byte[] buffer = new byte[4096];
5960 int num;
5961
5962 ZipEntry newEntry;
5963 if (zipEntry.getMethod() == ZipEntry.STORED) {
5964 // Preserve the STORED method of the input entry.
5965 newEntry = new ZipEntry(zipEntry);
5966 } else {
5967 // Create a new entry so that the compressed len is recomputed.
5968 newEntry = new ZipEntry(zipEntry.getName());
5969 }
5970 outZipStream.putNextEntry(newEntry);
5971
5972 InputStream data = inZipFile.getInputStream(zipEntry);
5973 while ((num = data.read(buffer)) > 0) {
5974 outZipStream.write(buffer, 0, num);
5975 }
5976 outZipStream.flush();
5977 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005978
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005979 private void deleteTempPackageFiles() {
5980 FilenameFilter filter = new FilenameFilter() {
5981 public boolean accept(File dir, String name) {
5982 return name.startsWith("vmdl") && name.endsWith(".tmp");
5983 }
5984 };
5985 String tmpFilesList[] = mAppInstallDir.list(filter);
5986 if(tmpFilesList == null) {
5987 return;
5988 }
5989 for(int i = 0; i < tmpFilesList.length; i++) {
5990 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5991 tmpFile.delete();
5992 }
5993 }
5994
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005995 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 File tmpPackageFile;
5997 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005998 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006000 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 return null;
6002 }
6003 try {
6004 FileUtils.setPermissions(
6005 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6006 -1, -1);
6007 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006008 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 return null;
6010 }
6011 return tmpPackageFile;
6012 }
6013
6014 public void deletePackage(final String packageName,
6015 final IPackageDeleteObserver observer,
6016 final int flags) {
6017 mContext.enforceCallingOrSelfPermission(
6018 android.Manifest.permission.DELETE_PACKAGES, null);
6019 // Queue up an async operation since the package deletion may take a little while.
6020 mHandler.post(new Runnable() {
6021 public void run() {
6022 mHandler.removeCallbacks(this);
6023 final boolean succeded = deletePackageX(packageName, true, true, flags);
6024 if (observer != null) {
6025 try {
6026 observer.packageDeleted(succeded);
6027 } catch (RemoteException e) {
6028 Log.i(TAG, "Observer no longer exists.");
6029 } //end catch
6030 } //end if
6031 } //end run
6032 });
6033 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 /**
6036 * This method is an internal method that could be get invoked either
6037 * to delete an installed package or to clean up a failed installation.
6038 * After deleting an installed package, a broadcast is sent to notify any
6039 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006040 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 * installation wouldn't have sent the initial broadcast either
6042 * The key steps in deleting a package are
6043 * deleting the package information in internal structures like mPackages,
6044 * deleting the packages base directories through installd
6045 * updating mSettings to reflect current status
6046 * persisting settings for later use
6047 * sending a broadcast if necessary
6048 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6050 boolean deleteCodeAndResources, int flags) {
6051 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006052 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006054 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6055 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6056 try {
6057 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006058 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006059 return false;
6060 }
6061 } catch (RemoteException e) {
6062 }
6063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006065 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006066 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006067 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006069 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006070 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006071 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006072
6073 // If the removed package was a system update, the old system packaged
6074 // was re-enabled; we need to broadcast this information
6075 if (systemUpdate) {
6076 Bundle extras = new Bundle(1);
6077 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6078 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6079
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006080 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6081 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006084 // Force a gc here.
6085 Runtime.getRuntime().gc();
6086 // Delete the resources here after sending the broadcast to let
6087 // other processes clean up before deleting resources.
6088 if (info.args != null) {
6089 synchronized (mInstallLock) {
6090 info.args.doPostDeleteLI(deleteCodeAndResources);
6091 }
6092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 return res;
6094 }
6095
6096 static class PackageRemovedInfo {
6097 String removedPackage;
6098 int uid = -1;
6099 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006100 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006101 // Clean up resources deleted packages.
6102 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006103
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006104 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 Bundle extras = new Bundle(1);
6106 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6107 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6108 if (replacing) {
6109 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6110 }
6111 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006112 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 }
6114 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006115 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 }
6117 }
6118 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 /*
6121 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6122 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006123 * 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 -08006124 * delete a partially installed application.
6125 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006126 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006127 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006129 if (outInfo != null) {
6130 outInfo.removedPackage = packageName;
6131 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006132 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 // Retrieve object to delete permissions for shared user later on
6134 PackageSetting deletedPs;
6135 synchronized (mPackages) {
6136 deletedPs = mSettings.mPackages.get(packageName);
6137 }
6138 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006139 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006141 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006142 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006143 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 + packageName + ", retcode=" + retCode);
6145 // we don't consider this to be a failure of the core package deletion
6146 }
6147 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006148 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 PackageParser.Package pkg = mPackages.get(packageName);
6150 File dataDir = new File(pkg.applicationInfo.dataDir);
6151 dataDir.delete();
6152 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006153 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006154 }
6155 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006156 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006157 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6158 if (outInfo != null) {
6159 outInfo.removedUid = mSettings.removePackageLP(packageName);
6160 }
6161 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006162 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006163 if (deletedPs.sharedUser != null) {
6164 // remove permissions associated with package
6165 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6166 }
6167 }
6168 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006169 // remove from preferred activities.
6170 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6171 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6172 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6173 removed.add(pa);
6174 }
6175 }
6176 for (PreferredActivity pa : removed) {
6177 mSettings.mPreferredActivities.removeFilter(pa);
6178 }
6179 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006180 if (writeSettings) {
6181 // Save settings now
6182 mSettings.writeLP();
6183 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 }
6185 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 /*
6188 * Tries to delete system package.
6189 */
6190 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006191 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 ApplicationInfo applicationInfo = p.applicationInfo;
6193 //applicable for non-partially installed applications only
6194 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006195 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 return false;
6197 }
6198 PackageSetting ps = null;
6199 // Confirm if the system package has been updated
6200 // An updated system app can be deleted. This will also have to restore
6201 // the system pkg from system partition
6202 synchronized (mPackages) {
6203 ps = mSettings.getDisabledSystemPkg(p.packageName);
6204 }
6205 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006206 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 return false;
6208 } else {
6209 Log.i(TAG, "Deleting system pkg from data partition");
6210 }
6211 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006212 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006213 final boolean deleteCodeAndResources;
6214 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006215 // Delete code and resources for downgrades
6216 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006217 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006218 } else {
6219 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006220 deleteCodeAndResources = false;
6221 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006222 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006223 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6224 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 if (!ret) {
6226 return false;
6227 }
6228 synchronized (mPackages) {
6229 // Reinstate the old system package
6230 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006231 // Remove any native libraries from the upgraded package.
6232 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233 }
6234 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006235 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006237 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006239 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006240 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 return false;
6242 }
6243 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006244 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006245 if (writeSettings) {
6246 mSettings.writeLP();
6247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 }
6249 return true;
6250 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006253 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6254 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 ApplicationInfo applicationInfo = p.applicationInfo;
6256 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006257 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 return false;
6259 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006260 if (outInfo != null) {
6261 outInfo.uid = applicationInfo.uid;
6262 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263
6264 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006265 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266
6267 // Delete application code and resources
6268 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006269 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006270 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6271 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6272 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6273 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 }
6275 return true;
6276 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 /*
6279 * This method handles package deletion in general
6280 */
6281 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006282 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6283 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006284 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006285 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 return false;
6287 }
6288 PackageParser.Package p;
6289 boolean dataOnly = false;
6290 synchronized (mPackages) {
6291 p = mPackages.get(packageName);
6292 if (p == null) {
6293 //this retrieves partially installed apps
6294 dataOnly = true;
6295 PackageSetting ps = mSettings.mPackages.get(packageName);
6296 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006297 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 return false;
6299 }
6300 p = ps.pkg;
6301 }
6302 }
6303 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006304 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006305 return false;
6306 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 if (dataOnly) {
6309 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006310 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 return true;
6312 }
6313 // At this point the package should have ApplicationInfo associated with it
6314 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006315 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 return false;
6317 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006318 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006319 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006320 Log.i(TAG, "Removing system package:"+p.packageName);
6321 // When an updated system application is deleted we delete the existing resources as well and
6322 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006323 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006324 } else {
6325 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006326 // Kill application pre-emptively especially for apps on sd.
6327 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006328 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6329 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006331 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 public void clearApplicationUserData(final String packageName,
6335 final IPackageDataObserver observer) {
6336 mContext.enforceCallingOrSelfPermission(
6337 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6338 // Queue up an async operation since the package deletion may take a little while.
6339 mHandler.post(new Runnable() {
6340 public void run() {
6341 mHandler.removeCallbacks(this);
6342 final boolean succeeded;
6343 synchronized (mInstallLock) {
6344 succeeded = clearApplicationUserDataLI(packageName);
6345 }
6346 if (succeeded) {
6347 // invoke DeviceStorageMonitor's update method to clear any notifications
6348 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6349 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6350 if (dsm != null) {
6351 dsm.updateMemory();
6352 }
6353 }
6354 if(observer != null) {
6355 try {
6356 observer.onRemoveCompleted(packageName, succeeded);
6357 } catch (RemoteException e) {
6358 Log.i(TAG, "Observer no longer exists.");
6359 }
6360 } //end if observer
6361 } //end run
6362 });
6363 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 private boolean clearApplicationUserDataLI(String packageName) {
6366 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006367 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 return false;
6369 }
6370 PackageParser.Package p;
6371 boolean dataOnly = false;
6372 synchronized (mPackages) {
6373 p = mPackages.get(packageName);
6374 if(p == null) {
6375 dataOnly = true;
6376 PackageSetting ps = mSettings.mPackages.get(packageName);
6377 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006378 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006379 return false;
6380 }
6381 p = ps.pkg;
6382 }
6383 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006384 boolean useEncryptedFSDir = false;
6385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 if(!dataOnly) {
6387 //need to check this only for fully installed applications
6388 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006389 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 return false;
6391 }
6392 final ApplicationInfo applicationInfo = p.applicationInfo;
6393 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006394 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 return false;
6396 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006397 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 }
6399 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006400 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006402 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006403 + packageName);
6404 return false;
6405 }
6406 }
6407 return true;
6408 }
6409
6410 public void deleteApplicationCacheFiles(final String packageName,
6411 final IPackageDataObserver observer) {
6412 mContext.enforceCallingOrSelfPermission(
6413 android.Manifest.permission.DELETE_CACHE_FILES, null);
6414 // Queue up an async operation since the package deletion may take a little while.
6415 mHandler.post(new Runnable() {
6416 public void run() {
6417 mHandler.removeCallbacks(this);
6418 final boolean succeded;
6419 synchronized (mInstallLock) {
6420 succeded = deleteApplicationCacheFilesLI(packageName);
6421 }
6422 if(observer != null) {
6423 try {
6424 observer.onRemoveCompleted(packageName, succeded);
6425 } catch (RemoteException e) {
6426 Log.i(TAG, "Observer no longer exists.");
6427 }
6428 } //end if observer
6429 } //end run
6430 });
6431 }
6432
6433 private boolean deleteApplicationCacheFilesLI(String packageName) {
6434 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006435 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 return false;
6437 }
6438 PackageParser.Package p;
6439 synchronized (mPackages) {
6440 p = mPackages.get(packageName);
6441 }
6442 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006443 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 return false;
6445 }
6446 final ApplicationInfo applicationInfo = p.applicationInfo;
6447 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006448 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 return false;
6450 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006451 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006452 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006453 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006454 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006455 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006456 + packageName);
6457 return false;
6458 }
6459 }
6460 return true;
6461 }
6462
6463 public void getPackageSizeInfo(final String packageName,
6464 final IPackageStatsObserver observer) {
6465 mContext.enforceCallingOrSelfPermission(
6466 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6467 // Queue up an async operation since the package deletion may take a little while.
6468 mHandler.post(new Runnable() {
6469 public void run() {
6470 mHandler.removeCallbacks(this);
6471 PackageStats lStats = new PackageStats(packageName);
6472 final boolean succeded;
6473 synchronized (mInstallLock) {
6474 succeded = getPackageSizeInfoLI(packageName, lStats);
6475 }
6476 if(observer != null) {
6477 try {
6478 observer.onGetStatsCompleted(lStats, succeded);
6479 } catch (RemoteException e) {
6480 Log.i(TAG, "Observer no longer exists.");
6481 }
6482 } //end if observer
6483 } //end run
6484 });
6485 }
6486
6487 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6488 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006489 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006490 return false;
6491 }
6492 PackageParser.Package p;
6493 boolean dataOnly = false;
6494 synchronized (mPackages) {
6495 p = mPackages.get(packageName);
6496 if(p == null) {
6497 dataOnly = true;
6498 PackageSetting ps = mSettings.mPackages.get(packageName);
6499 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006500 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006501 return false;
6502 }
6503 p = ps.pkg;
6504 }
6505 }
6506 String publicSrcDir = null;
6507 if(!dataOnly) {
6508 final ApplicationInfo applicationInfo = p.applicationInfo;
6509 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006510 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 return false;
6512 }
6513 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6514 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006515 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 if (mInstaller != null) {
6517 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006518 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006519 if (res < 0) {
6520 return false;
6521 } else {
6522 return true;
6523 }
6524 }
6525 return true;
6526 }
6527
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006530 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 }
6532
6533 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006534 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 }
6536
6537 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006538 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 }
6540
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006541 int getUidTargetSdkVersionLockedLP(int uid) {
6542 Object obj = mSettings.getUserIdLP(uid);
6543 if (obj instanceof SharedUserSetting) {
6544 SharedUserSetting sus = (SharedUserSetting)obj;
6545 final int N = sus.packages.size();
6546 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6547 Iterator<PackageSetting> it = sus.packages.iterator();
6548 int i=0;
6549 while (it.hasNext()) {
6550 PackageSetting ps = it.next();
6551 if (ps.pkg != null) {
6552 int v = ps.pkg.applicationInfo.targetSdkVersion;
6553 if (v < vers) vers = v;
6554 }
6555 }
6556 return vers;
6557 } else if (obj instanceof PackageSetting) {
6558 PackageSetting ps = (PackageSetting)obj;
6559 if (ps.pkg != null) {
6560 return ps.pkg.applicationInfo.targetSdkVersion;
6561 }
6562 }
6563 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6564 }
6565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 public void addPreferredActivity(IntentFilter filter, int match,
6567 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006569 if (mContext.checkCallingOrSelfPermission(
6570 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6571 != PackageManager.PERMISSION_GRANTED) {
6572 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6573 < Build.VERSION_CODES.FROYO) {
6574 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6575 + Binder.getCallingUid());
6576 return;
6577 }
6578 mContext.enforceCallingOrSelfPermission(
6579 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6580 }
6581
6582 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006583 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6584 mSettings.mPreferredActivities.addFilter(
6585 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006586 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006587 }
6588 }
6589
Satish Sampath8dbe6122009-06-02 23:35:54 +01006590 public void replacePreferredActivity(IntentFilter filter, int match,
6591 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006592 if (filter.countActions() != 1) {
6593 throw new IllegalArgumentException(
6594 "replacePreferredActivity expects filter to have only 1 action.");
6595 }
6596 if (filter.countCategories() != 1) {
6597 throw new IllegalArgumentException(
6598 "replacePreferredActivity expects filter to have only 1 category.");
6599 }
6600 if (filter.countDataAuthorities() != 0
6601 || filter.countDataPaths() != 0
6602 || filter.countDataSchemes() != 0
6603 || filter.countDataTypes() != 0) {
6604 throw new IllegalArgumentException(
6605 "replacePreferredActivity expects filter to have no data authorities, " +
6606 "paths, schemes or types.");
6607 }
6608 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006609 if (mContext.checkCallingOrSelfPermission(
6610 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6611 != PackageManager.PERMISSION_GRANTED) {
6612 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6613 < Build.VERSION_CODES.FROYO) {
6614 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6615 + Binder.getCallingUid());
6616 return;
6617 }
6618 mContext.enforceCallingOrSelfPermission(
6619 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6620 }
6621
Satish Sampath8dbe6122009-06-02 23:35:54 +01006622 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6623 String action = filter.getAction(0);
6624 String category = filter.getCategory(0);
6625 while (it.hasNext()) {
6626 PreferredActivity pa = it.next();
6627 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6628 it.remove();
6629 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6630 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6631 }
6632 }
6633 addPreferredActivity(filter, match, set, activity);
6634 }
6635 }
6636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006637 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006638 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006639 int uid = Binder.getCallingUid();
6640 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006641 if (pkg == null || pkg.applicationInfo.uid != uid) {
6642 if (mContext.checkCallingOrSelfPermission(
6643 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6644 != PackageManager.PERMISSION_GRANTED) {
6645 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6646 < Build.VERSION_CODES.FROYO) {
6647 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6648 + Binder.getCallingUid());
6649 return;
6650 }
6651 mContext.enforceCallingOrSelfPermission(
6652 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6653 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006654 }
6655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006656 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006657 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006658 }
6659 }
6660 }
6661
6662 boolean clearPackagePreferredActivitiesLP(String packageName) {
6663 boolean changed = false;
6664 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6665 while (it.hasNext()) {
6666 PreferredActivity pa = it.next();
6667 if (pa.mActivity.getPackageName().equals(packageName)) {
6668 it.remove();
6669 changed = true;
6670 }
6671 }
6672 return changed;
6673 }
6674
6675 public int getPreferredActivities(List<IntentFilter> outFilters,
6676 List<ComponentName> outActivities, String packageName) {
6677
6678 int num = 0;
6679 synchronized (mPackages) {
6680 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6681 while (it.hasNext()) {
6682 PreferredActivity pa = it.next();
6683 if (packageName == null
6684 || pa.mActivity.getPackageName().equals(packageName)) {
6685 if (outFilters != null) {
6686 outFilters.add(new IntentFilter(pa));
6687 }
6688 if (outActivities != null) {
6689 outActivities.add(pa.mActivity);
6690 }
6691 }
6692 }
6693 }
6694
6695 return num;
6696 }
6697
6698 public void setApplicationEnabledSetting(String appPackageName,
6699 int newState, int flags) {
6700 setEnabledSetting(appPackageName, null, newState, flags);
6701 }
6702
6703 public void setComponentEnabledSetting(ComponentName componentName,
6704 int newState, int flags) {
6705 setEnabledSetting(componentName.getPackageName(),
6706 componentName.getClassName(), newState, flags);
6707 }
6708
6709 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006710 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6712 || newState == COMPONENT_ENABLED_STATE_ENABLED
6713 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6714 throw new IllegalArgumentException("Invalid new component state: "
6715 + newState);
6716 }
6717 PackageSetting pkgSetting;
6718 final int uid = Binder.getCallingUid();
6719 final int permission = mContext.checkCallingPermission(
6720 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6721 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006722 boolean sendNow = false;
6723 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006724 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006726 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006728 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006730 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006732 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 }
6734 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006735 "Unknown component: " + packageName
6736 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 }
6738 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6739 throw new SecurityException(
6740 "Permission Denial: attempt to change component state from pid="
6741 + Binder.getCallingPid()
6742 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6743 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006744 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006746 if (pkgSetting.enabled == newState) {
6747 // Nothing to do
6748 return;
6749 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006751 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006752 } else {
6753 // We're dealing with a component level state change
6754 switch (newState) {
6755 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006756 if (!pkgSetting.enableComponentLP(className)) {
6757 return;
6758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 break;
6760 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006761 if (!pkgSetting.disableComponentLP(className)) {
6762 return;
6763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 break;
6765 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006766 if (!pkgSetting.restoreComponentLP(className)) {
6767 return;
6768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 break;
6770 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006771 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006772 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006773 }
6774 }
6775 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006776 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006777 components = mPendingBroadcasts.get(packageName);
6778 boolean newPackage = components == null;
6779 if (newPackage) {
6780 components = new ArrayList<String>();
6781 }
6782 if (!components.contains(componentName)) {
6783 components.add(componentName);
6784 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006785 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6786 sendNow = true;
6787 // Purge entry from pending broadcast list if another one exists already
6788 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006789 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006790 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006791 if (newPackage) {
6792 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006793 }
6794 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6795 // Schedule a message
6796 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6797 }
6798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 long callingId = Binder.clearCallingIdentity();
6802 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006803 if (sendNow) {
6804 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006805 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006807 } finally {
6808 Binder.restoreCallingIdentity(callingId);
6809 }
6810 }
6811
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006812 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006813 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6814 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6815 + " components=" + componentNames);
6816 Bundle extras = new Bundle(4);
6817 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6818 String nameList[] = new String[componentNames.size()];
6819 componentNames.toArray(nameList);
6820 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006821 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6822 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006823 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006824 }
6825
Jacek Surazski65e13172009-04-28 15:26:38 +02006826 public String getInstallerPackageName(String packageName) {
6827 synchronized (mPackages) {
6828 PackageSetting pkg = mSettings.mPackages.get(packageName);
6829 if (pkg == null) {
6830 throw new IllegalArgumentException("Unknown package: " + packageName);
6831 }
6832 return pkg.installerPackageName;
6833 }
6834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006836 public int getApplicationEnabledSetting(String appPackageName) {
6837 synchronized (mPackages) {
6838 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6839 if (pkg == null) {
6840 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6841 }
6842 return pkg.enabled;
6843 }
6844 }
6845
6846 public int getComponentEnabledSetting(ComponentName componentName) {
6847 synchronized (mPackages) {
6848 final String packageNameStr = componentName.getPackageName();
6849 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6850 if (pkg == null) {
6851 throw new IllegalArgumentException("Unknown component: " + componentName);
6852 }
6853 final String classNameStr = componentName.getClassName();
6854 return pkg.currentEnabledStateLP(classNameStr);
6855 }
6856 }
6857
6858 public void enterSafeMode() {
6859 if (!mSystemReady) {
6860 mSafeMode = true;
6861 }
6862 }
6863
6864 public void systemReady() {
6865 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006866
6867 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006868 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006869 mContext.getContentResolver(),
6870 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006871 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006872 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006873 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006874 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006875 }
6876
6877 public boolean isSafeMode() {
6878 return mSafeMode;
6879 }
6880
6881 public boolean hasSystemUidErrors() {
6882 return mHasSystemUidErrors;
6883 }
6884
6885 static String arrayToString(int[] array) {
6886 StringBuffer buf = new StringBuffer(128);
6887 buf.append('[');
6888 if (array != null) {
6889 for (int i=0; i<array.length; i++) {
6890 if (i > 0) buf.append(", ");
6891 buf.append(array[i]);
6892 }
6893 }
6894 buf.append(']');
6895 return buf.toString();
6896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006898 @Override
6899 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6900 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6901 != PackageManager.PERMISSION_GRANTED) {
6902 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6903 + Binder.getCallingPid()
6904 + ", uid=" + Binder.getCallingUid()
6905 + " without permission "
6906 + android.Manifest.permission.DUMP);
6907 return;
6908 }
6909
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006910 boolean dumpStar = true;
6911 boolean dumpLibs = false;
6912 boolean dumpFeatures = false;
6913 boolean dumpResolvers = false;
6914 boolean dumpPermissions = false;
6915 boolean dumpPackages = false;
6916 boolean dumpSharedUsers = false;
6917 boolean dumpMessages = false;
6918 boolean dumpProviders = false;
6919
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006920 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006921 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006922
6923 int opti = 0;
6924 while (opti < args.length) {
6925 String opt = args[opti];
6926 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6927 break;
6928 }
6929 opti++;
6930 if ("-a".equals(opt)) {
6931 // Right now we only know how to print all.
6932 } else if ("-h".equals(opt)) {
6933 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006934 pw.println(" [-h] [-f] [cmd] ...");
6935 pw.println(" -f: print details of intent filters");
6936 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006937 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006938 pw.println(" l[ibraries]: list known shared libraries");
6939 pw.println(" f[ibraries]: list device features");
6940 pw.println(" r[esolvers]: dump intent resolvers");
6941 pw.println(" perm[issions]: dump permissions");
6942 pw.println(" prov[iders]: dump content providers");
6943 pw.println(" p[ackages]: dump installed packages");
6944 pw.println(" s[hared-users]: dump shared user IDs");
6945 pw.println(" m[essages]: print collected runtime messages");
6946 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006947 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006948 } else if ("-f".equals(opt)) {
6949 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006950 } else {
6951 pw.println("Unknown argument: " + opt + "; use -h for help");
6952 }
6953 }
6954
6955 // Is the caller requesting to dump a particular piece of data?
6956 if (opti < args.length) {
6957 String cmd = args[opti];
6958 opti++;
6959 // Is this a package name?
6960 if ("android".equals(cmd) || cmd.contains(".")) {
6961 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006962 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
6963 dumpStar = false;
6964 dumpLibs = true;
6965 } else if ("f".equals(cmd) || "features".equals(cmd)) {
6966 dumpStar = false;
6967 dumpFeatures = true;
6968 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
6969 dumpStar = false;
6970 dumpResolvers = true;
6971 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
6972 dumpStar = false;
6973 dumpPermissions = true;
6974 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
6975 dumpStar = false;
6976 dumpPackages = true;
6977 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
6978 dumpStar = false;
6979 dumpSharedUsers = true;
6980 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
6981 dumpStar = false;
6982 dumpProviders = true;
6983 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
6984 dumpStar = false;
6985 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006986 }
6987 }
6988
6989 boolean printedTitle = false;
6990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006992 if ((dumpStar || dumpLibs) && packageName == null) {
6993 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006994 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006995 pw.println("Libraries:");
6996 Iterator<String> it = mSharedLibraries.keySet().iterator();
6997 while (it.hasNext()) {
6998 String name = it.next();
6999 pw.print(" ");
7000 pw.print(name);
7001 pw.print(" -> ");
7002 pw.println(mSharedLibraries.get(name));
7003 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007004 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007005
7006 if ((dumpStar || dumpFeatures) && packageName == null) {
7007 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007008 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007009 pw.println("Features:");
7010 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7011 while (it.hasNext()) {
7012 String name = it.next();
7013 pw.print(" ");
7014 pw.println(name);
7015 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007016 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007017
7018 if (dumpStar || dumpResolvers) {
7019 if (mActivities.dump(pw, printedTitle
7020 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7021 " ", packageName, showFilters)) {
7022 printedTitle = true;
7023 }
7024 if (mReceivers.dump(pw, printedTitle
7025 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7026 " ", packageName, showFilters)) {
7027 printedTitle = true;
7028 }
7029 if (mServices.dump(pw, printedTitle
7030 ? "\nService Resolver Table:" : "Service Resolver Table:",
7031 " ", packageName, showFilters)) {
7032 printedTitle = true;
7033 }
7034 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7035 ? "\nPreferred Activities:" : "Preferred Activities:",
7036 " ", packageName, showFilters)) {
7037 printedTitle = true;
7038 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007039 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007040
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007041 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007042 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007044 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7045 continue;
7046 }
7047 if (!printedSomething) {
7048 if (printedTitle) pw.println(" ");
7049 pw.println("Permissions:");
7050 printedSomething = true;
7051 printedTitle = true;
7052 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007053 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7054 pw.print(Integer.toHexString(System.identityHashCode(p)));
7055 pw.println("):");
7056 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7057 pw.print(" uid="); pw.print(p.uid);
7058 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007059 pw.print(" type="); pw.print(p.type);
7060 pw.print(" prot="); pw.println(p.protectionLevel);
7061 if (p.packageSetting != null) {
7062 pw.print(" packageSetting="); pw.println(p.packageSetting);
7063 }
7064 if (p.perm != null) {
7065 pw.print(" perm="); pw.println(p.perm);
7066 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007067 }
7068 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007069
7070 if (dumpStar || dumpProviders) {
7071 printedSomething = false;
7072 for (PackageParser.Provider p : mProviders.values()) {
7073 if (packageName != null && !packageName.equals(p.info.packageName)) {
7074 continue;
7075 }
7076 if (!printedSomething) {
7077 if (printedTitle) pw.println(" ");
7078 pw.println("Registered ContentProviders:");
7079 printedSomething = true;
7080 printedTitle = true;
7081 }
7082 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7083 pw.println(p.toString());
7084 }
7085 }
7086
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007087 printedSomething = false;
7088 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007089 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007090 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7091 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007092 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007093 if (packageName != null && !packageName.equals(ps.realName)
7094 && !packageName.equals(ps.name)) {
7095 continue;
7096 }
7097 if (!printedSomething) {
7098 if (printedTitle) pw.println(" ");
7099 pw.println("Packages:");
7100 printedSomething = true;
7101 printedTitle = true;
7102 }
7103 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007104 pw.print(" Package [");
7105 pw.print(ps.realName != null ? ps.realName : ps.name);
7106 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007107 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7108 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007109 if (ps.realName != null) {
7110 pw.print(" compat name="); pw.println(ps.name);
7111 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007112 pw.print(" userId="); pw.print(ps.userId);
7113 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7114 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7115 pw.print(" pkg="); pw.println(ps.pkg);
7116 pw.print(" codePath="); pw.println(ps.codePathString);
7117 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007118 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007119 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007120 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007121 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007122 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007123 if (ps.pkg.mOperationPending) {
7124 pw.println(" mOperationPending=true");
7125 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007126 pw.print(" supportsScreens=[");
7127 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007128 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007129 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7130 if (!first) pw.print(", ");
7131 first = false;
7132 pw.print("small");
7133 }
7134 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007135 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007136 if (!first) pw.print(", ");
7137 first = false;
7138 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007139 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007140 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007141 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007142 if (!first) pw.print(", ");
7143 first = false;
7144 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007145 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007146 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007147 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007148 if (!first) pw.print(", ");
7149 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007150 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007151 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007152 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007153 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007154 if (!first) pw.print(", ");
7155 first = false;
7156 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007157 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007158 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007159 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7160 if (!first) pw.print(", ");
7161 first = false;
7162 pw.print("anyDensity");
7163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007164 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007165 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007166 pw.print(" timeStamp=");
7167 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7168 pw.print(" firstInstallTime=");
7169 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7170 pw.print(" lastUpdateTime=");
7171 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007172 pw.print(" signatures="); pw.println(ps.signatures);
7173 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007174 pw.print(" haveGids="); pw.println(ps.haveGids);
7175 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007176 pw.print(" installStatus="); pw.print(ps.installStatus);
7177 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007178 if (ps.disabledComponents.size() > 0) {
7179 pw.println(" disabledComponents:");
7180 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007181 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 }
7183 }
7184 if (ps.enabledComponents.size() > 0) {
7185 pw.println(" enabledComponents:");
7186 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007187 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188 }
7189 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007190 if (ps.grantedPermissions.size() > 0) {
7191 pw.println(" grantedPermissions:");
7192 for (String s : ps.grantedPermissions) {
7193 pw.print(" "); pw.println(s);
7194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 }
7197 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007198 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007199 if (dumpStar || dumpPackages) {
7200 if (mSettings.mRenamedPackages.size() > 0) {
7201 for (HashMap.Entry<String, String> e
7202 : mSettings.mRenamedPackages.entrySet()) {
7203 if (packageName != null && !packageName.equals(e.getKey())
7204 && !packageName.equals(e.getValue())) {
7205 continue;
7206 }
7207 if (!printedSomething) {
7208 if (printedTitle) pw.println(" ");
7209 pw.println("Renamed packages:");
7210 printedSomething = true;
7211 printedTitle = true;
7212 }
7213 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7214 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007215 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007216 }
7217 printedSomething = false;
7218 if (mSettings.mDisabledSysPackages.size() > 0) {
7219 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7220 if (packageName != null && !packageName.equals(ps.realName)
7221 && !packageName.equals(ps.name)) {
7222 continue;
7223 }
7224 if (!printedSomething) {
7225 if (printedTitle) pw.println(" ");
7226 pw.println("Hidden system packages:");
7227 printedSomething = true;
7228 printedTitle = true;
7229 }
7230 pw.print(" Package [");
7231 pw.print(ps.realName != null ? ps.realName : ps.name);
7232 pw.print("] (");
7233 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7234 pw.println("):");
7235 if (ps.realName != null) {
7236 pw.print(" compat name="); pw.println(ps.name);
7237 }
7238 pw.print(" userId="); pw.println(ps.userId);
7239 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7240 pw.print(" codePath="); pw.println(ps.codePathString);
7241 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007242 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007243 }
7244 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007245 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007246 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007247 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007248 if (packageName != null && su != packageSharedUser) {
7249 continue;
7250 }
7251 if (!printedSomething) {
7252 if (printedTitle) pw.println(" ");
7253 pw.println("Shared users:");
7254 printedSomething = true;
7255 printedTitle = true;
7256 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007257 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7258 pw.print(Integer.toHexString(System.identityHashCode(su)));
7259 pw.println("):");
7260 pw.print(" userId="); pw.print(su.userId);
7261 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007262 pw.println(" grantedPermissions:");
7263 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007264 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007265 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007266 }
7267 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007268
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007269 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007270 if (printedTitle) pw.println(" ");
7271 printedTitle = true;
7272 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007273 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007274
7275 pw.println(" ");
7276 pw.println("Package warning messages:");
7277 File fname = getSettingsProblemFile();
7278 FileInputStream in;
7279 try {
7280 in = new FileInputStream(fname);
7281 int avail = in.available();
7282 byte[] data = new byte[avail];
7283 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007284 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007285 } catch (FileNotFoundException e) {
7286 } catch (IOException e) {
7287 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007289 }
7290 }
7291
7292 static final class BasePermission {
7293 final static int TYPE_NORMAL = 0;
7294 final static int TYPE_BUILTIN = 1;
7295 final static int TYPE_DYNAMIC = 2;
7296
7297 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007298 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007299 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007300 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007301 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 PackageParser.Permission perm;
7303 PermissionInfo pendingInfo;
7304 int uid;
7305 int[] gids;
7306
7307 BasePermission(String _name, String _sourcePackage, int _type) {
7308 name = _name;
7309 sourcePackage = _sourcePackage;
7310 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007311 // Default to most conservative protection level.
7312 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7313 }
7314
7315 public String toString() {
7316 return "BasePermission{"
7317 + Integer.toHexString(System.identityHashCode(this))
7318 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007319 }
7320 }
7321
7322 static class PackageSignatures {
7323 private Signature[] mSignatures;
7324
7325 PackageSignatures(Signature[] sigs) {
7326 assignSignatures(sigs);
7327 }
7328
7329 PackageSignatures() {
7330 }
7331
7332 void writeXml(XmlSerializer serializer, String tagName,
7333 ArrayList<Signature> pastSignatures) throws IOException {
7334 if (mSignatures == null) {
7335 return;
7336 }
7337 serializer.startTag(null, tagName);
7338 serializer.attribute(null, "count",
7339 Integer.toString(mSignatures.length));
7340 for (int i=0; i<mSignatures.length; i++) {
7341 serializer.startTag(null, "cert");
7342 final Signature sig = mSignatures[i];
7343 final int sigHash = sig.hashCode();
7344 final int numPast = pastSignatures.size();
7345 int j;
7346 for (j=0; j<numPast; j++) {
7347 Signature pastSig = pastSignatures.get(j);
7348 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7349 serializer.attribute(null, "index", Integer.toString(j));
7350 break;
7351 }
7352 }
7353 if (j >= numPast) {
7354 pastSignatures.add(sig);
7355 serializer.attribute(null, "index", Integer.toString(numPast));
7356 serializer.attribute(null, "key", sig.toCharsString());
7357 }
7358 serializer.endTag(null, "cert");
7359 }
7360 serializer.endTag(null, tagName);
7361 }
7362
7363 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7364 throws IOException, XmlPullParserException {
7365 String countStr = parser.getAttributeValue(null, "count");
7366 if (countStr == null) {
7367 reportSettingsProblem(Log.WARN,
7368 "Error in package manager settings: <signatures> has"
7369 + " no count at " + parser.getPositionDescription());
7370 XmlUtils.skipCurrentTag(parser);
7371 }
7372 final int count = Integer.parseInt(countStr);
7373 mSignatures = new Signature[count];
7374 int pos = 0;
7375
7376 int outerDepth = parser.getDepth();
7377 int type;
7378 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7379 && (type != XmlPullParser.END_TAG
7380 || parser.getDepth() > outerDepth)) {
7381 if (type == XmlPullParser.END_TAG
7382 || type == XmlPullParser.TEXT) {
7383 continue;
7384 }
7385
7386 String tagName = parser.getName();
7387 if (tagName.equals("cert")) {
7388 if (pos < count) {
7389 String index = parser.getAttributeValue(null, "index");
7390 if (index != null) {
7391 try {
7392 int idx = Integer.parseInt(index);
7393 String key = parser.getAttributeValue(null, "key");
7394 if (key == null) {
7395 if (idx >= 0 && idx < pastSignatures.size()) {
7396 Signature sig = pastSignatures.get(idx);
7397 if (sig != null) {
7398 mSignatures[pos] = pastSignatures.get(idx);
7399 pos++;
7400 } else {
7401 reportSettingsProblem(Log.WARN,
7402 "Error in package manager settings: <cert> "
7403 + "index " + index + " is not defined at "
7404 + parser.getPositionDescription());
7405 }
7406 } else {
7407 reportSettingsProblem(Log.WARN,
7408 "Error in package manager settings: <cert> "
7409 + "index " + index + " is out of bounds at "
7410 + parser.getPositionDescription());
7411 }
7412 } else {
7413 while (pastSignatures.size() <= idx) {
7414 pastSignatures.add(null);
7415 }
7416 Signature sig = new Signature(key);
7417 pastSignatures.set(idx, sig);
7418 mSignatures[pos] = sig;
7419 pos++;
7420 }
7421 } catch (NumberFormatException e) {
7422 reportSettingsProblem(Log.WARN,
7423 "Error in package manager settings: <cert> "
7424 + "index " + index + " is not a number at "
7425 + parser.getPositionDescription());
7426 }
7427 } else {
7428 reportSettingsProblem(Log.WARN,
7429 "Error in package manager settings: <cert> has"
7430 + " no index at " + parser.getPositionDescription());
7431 }
7432 } else {
7433 reportSettingsProblem(Log.WARN,
7434 "Error in package manager settings: too "
7435 + "many <cert> tags, expected " + count
7436 + " at " + parser.getPositionDescription());
7437 }
7438 } else {
7439 reportSettingsProblem(Log.WARN,
7440 "Unknown element under <cert>: "
7441 + parser.getName());
7442 }
7443 XmlUtils.skipCurrentTag(parser);
7444 }
7445
7446 if (pos < count) {
7447 // Should never happen -- there is an error in the written
7448 // settings -- but if it does we don't want to generate
7449 // a bad array.
7450 Signature[] newSigs = new Signature[pos];
7451 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7452 mSignatures = newSigs;
7453 }
7454 }
7455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007456 private void assignSignatures(Signature[] sigs) {
7457 if (sigs == null) {
7458 mSignatures = null;
7459 return;
7460 }
7461 mSignatures = new Signature[sigs.length];
7462 for (int i=0; i<sigs.length; i++) {
7463 mSignatures[i] = sigs[i];
7464 }
7465 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007467 @Override
7468 public String toString() {
7469 StringBuffer buf = new StringBuffer(128);
7470 buf.append("PackageSignatures{");
7471 buf.append(Integer.toHexString(System.identityHashCode(this)));
7472 buf.append(" [");
7473 if (mSignatures != null) {
7474 for (int i=0; i<mSignatures.length; i++) {
7475 if (i > 0) buf.append(", ");
7476 buf.append(Integer.toHexString(
7477 System.identityHashCode(mSignatures[i])));
7478 }
7479 }
7480 buf.append("]}");
7481 return buf.toString();
7482 }
7483 }
7484
7485 static class PreferredActivity extends IntentFilter {
7486 final int mMatch;
7487 final String[] mSetPackages;
7488 final String[] mSetClasses;
7489 final String[] mSetComponents;
7490 final ComponentName mActivity;
7491 final String mShortActivity;
7492 String mParseError;
7493
7494 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7495 ComponentName activity) {
7496 super(filter);
7497 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7498 mActivity = activity;
7499 mShortActivity = activity.flattenToShortString();
7500 mParseError = null;
7501 if (set != null) {
7502 final int N = set.length;
7503 String[] myPackages = new String[N];
7504 String[] myClasses = new String[N];
7505 String[] myComponents = new String[N];
7506 for (int i=0; i<N; i++) {
7507 ComponentName cn = set[i];
7508 if (cn == null) {
7509 mSetPackages = null;
7510 mSetClasses = null;
7511 mSetComponents = null;
7512 return;
7513 }
7514 myPackages[i] = cn.getPackageName().intern();
7515 myClasses[i] = cn.getClassName().intern();
7516 myComponents[i] = cn.flattenToShortString().intern();
7517 }
7518 mSetPackages = myPackages;
7519 mSetClasses = myClasses;
7520 mSetComponents = myComponents;
7521 } else {
7522 mSetPackages = null;
7523 mSetClasses = null;
7524 mSetComponents = null;
7525 }
7526 }
7527
7528 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7529 IOException {
7530 mShortActivity = parser.getAttributeValue(null, "name");
7531 mActivity = ComponentName.unflattenFromString(mShortActivity);
7532 if (mActivity == null) {
7533 mParseError = "Bad activity name " + mShortActivity;
7534 }
7535 String matchStr = parser.getAttributeValue(null, "match");
7536 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7537 String setCountStr = parser.getAttributeValue(null, "set");
7538 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7539
7540 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7541 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7542 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7543
7544 int setPos = 0;
7545
7546 int outerDepth = parser.getDepth();
7547 int type;
7548 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7549 && (type != XmlPullParser.END_TAG
7550 || parser.getDepth() > outerDepth)) {
7551 if (type == XmlPullParser.END_TAG
7552 || type == XmlPullParser.TEXT) {
7553 continue;
7554 }
7555
7556 String tagName = parser.getName();
7557 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7558 // + parser.getDepth() + " tag=" + tagName);
7559 if (tagName.equals("set")) {
7560 String name = parser.getAttributeValue(null, "name");
7561 if (name == null) {
7562 if (mParseError == null) {
7563 mParseError = "No name in set tag in preferred activity "
7564 + mShortActivity;
7565 }
7566 } else if (setPos >= setCount) {
7567 if (mParseError == null) {
7568 mParseError = "Too many set tags in preferred activity "
7569 + mShortActivity;
7570 }
7571 } else {
7572 ComponentName cn = ComponentName.unflattenFromString(name);
7573 if (cn == null) {
7574 if (mParseError == null) {
7575 mParseError = "Bad set name " + name + " in preferred activity "
7576 + mShortActivity;
7577 }
7578 } else {
7579 myPackages[setPos] = cn.getPackageName();
7580 myClasses[setPos] = cn.getClassName();
7581 myComponents[setPos] = name;
7582 setPos++;
7583 }
7584 }
7585 XmlUtils.skipCurrentTag(parser);
7586 } else if (tagName.equals("filter")) {
7587 //Log.i(TAG, "Starting to parse filter...");
7588 readFromXml(parser);
7589 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7590 // + parser.getDepth() + " tag=" + parser.getName());
7591 } else {
7592 reportSettingsProblem(Log.WARN,
7593 "Unknown element under <preferred-activities>: "
7594 + parser.getName());
7595 XmlUtils.skipCurrentTag(parser);
7596 }
7597 }
7598
7599 if (setPos != setCount) {
7600 if (mParseError == null) {
7601 mParseError = "Not enough set tags (expected " + setCount
7602 + " but found " + setPos + ") in " + mShortActivity;
7603 }
7604 }
7605
7606 mSetPackages = myPackages;
7607 mSetClasses = myClasses;
7608 mSetComponents = myComponents;
7609 }
7610
7611 public void writeToXml(XmlSerializer serializer) throws IOException {
7612 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7613 serializer.attribute(null, "name", mShortActivity);
7614 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7615 serializer.attribute(null, "set", Integer.toString(NS));
7616 for (int s=0; s<NS; s++) {
7617 serializer.startTag(null, "set");
7618 serializer.attribute(null, "name", mSetComponents[s]);
7619 serializer.endTag(null, "set");
7620 }
7621 serializer.startTag(null, "filter");
7622 super.writeToXml(serializer);
7623 serializer.endTag(null, "filter");
7624 }
7625
7626 boolean sameSet(List<ResolveInfo> query, int priority) {
7627 if (mSetPackages == null) return false;
7628 final int NQ = query.size();
7629 final int NS = mSetPackages.length;
7630 int numMatch = 0;
7631 for (int i=0; i<NQ; i++) {
7632 ResolveInfo ri = query.get(i);
7633 if (ri.priority != priority) continue;
7634 ActivityInfo ai = ri.activityInfo;
7635 boolean good = false;
7636 for (int j=0; j<NS; j++) {
7637 if (mSetPackages[j].equals(ai.packageName)
7638 && mSetClasses[j].equals(ai.name)) {
7639 numMatch++;
7640 good = true;
7641 break;
7642 }
7643 }
7644 if (!good) return false;
7645 }
7646 return numMatch == NS;
7647 }
7648 }
7649
7650 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007651 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007653 HashSet<String> grantedPermissions = new HashSet<String>();
7654 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007657 setFlags(pkgFlags);
7658 }
7659
7660 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007661 this.pkgFlags = pkgFlags & (
7662 ApplicationInfo.FLAG_SYSTEM |
7663 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007664 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007665 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 }
7667 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007669 /**
7670 * Settings base class for pending and resolved classes.
7671 */
7672 static class PackageSettingBase extends GrantedPermissions {
7673 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007674 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007675 File codePath;
7676 String codePathString;
7677 File resourcePath;
7678 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007679 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007680 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007681 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007682 long firstInstallTime;
7683 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007684 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007685
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007686 boolean uidError;
7687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 PackageSignatures signatures = new PackageSignatures();
7689
7690 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007691 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 /* Explicitly disabled components */
7694 HashSet<String> disabledComponents = new HashSet<String>(0);
7695 /* Explicitly enabled components */
7696 HashSet<String> enabledComponents = new HashSet<String>(0);
7697 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7698 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007699
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007700 PackageSettingBase origPackage;
7701
Jacek Surazski65e13172009-04-28 15:26:38 +02007702 /* package name of the app that installed this package */
7703 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007705 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007706 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 super(pkgFlags);
7708 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007709 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007710 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007711 }
7712
Kenny Root806cc132010-09-12 08:34:19 -07007713 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7714 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 this.codePath = codePath;
7716 this.codePathString = codePath.toString();
7717 this.resourcePath = resourcePath;
7718 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007719 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007720 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721 }
Kenny Root85387d72010-08-26 10:13:11 -07007722
Jacek Surazski65e13172009-04-28 15:26:38 +02007723 public void setInstallerPackageName(String packageName) {
7724 installerPackageName = packageName;
7725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007726
Jacek Surazski65e13172009-04-28 15:26:38 +02007727 String getInstallerPackageName() {
7728 return installerPackageName;
7729 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 public void setInstallStatus(int newStatus) {
7732 installStatus = newStatus;
7733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 public int getInstallStatus() {
7736 return installStatus;
7737 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 }
7742
7743 public void copyFrom(PackageSettingBase base) {
7744 grantedPermissions = base.grantedPermissions;
7745 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007746
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007748 firstInstallTime = base.firstInstallTime;
7749 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 signatures = base.signatures;
7751 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007752 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 disabledComponents = base.disabledComponents;
7754 enabledComponents = base.enabledComponents;
7755 enabled = base.enabled;
7756 installStatus = base.installStatus;
7757 }
7758
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007759 boolean enableComponentLP(String componentClassName) {
7760 boolean changed = disabledComponents.remove(componentClassName);
7761 changed |= enabledComponents.add(componentClassName);
7762 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 }
7764
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007765 boolean disableComponentLP(String componentClassName) {
7766 boolean changed = enabledComponents.remove(componentClassName);
7767 changed |= disabledComponents.add(componentClassName);
7768 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 }
7770
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007771 boolean restoreComponentLP(String componentClassName) {
7772 boolean changed = enabledComponents.remove(componentClassName);
7773 changed |= disabledComponents.remove(componentClassName);
7774 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007775 }
7776
7777 int currentEnabledStateLP(String componentName) {
7778 if (enabledComponents.contains(componentName)) {
7779 return COMPONENT_ENABLED_STATE_ENABLED;
7780 } else if (disabledComponents.contains(componentName)) {
7781 return COMPONENT_ENABLED_STATE_DISABLED;
7782 } else {
7783 return COMPONENT_ENABLED_STATE_DEFAULT;
7784 }
7785 }
7786 }
7787
7788 /**
7789 * Settings data for a particular package we know about.
7790 */
7791 static final class PackageSetting extends PackageSettingBase {
7792 int userId;
7793 PackageParser.Package pkg;
7794 SharedUserSetting sharedUser;
7795
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007796 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007797 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7798 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7799 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007800 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 @Override
7803 public String toString() {
7804 return "PackageSetting{"
7805 + Integer.toHexString(System.identityHashCode(this))
7806 + " " + name + "/" + userId + "}";
7807 }
7808 }
7809
7810 /**
7811 * Settings data for a particular shared user ID we know about.
7812 */
7813 static final class SharedUserSetting extends GrantedPermissions {
7814 final String name;
7815 int userId;
7816 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7817 final PackageSignatures signatures = new PackageSignatures();
7818
7819 SharedUserSetting(String _name, int _pkgFlags) {
7820 super(_pkgFlags);
7821 name = _name;
7822 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 @Override
7825 public String toString() {
7826 return "SharedUserSetting{"
7827 + Integer.toHexString(System.identityHashCode(this))
7828 + " " + name + "/" + userId + "}";
7829 }
7830 }
7831
7832 /**
7833 * Holds information about dynamic settings.
7834 */
7835 private static final class Settings {
7836 private final File mSettingsFilename;
7837 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007838 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 private final HashMap<String, PackageSetting> mPackages =
7840 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007841 // List of replaced system applications
7842 final HashMap<String, PackageSetting> mDisabledSysPackages =
7843 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007844
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007845 // These are the last platform API version we were using for
7846 // the apps installed on internal and external storage. It is
7847 // used to grant newer permissions one time during a system upgrade.
7848 int mInternalSdkPlatform;
7849 int mExternalSdkPlatform;
7850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 // The user's preferred activities associated with particular intent
7852 // filters.
7853 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7854 new IntentResolver<PreferredActivity, PreferredActivity>() {
7855 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007856 protected String packageForFilter(PreferredActivity filter) {
7857 return filter.mActivity.getPackageName();
7858 }
7859 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007860 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007862 out.print(prefix); out.print(
7863 Integer.toHexString(System.identityHashCode(filter)));
7864 out.print(' ');
7865 out.print(filter.mActivity.flattenToShortString());
7866 out.print(" match=0x");
7867 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007868 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007869 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007870 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007871 out.print(prefix); out.print(" ");
7872 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007873 }
7874 }
7875 }
7876 };
7877 private final HashMap<String, SharedUserSetting> mSharedUsers =
7878 new HashMap<String, SharedUserSetting>();
7879 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7880 private final SparseArray<Object> mOtherUserIds =
7881 new SparseArray<Object>();
7882
7883 // For reading/writing settings file.
7884 private final ArrayList<Signature> mPastSignatures =
7885 new ArrayList<Signature>();
7886
7887 // Mapping from permission names to info about them.
7888 final HashMap<String, BasePermission> mPermissions =
7889 new HashMap<String, BasePermission>();
7890
7891 // Mapping from permission tree names to info about them.
7892 final HashMap<String, BasePermission> mPermissionTrees =
7893 new HashMap<String, BasePermission>();
7894
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007895 // Packages that have been uninstalled and still need their external
7896 // storage data deleted.
7897 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7898
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007899 // Packages that have been renamed since they were first installed.
7900 // Keys are the new names of the packages, values are the original
7901 // names. The packages appear everwhere else under their original
7902 // names.
7903 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 private final StringBuilder mReadMessages = new StringBuilder();
7906
7907 private static final class PendingPackage extends PackageSettingBase {
7908 final int sharedId;
7909
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007910 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007911 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7912 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7913 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007914 this.sharedId = sharedId;
7915 }
7916 }
7917 private final ArrayList<PendingPackage> mPendingPackages
7918 = new ArrayList<PendingPackage>();
7919
7920 Settings() {
7921 File dataDir = Environment.getDataDirectory();
7922 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007923 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7924 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007925 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007926 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 FileUtils.setPermissions(systemDir.toString(),
7928 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7929 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7930 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007931 FileUtils.setPermissions(systemSecureDir.toString(),
7932 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7933 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7934 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007935 mSettingsFilename = new File(systemDir, "packages.xml");
7936 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007937 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007938 }
7939
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007940 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007941 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007942 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007943 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007944 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007945 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007946 return p;
7947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007948
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007949 PackageSetting peekPackageLP(String name) {
7950 return mPackages.get(name);
7951 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007952 PackageSetting p = mPackages.get(name);
7953 if (p != null && p.codePath.getPath().equals(codePath)) {
7954 return p;
7955 }
7956 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007957 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 void setInstallStatus(String pkgName, int status) {
7961 PackageSetting p = mPackages.get(pkgName);
7962 if(p != null) {
7963 if(p.getInstallStatus() != status) {
7964 p.setInstallStatus(status);
7965 }
7966 }
7967 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007968
Jacek Surazski65e13172009-04-28 15:26:38 +02007969 void setInstallerPackageName(String pkgName,
7970 String installerPkgName) {
7971 PackageSetting p = mPackages.get(pkgName);
7972 if(p != null) {
7973 p.setInstallerPackageName(installerPkgName);
7974 }
7975 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007976
Jacek Surazski65e13172009-04-28 15:26:38 +02007977 String getInstallerPackageName(String pkgName) {
7978 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007979 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007980 }
7981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 int getInstallStatus(String pkgName) {
7983 PackageSetting p = mPackages.get(pkgName);
7984 if(p != null) {
7985 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007987 return -1;
7988 }
7989
7990 SharedUserSetting getSharedUserLP(String name,
7991 int pkgFlags, boolean create) {
7992 SharedUserSetting s = mSharedUsers.get(name);
7993 if (s == null) {
7994 if (!create) {
7995 return null;
7996 }
7997 s = new SharedUserSetting(name, pkgFlags);
7998 if (MULTIPLE_APPLICATION_UIDS) {
7999 s.userId = newUserIdLP(s);
8000 } else {
8001 s.userId = FIRST_APPLICATION_UID;
8002 }
8003 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8004 // < 0 means we couldn't assign a userid; fall out and return
8005 // s, which is currently null
8006 if (s.userId >= 0) {
8007 mSharedUsers.put(name, s);
8008 }
8009 }
8010
8011 return s;
8012 }
8013
8014 int disableSystemPackageLP(String name) {
8015 PackageSetting p = mPackages.get(name);
8016 if(p == null) {
8017 Log.w(TAG, "Package:"+name+" is not an installed package");
8018 return -1;
8019 }
8020 PackageSetting dp = mDisabledSysPackages.get(name);
8021 // always make sure the system package code and resource paths dont change
8022 if(dp == null) {
8023 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8024 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8025 }
8026 mDisabledSysPackages.put(name, p);
8027 }
8028 return removePackageLP(name);
8029 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008030
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008031 PackageSetting enableSystemPackageLP(String name) {
8032 PackageSetting p = mDisabledSysPackages.get(name);
8033 if(p == null) {
8034 Log.w(TAG, "Package:"+name+" is not disabled");
8035 return null;
8036 }
8037 // Reset flag in ApplicationInfo object
8038 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8039 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8040 }
Kenny Root806cc132010-09-12 08:34:19 -07008041 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8042 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008043 mDisabledSysPackages.remove(name);
8044 return ret;
8045 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008046
Kenny Root806cc132010-09-12 08:34:19 -07008047 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8048 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 PackageSetting p = mPackages.get(name);
8050 if (p != null) {
8051 if (p.userId == uid) {
8052 return p;
8053 }
8054 reportSettingsProblem(Log.ERROR,
8055 "Adding duplicate package, keeping first: " + name);
8056 return null;
8057 }
Kenny Root806cc132010-09-12 08:34:19 -07008058 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8059 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 p.userId = uid;
8061 if (addUserIdLP(uid, p, name)) {
8062 mPackages.put(name, p);
8063 return p;
8064 }
8065 return null;
8066 }
8067
8068 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8069 SharedUserSetting s = mSharedUsers.get(name);
8070 if (s != null) {
8071 if (s.userId == uid) {
8072 return s;
8073 }
8074 reportSettingsProblem(Log.ERROR,
8075 "Adding duplicate shared user, keeping first: " + name);
8076 return null;
8077 }
8078 s = new SharedUserSetting(name, pkgFlags);
8079 s.userId = uid;
8080 if (addUserIdLP(uid, s, name)) {
8081 mSharedUsers.put(name, s);
8082 return s;
8083 }
8084 return null;
8085 }
8086
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008087 // Transfer ownership of permissions from one package to another.
8088 private void transferPermissions(String origPkg, String newPkg) {
8089 // Transfer ownership of permissions to the new package.
8090 for (int i=0; i<2; i++) {
8091 HashMap<String, BasePermission> permissions =
8092 i == 0 ? mPermissionTrees : mPermissions;
8093 for (BasePermission bp : permissions.values()) {
8094 if (origPkg.equals(bp.sourcePackage)) {
8095 if (DEBUG_UPGRADE) Log.v(TAG,
8096 "Moving permission " + bp.name
8097 + " from pkg " + bp.sourcePackage
8098 + " to " + newPkg);
8099 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008100 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008101 bp.perm = null;
8102 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008103 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008104 }
8105 bp.uid = 0;
8106 bp.gids = null;
8107 }
8108 }
8109 }
8110 }
8111
8112 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008113 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008114 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008115 PackageSetting p = mPackages.get(name);
8116 if (p != null) {
8117 if (!p.codePath.equals(codePath)) {
8118 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008119 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008120 // This is an updated system app with versions in both system
8121 // and data partition. Just let the most recent version
8122 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008123 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008124 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008125 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008126 // Just a change in the code path is not an issue, but
8127 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008128 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008129 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008130 /*
8131 * Since we've changed paths, we need to prefer the new
8132 * native library path over the one stored in the
8133 * package settings since we might have moved from
8134 * internal to external storage or vice versa.
8135 */
8136 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008137 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008138 }
8139 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008140 reportSettingsProblem(Log.WARN,
8141 "Package " + name + " shared user changed from "
8142 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8143 + " to "
8144 + (sharedUser != null ? sharedUser.name : "<nothing>")
8145 + "; replacing with new");
8146 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008147 } else {
8148 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8149 // If what we are scanning is a system package, then
8150 // make it so, regardless of whether it was previously
8151 // installed only in the data partition.
8152 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008154 }
8155 }
8156 if (p == null) {
8157 // Create a new PackageSettings entry. this can end up here because
8158 // of code path mismatch or user id mismatch of an updated system partition
8159 if (!create) {
8160 return null;
8161 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008162 if (origPackage != null) {
8163 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008164 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8165 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008166 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8167 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008168 // Note that we will retain the new package's signature so
8169 // that we can keep its data.
8170 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008171 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008172 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008173 p.sharedUser = origPackage.sharedUser;
8174 p.userId = origPackage.userId;
8175 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008176 mRenamedPackages.put(name, origPackage.name);
8177 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008178 // Update new package state.
8179 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008180 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008181 p = new PackageSetting(name, realName, codePath, resourcePath,
8182 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008183 p.setTimeStamp(codePath.lastModified());
8184 p.sharedUser = sharedUser;
8185 if (sharedUser != null) {
8186 p.userId = sharedUser.userId;
8187 } else if (MULTIPLE_APPLICATION_UIDS) {
8188 // Clone the setting here for disabled system packages
8189 PackageSetting dis = mDisabledSysPackages.get(name);
8190 if (dis != null) {
8191 // For disabled packages a new setting is created
8192 // from the existing user id. This still has to be
8193 // added to list of user id's
8194 // Copy signatures from previous setting
8195 if (dis.signatures.mSignatures != null) {
8196 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8197 }
8198 p.userId = dis.userId;
8199 // Clone permissions
8200 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008201 // Clone component info
8202 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8203 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8204 // Add new setting to list of user ids
8205 addUserIdLP(p.userId, p, name);
8206 } else {
8207 // Assign new user id
8208 p.userId = newUserIdLP(p);
8209 }
8210 } else {
8211 p.userId = FIRST_APPLICATION_UID;
8212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 }
8214 if (p.userId < 0) {
8215 reportSettingsProblem(Log.WARN,
8216 "Package " + name + " could not be assigned a valid uid");
8217 return null;
8218 }
8219 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008220 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008221 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008222 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008223 }
8224 }
8225 return p;
8226 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008227
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008228 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008229 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008230 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008231 final String codePath = pkg.applicationInfo.sourceDir;
8232 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008233 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008234 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008235 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008236 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008237 p.codePath = new File(codePath);
8238 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008239 }
8240 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008241 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008242 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008243 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008244 p.resourcePath = new File(resourcePath);
8245 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008246 }
Kenny Root85387d72010-08-26 10:13:11 -07008247 // Update the native library path if needed
8248 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8249 if (nativeLibraryPath != null
8250 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8251 p.nativeLibraryPathString = nativeLibraryPath;
8252 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008253 // Update version code if needed
8254 if (pkg.mVersionCode != p.versionCode) {
8255 p.versionCode = pkg.mVersionCode;
8256 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008257 // Update signatures if needed.
8258 if (p.signatures.mSignatures == null) {
8259 p.signatures.assignSignatures(pkg.mSignatures);
8260 }
8261 // If this app defines a shared user id initialize
8262 // the shared user signatures as well.
8263 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8264 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8265 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008266 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8267 }
8268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008269 // Utility method that adds a PackageSetting to mPackages and
8270 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008271 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008272 SharedUserSetting sharedUser) {
8273 mPackages.put(name, p);
8274 if (sharedUser != null) {
8275 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8276 reportSettingsProblem(Log.ERROR,
8277 "Package " + p.name + " was user "
8278 + p.sharedUser + " but is now " + sharedUser
8279 + "; I am not changing its files so it will probably fail!");
8280 p.sharedUser.packages.remove(p);
8281 } else if (p.userId != sharedUser.userId) {
8282 reportSettingsProblem(Log.ERROR,
8283 "Package " + p.name + " was user id " + p.userId
8284 + " but is now user " + sharedUser
8285 + " with id " + sharedUser.userId
8286 + "; I am not changing its files so it will probably fail!");
8287 }
8288
8289 sharedUser.packages.add(p);
8290 p.sharedUser = sharedUser;
8291 p.userId = sharedUser.userId;
8292 }
8293 }
8294
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008295 /*
8296 * Update the shared user setting when a package using
8297 * specifying the shared user id is removed. The gids
8298 * associated with each permission of the deleted package
8299 * are removed from the shared user's gid list only if its
8300 * not in use by other permissions of packages in the
8301 * shared user setting.
8302 */
8303 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008305 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008306 return;
8307 }
8308 // No sharedUserId
8309 if (deletedPs.sharedUser == null) {
8310 return;
8311 }
8312 SharedUserSetting sus = deletedPs.sharedUser;
8313 // Update permissions
8314 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8315 boolean used = false;
8316 if (!sus.grantedPermissions.contains (eachPerm)) {
8317 continue;
8318 }
8319 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008320 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008321 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008322 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008323 used = true;
8324 break;
8325 }
8326 }
8327 if (!used) {
8328 // can safely delete this permission from list
8329 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008330 }
8331 }
8332 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008333 int newGids[] = globalGids;
8334 for (String eachPerm : sus.grantedPermissions) {
8335 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008336 if (bp != null) {
8337 newGids = appendInts(newGids, bp.gids);
8338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 }
8340 sus.gids = newGids;
8341 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008343 private int removePackageLP(String name) {
8344 PackageSetting p = mPackages.get(name);
8345 if (p != null) {
8346 mPackages.remove(name);
8347 if (p.sharedUser != null) {
8348 p.sharedUser.packages.remove(p);
8349 if (p.sharedUser.packages.size() == 0) {
8350 mSharedUsers.remove(p.sharedUser.name);
8351 removeUserIdLP(p.sharedUser.userId);
8352 return p.sharedUser.userId;
8353 }
8354 } else {
8355 removeUserIdLP(p.userId);
8356 return p.userId;
8357 }
8358 }
8359 return -1;
8360 }
8361
8362 private boolean addUserIdLP(int uid, Object obj, Object name) {
8363 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8364 return false;
8365 }
8366
8367 if (uid >= FIRST_APPLICATION_UID) {
8368 int N = mUserIds.size();
8369 final int index = uid - FIRST_APPLICATION_UID;
8370 while (index >= N) {
8371 mUserIds.add(null);
8372 N++;
8373 }
8374 if (mUserIds.get(index) != null) {
8375 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008376 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008377 + " name=" + name);
8378 return false;
8379 }
8380 mUserIds.set(index, obj);
8381 } else {
8382 if (mOtherUserIds.get(uid) != null) {
8383 reportSettingsProblem(Log.ERROR,
8384 "Adding duplicate shared id: " + uid
8385 + " name=" + name);
8386 return false;
8387 }
8388 mOtherUserIds.put(uid, obj);
8389 }
8390 return true;
8391 }
8392
8393 public Object getUserIdLP(int uid) {
8394 if (uid >= FIRST_APPLICATION_UID) {
8395 int N = mUserIds.size();
8396 final int index = uid - FIRST_APPLICATION_UID;
8397 return index < N ? mUserIds.get(index) : null;
8398 } else {
8399 return mOtherUserIds.get(uid);
8400 }
8401 }
8402
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008403 private Set<String> findPackagesWithFlag(int flag) {
8404 Set<String> ret = new HashSet<String>();
8405 for (PackageSetting ps : mPackages.values()) {
8406 // Has to match atleast all the flag bits set on flag
8407 if ((ps.pkgFlags & flag) == flag) {
8408 ret.add(ps.name);
8409 }
8410 }
8411 return ret;
8412 }
8413
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008414 private void removeUserIdLP(int uid) {
8415 if (uid >= FIRST_APPLICATION_UID) {
8416 int N = mUserIds.size();
8417 final int index = uid - FIRST_APPLICATION_UID;
8418 if (index < N) mUserIds.set(index, null);
8419 } else {
8420 mOtherUserIds.remove(uid);
8421 }
8422 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008424 void writeLP() {
8425 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8426
8427 // Keep the old settings around until we know the new ones have
8428 // been successfully written.
8429 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008430 // Presence of backup settings file indicates that we failed
8431 // to persist settings earlier. So preserve the older
8432 // backup for future reference since the current settings
8433 // might have been corrupted.
8434 if (!mBackupSettingsFilename.exists()) {
8435 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008436 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008437 return;
8438 }
8439 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008440 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008441 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008443 }
8444
8445 mPastSignatures.clear();
8446
8447 try {
Kenny Root9f306d72010-09-26 11:19:47 -07008448 BufferedOutputStream str = new BufferedOutputStream(new FileOutputStream(
8449 mSettingsFilename));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008450
8451 //XmlSerializer serializer = XmlUtils.serializerInstance();
8452 XmlSerializer serializer = new FastXmlSerializer();
8453 serializer.setOutput(str, "utf-8");
8454 serializer.startDocument(null, true);
8455 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8456
8457 serializer.startTag(null, "packages");
8458
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008459 serializer.startTag(null, "last-platform-version");
8460 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8461 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8462 serializer.endTag(null, "last-platform-version");
8463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464 serializer.startTag(null, "permission-trees");
8465 for (BasePermission bp : mPermissionTrees.values()) {
8466 writePermission(serializer, bp);
8467 }
8468 serializer.endTag(null, "permission-trees");
8469
8470 serializer.startTag(null, "permissions");
8471 for (BasePermission bp : mPermissions.values()) {
8472 writePermission(serializer, bp);
8473 }
8474 serializer.endTag(null, "permissions");
8475
8476 for (PackageSetting pkg : mPackages.values()) {
8477 writePackage(serializer, pkg);
8478 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008479
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008480 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8481 writeDisabledSysPackage(serializer, pkg);
8482 }
8483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008484 serializer.startTag(null, "preferred-activities");
8485 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8486 serializer.startTag(null, "item");
8487 pa.writeToXml(serializer);
8488 serializer.endTag(null, "item");
8489 }
8490 serializer.endTag(null, "preferred-activities");
8491
8492 for (SharedUserSetting usr : mSharedUsers.values()) {
8493 serializer.startTag(null, "shared-user");
8494 serializer.attribute(null, "name", usr.name);
8495 serializer.attribute(null, "userId",
8496 Integer.toString(usr.userId));
8497 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8498 serializer.startTag(null, "perms");
8499 for (String name : usr.grantedPermissions) {
8500 serializer.startTag(null, "item");
8501 serializer.attribute(null, "name", name);
8502 serializer.endTag(null, "item");
8503 }
8504 serializer.endTag(null, "perms");
8505 serializer.endTag(null, "shared-user");
8506 }
8507
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008508 if (mPackagesToBeCleaned.size() > 0) {
8509 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8510 serializer.startTag(null, "cleaning-package");
8511 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8512 serializer.endTag(null, "cleaning-package");
8513 }
8514 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008515
8516 if (mRenamedPackages.size() > 0) {
8517 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8518 serializer.startTag(null, "renamed-package");
8519 serializer.attribute(null, "new", e.getKey());
8520 serializer.attribute(null, "old", e.getValue());
8521 serializer.endTag(null, "renamed-package");
8522 }
8523 }
8524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 serializer.endTag(null, "packages");
8526
8527 serializer.endDocument();
8528
8529 str.flush();
8530 str.close();
8531
8532 // New settings successfully written, old ones are no longer
8533 // needed.
8534 mBackupSettingsFilename.delete();
8535 FileUtils.setPermissions(mSettingsFilename.toString(),
8536 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8537 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8538 |FileUtils.S_IROTH,
8539 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008540
8541 // Write package list file now, use a JournaledFile.
8542 //
8543 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8544 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8545
Kenny Root9f306d72010-09-26 11:19:47 -07008546 str = new BufferedOutputStream(new FileOutputStream(journal.chooseForWrite()));
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008547 try {
8548 StringBuilder sb = new StringBuilder();
8549 for (PackageSetting pkg : mPackages.values()) {
8550 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008551 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008552 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8553
8554 // Avoid any application that has a space in its path
8555 // or that is handled by the system.
8556 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8557 continue;
8558
8559 // we store on each line the following information for now:
8560 //
8561 // pkgName - package name
8562 // userId - application-specific user id
8563 // debugFlag - 0 or 1 if the package is debuggable.
8564 // dataPath - path to package's data path
8565 //
8566 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8567 //
8568 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8569 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8570 // system/core/run-as/run-as.c
8571 //
8572 sb.setLength(0);
8573 sb.append(ai.packageName);
8574 sb.append(" ");
8575 sb.append((int)ai.uid);
8576 sb.append(isDebug ? " 1 " : " 0 ");
8577 sb.append(dataPath);
8578 sb.append("\n");
8579 str.write(sb.toString().getBytes());
8580 }
8581 str.flush();
8582 str.close();
8583 journal.commit();
8584 }
8585 catch (Exception e) {
8586 journal.rollback();
8587 }
8588
8589 FileUtils.setPermissions(mPackageListFilename.toString(),
8590 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8591 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8592 |FileUtils.S_IROTH,
8593 -1, -1);
8594
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008595 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008596
8597 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008598 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 -08008599 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008600 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 -08008601 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008602 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008603 if (mSettingsFilename.exists()) {
8604 if (!mSettingsFilename.delete()) {
8605 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8606 }
8607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008608 //Debug.stopMethodTracing();
8609 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008610
8611 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008612 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 serializer.startTag(null, "updated-package");
8614 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008615 if (pkg.realName != null) {
8616 serializer.attribute(null, "realName", pkg.realName);
8617 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008619 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8620 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8621 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008622 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008623 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8624 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8625 }
Kenny Root85387d72010-08-26 10:13:11 -07008626 if (pkg.nativeLibraryPathString != null) {
8627 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629 if (pkg.sharedUser == null) {
8630 serializer.attribute(null, "userId",
8631 Integer.toString(pkg.userId));
8632 } else {
8633 serializer.attribute(null, "sharedUserId",
8634 Integer.toString(pkg.userId));
8635 }
8636 serializer.startTag(null, "perms");
8637 if (pkg.sharedUser == null) {
8638 // If this is a shared user, the permissions will
8639 // be written there. We still need to write an
8640 // empty permissions list so permissionsFixed will
8641 // be set.
8642 for (final String name : pkg.grantedPermissions) {
8643 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008644 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 // We only need to write signature or system permissions but this wont
8646 // match the semantics of grantedPermissions. So write all permissions.
8647 serializer.startTag(null, "item");
8648 serializer.attribute(null, "name", name);
8649 serializer.endTag(null, "item");
8650 }
8651 }
8652 }
8653 serializer.endTag(null, "perms");
8654 serializer.endTag(null, "updated-package");
8655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008656
8657 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008658 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008659 serializer.startTag(null, "package");
8660 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008661 if (pkg.realName != null) {
8662 serializer.attribute(null, "realName", pkg.realName);
8663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008664 serializer.attribute(null, "codePath", pkg.codePathString);
8665 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8666 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8667 }
Kenny Root85387d72010-08-26 10:13:11 -07008668 if (pkg.nativeLibraryPathString != null) {
8669 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8670 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008671 serializer.attribute(null, "flags",
8672 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008673 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8674 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8675 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008676 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008677 if (pkg.sharedUser == null) {
8678 serializer.attribute(null, "userId",
8679 Integer.toString(pkg.userId));
8680 } else {
8681 serializer.attribute(null, "sharedUserId",
8682 Integer.toString(pkg.userId));
8683 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008684 if (pkg.uidError) {
8685 serializer.attribute(null, "uidError", "true");
8686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008687 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8688 serializer.attribute(null, "enabled",
8689 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8690 ? "true" : "false");
8691 }
8692 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8693 serializer.attribute(null, "installStatus", "false");
8694 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008695 if (pkg.installerPackageName != null) {
8696 serializer.attribute(null, "installer", pkg.installerPackageName);
8697 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008698 if (pkg.obbPathString != null) {
8699 serializer.attribute(null, "obbPath", pkg.obbPathString);
8700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008701 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8702 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8703 serializer.startTag(null, "perms");
8704 if (pkg.sharedUser == null) {
8705 // If this is a shared user, the permissions will
8706 // be written there. We still need to write an
8707 // empty permissions list so permissionsFixed will
8708 // be set.
8709 for (final String name : pkg.grantedPermissions) {
8710 serializer.startTag(null, "item");
8711 serializer.attribute(null, "name", name);
8712 serializer.endTag(null, "item");
8713 }
8714 }
8715 serializer.endTag(null, "perms");
8716 }
8717 if (pkg.disabledComponents.size() > 0) {
8718 serializer.startTag(null, "disabled-components");
8719 for (final String name : pkg.disabledComponents) {
8720 serializer.startTag(null, "item");
8721 serializer.attribute(null, "name", name);
8722 serializer.endTag(null, "item");
8723 }
8724 serializer.endTag(null, "disabled-components");
8725 }
8726 if (pkg.enabledComponents.size() > 0) {
8727 serializer.startTag(null, "enabled-components");
8728 for (final String name : pkg.enabledComponents) {
8729 serializer.startTag(null, "item");
8730 serializer.attribute(null, "name", name);
8731 serializer.endTag(null, "item");
8732 }
8733 serializer.endTag(null, "enabled-components");
8734 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008736 serializer.endTag(null, "package");
8737 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 void writePermission(XmlSerializer serializer, BasePermission bp)
8740 throws XmlPullParserException, java.io.IOException {
8741 if (bp.type != BasePermission.TYPE_BUILTIN
8742 && bp.sourcePackage != null) {
8743 serializer.startTag(null, "item");
8744 serializer.attribute(null, "name", bp.name);
8745 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008746 if (bp.protectionLevel !=
8747 PermissionInfo.PROTECTION_NORMAL) {
8748 serializer.attribute(null, "protection",
8749 Integer.toString(bp.protectionLevel));
8750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008751 if (DEBUG_SETTINGS) Log.v(TAG,
8752 "Writing perm: name=" + bp.name + " type=" + bp.type);
8753 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8754 PermissionInfo pi = bp.perm != null ? bp.perm.info
8755 : bp.pendingInfo;
8756 if (pi != null) {
8757 serializer.attribute(null, "type", "dynamic");
8758 if (pi.icon != 0) {
8759 serializer.attribute(null, "icon",
8760 Integer.toString(pi.icon));
8761 }
8762 if (pi.nonLocalizedLabel != null) {
8763 serializer.attribute(null, "label",
8764 pi.nonLocalizedLabel.toString());
8765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 }
8767 }
8768 serializer.endTag(null, "item");
8769 }
8770 }
8771
8772 String getReadMessagesLP() {
8773 return mReadMessages.toString();
8774 }
8775
Oscar Montemayora8529f62009-11-18 10:14:20 -08008776 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008777 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8778 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008779 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008780 while(its.hasNext()) {
8781 String key = its.next();
8782 PackageSetting ps = mPackages.get(key);
8783 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008784 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 }
8786 }
8787 return ret;
8788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008790 boolean readLP() {
8791 FileInputStream str = null;
8792 if (mBackupSettingsFilename.exists()) {
8793 try {
8794 str = new FileInputStream(mBackupSettingsFilename);
8795 mReadMessages.append("Reading from backup settings file\n");
8796 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008797 if (mSettingsFilename.exists()) {
8798 // If both the backup and settings file exist, we
8799 // ignore the settings since it might have been
8800 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008801 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008802 mSettingsFilename.delete();
8803 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804 } catch (java.io.IOException e) {
8805 // We'll try for the normal settings file.
8806 }
8807 }
8808
8809 mPastSignatures.clear();
8810
8811 try {
8812 if (str == null) {
8813 if (!mSettingsFilename.exists()) {
8814 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008815 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008816 return false;
8817 }
8818 str = new FileInputStream(mSettingsFilename);
8819 }
8820 XmlPullParser parser = Xml.newPullParser();
8821 parser.setInput(str, null);
8822
8823 int type;
8824 while ((type=parser.next()) != XmlPullParser.START_TAG
8825 && type != XmlPullParser.END_DOCUMENT) {
8826 ;
8827 }
8828
8829 if (type != XmlPullParser.START_TAG) {
8830 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008831 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832 return false;
8833 }
8834
8835 int outerDepth = parser.getDepth();
8836 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8837 && (type != XmlPullParser.END_TAG
8838 || parser.getDepth() > outerDepth)) {
8839 if (type == XmlPullParser.END_TAG
8840 || type == XmlPullParser.TEXT) {
8841 continue;
8842 }
8843
8844 String tagName = parser.getName();
8845 if (tagName.equals("package")) {
8846 readPackageLP(parser);
8847 } else if (tagName.equals("permissions")) {
8848 readPermissionsLP(mPermissions, parser);
8849 } else if (tagName.equals("permission-trees")) {
8850 readPermissionsLP(mPermissionTrees, parser);
8851 } else if (tagName.equals("shared-user")) {
8852 readSharedUserLP(parser);
8853 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008854 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008855 } else if (tagName.equals("preferred-activities")) {
8856 readPreferredActivitiesLP(parser);
8857 } else if(tagName.equals("updated-package")) {
8858 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008859 } else if (tagName.equals("cleaning-package")) {
8860 String name = parser.getAttributeValue(null, "name");
8861 if (name != null) {
8862 mPackagesToBeCleaned.add(name);
8863 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008864 } else if (tagName.equals("renamed-package")) {
8865 String nname = parser.getAttributeValue(null, "new");
8866 String oname = parser.getAttributeValue(null, "old");
8867 if (nname != null && oname != null) {
8868 mRenamedPackages.put(nname, oname);
8869 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008870 } else if (tagName.equals("last-platform-version")) {
8871 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8872 try {
8873 String internal = parser.getAttributeValue(null, "internal");
8874 if (internal != null) {
8875 mInternalSdkPlatform = Integer.parseInt(internal);
8876 }
8877 String external = parser.getAttributeValue(null, "external");
8878 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008879 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008880 }
8881 } catch (NumberFormatException e) {
8882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008884 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 + parser.getName());
8886 XmlUtils.skipCurrentTag(parser);
8887 }
8888 }
8889
8890 str.close();
8891
8892 } catch(XmlPullParserException e) {
8893 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008894 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008895
8896 } catch(java.io.IOException e) {
8897 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008898 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008899
8900 }
8901
8902 int N = mPendingPackages.size();
8903 for (int i=0; i<N; i++) {
8904 final PendingPackage pp = mPendingPackages.get(i);
8905 Object idObj = getUserIdLP(pp.sharedId);
8906 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008907 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008908 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8909 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008910 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008911 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008912 + pp.name);
8913 continue;
8914 }
8915 p.copyFrom(pp);
8916 } else if (idObj != null) {
8917 String msg = "Bad package setting: package " + pp.name
8918 + " has shared uid " + pp.sharedId
8919 + " that is not a shared uid\n";
8920 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008921 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008922 } else {
8923 String msg = "Bad package setting: package " + pp.name
8924 + " has shared uid " + pp.sharedId
8925 + " that is not defined\n";
8926 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008927 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928 }
8929 }
8930 mPendingPackages.clear();
8931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932 mReadMessages.append("Read completed successfully: "
8933 + mPackages.size() + " packages, "
8934 + mSharedUsers.size() + " shared uids\n");
8935
8936 return true;
8937 }
8938
8939 private int readInt(XmlPullParser parser, String ns, String name,
8940 int defValue) {
8941 String v = parser.getAttributeValue(ns, name);
8942 try {
8943 if (v == null) {
8944 return defValue;
8945 }
8946 return Integer.parseInt(v);
8947 } catch (NumberFormatException e) {
8948 reportSettingsProblem(Log.WARN,
8949 "Error in package manager settings: attribute " +
8950 name + " has bad integer value " + v + " at "
8951 + parser.getPositionDescription());
8952 }
8953 return defValue;
8954 }
8955
8956 private void readPermissionsLP(HashMap<String, BasePermission> out,
8957 XmlPullParser parser)
8958 throws IOException, XmlPullParserException {
8959 int outerDepth = parser.getDepth();
8960 int type;
8961 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8962 && (type != XmlPullParser.END_TAG
8963 || parser.getDepth() > outerDepth)) {
8964 if (type == XmlPullParser.END_TAG
8965 || type == XmlPullParser.TEXT) {
8966 continue;
8967 }
8968
8969 String tagName = parser.getName();
8970 if (tagName.equals("item")) {
8971 String name = parser.getAttributeValue(null, "name");
8972 String sourcePackage = parser.getAttributeValue(null, "package");
8973 String ptype = parser.getAttributeValue(null, "type");
8974 if (name != null && sourcePackage != null) {
8975 boolean dynamic = "dynamic".equals(ptype);
8976 BasePermission bp = new BasePermission(name, sourcePackage,
8977 dynamic
8978 ? BasePermission.TYPE_DYNAMIC
8979 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008980 bp.protectionLevel = readInt(parser, null, "protection",
8981 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008982 if (dynamic) {
8983 PermissionInfo pi = new PermissionInfo();
8984 pi.packageName = sourcePackage.intern();
8985 pi.name = name.intern();
8986 pi.icon = readInt(parser, null, "icon", 0);
8987 pi.nonLocalizedLabel = parser.getAttributeValue(
8988 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008989 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008990 bp.pendingInfo = pi;
8991 }
8992 out.put(bp.name, bp);
8993 } else {
8994 reportSettingsProblem(Log.WARN,
8995 "Error in package manager settings: permissions has"
8996 + " no name at " + parser.getPositionDescription());
8997 }
8998 } else {
8999 reportSettingsProblem(Log.WARN,
9000 "Unknown element reading permissions: "
9001 + parser.getName() + " at "
9002 + parser.getPositionDescription());
9003 }
9004 XmlUtils.skipCurrentTag(parser);
9005 }
9006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009009 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009010 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009011 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 String codePathStr = parser.getAttributeValue(null, "codePath");
9013 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009014 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009015 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 resourcePathStr = codePathStr;
9017 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009018 String version = parser.getAttributeValue(null, "version");
9019 int versionCode = 0;
9020 if (version != null) {
9021 try {
9022 versionCode = Integer.parseInt(version);
9023 } catch (NumberFormatException e) {
9024 }
9025 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009026
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 int pkgFlags = 0;
9028 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009029 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9030 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009031 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009032 if (timeStampStr != null) {
9033 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009034 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009035 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 } catch (NumberFormatException e) {
9037 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009038 } else {
9039 timeStampStr = parser.getAttributeValue(null, "ts");
9040 if (timeStampStr != null) {
9041 try {
9042 long timeStamp = Long.parseLong(timeStampStr);
9043 ps.setTimeStamp(timeStamp);
9044 } catch (NumberFormatException e) {
9045 }
9046 }
9047 }
9048 timeStampStr = parser.getAttributeValue(null, "it");
9049 if (timeStampStr != null) {
9050 try {
9051 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9052 } catch (NumberFormatException e) {
9053 }
9054 }
9055 timeStampStr = parser.getAttributeValue(null, "ut");
9056 if (timeStampStr != null) {
9057 try {
9058 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9059 } catch (NumberFormatException e) {
9060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 }
9062 String idStr = parser.getAttributeValue(null, "userId");
9063 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9064 if(ps.userId <= 0) {
9065 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9066 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9067 }
9068 int outerDepth = parser.getDepth();
9069 int type;
9070 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9071 && (type != XmlPullParser.END_TAG
9072 || parser.getDepth() > outerDepth)) {
9073 if (type == XmlPullParser.END_TAG
9074 || type == XmlPullParser.TEXT) {
9075 continue;
9076 }
9077
9078 String tagName = parser.getName();
9079 if (tagName.equals("perms")) {
9080 readGrantedPermissionsLP(parser,
9081 ps.grantedPermissions);
9082 } else {
9083 reportSettingsProblem(Log.WARN,
9084 "Unknown element under <updated-package>: "
9085 + parser.getName());
9086 XmlUtils.skipCurrentTag(parser);
9087 }
9088 }
9089 mDisabledSysPackages.put(name, ps);
9090 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009092 private void readPackageLP(XmlPullParser parser)
9093 throws XmlPullParserException, IOException {
9094 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009095 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 String idStr = null;
9097 String sharedIdStr = null;
9098 String codePathStr = null;
9099 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009100 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009101 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009102 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009103 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009104 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009105 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009106 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009107 long firstInstallTime = 0;
9108 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009109 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009110 String version = null;
9111 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009112 try {
9113 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009114 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009115 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009116 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009117 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9118 codePathStr = parser.getAttributeValue(null, "codePath");
9119 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009120 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009121 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009122 version = parser.getAttributeValue(null, "version");
9123 if (version != null) {
9124 try {
9125 versionCode = Integer.parseInt(version);
9126 } catch (NumberFormatException e) {
9127 }
9128 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009129 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009130
9131 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009132 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009133 try {
9134 pkgFlags = Integer.parseInt(systemStr);
9135 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009136 }
9137 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009138 // For backward compatibility
9139 systemStr = parser.getAttributeValue(null, "system");
9140 if (systemStr != null) {
9141 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9142 } else {
9143 // Old settings that don't specify system... just treat
9144 // them as system, good enough.
9145 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009147 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009148 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 if (timeStampStr != null) {
9150 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009151 timeStamp = Long.parseLong(timeStampStr, 16);
9152 } catch (NumberFormatException e) {
9153 }
9154 } else {
9155 timeStampStr = parser.getAttributeValue(null, "ts");
9156 if (timeStampStr != null) {
9157 try {
9158 timeStamp = Long.parseLong(timeStampStr);
9159 } catch (NumberFormatException e) {
9160 }
9161 }
9162 }
9163 timeStampStr = parser.getAttributeValue(null, "it");
9164 if (timeStampStr != null) {
9165 try {
9166 firstInstallTime = Long.parseLong(timeStampStr, 16);
9167 } catch (NumberFormatException e) {
9168 }
9169 }
9170 timeStampStr = parser.getAttributeValue(null, "ut");
9171 if (timeStampStr != null) {
9172 try {
9173 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009174 } catch (NumberFormatException e) {
9175 }
9176 }
9177 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9178 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9179 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9180 if (resourcePathStr == null) {
9181 resourcePathStr = codePathStr;
9182 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009183 if (realName != null) {
9184 realName = realName.intern();
9185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009186 if (name == null) {
9187 reportSettingsProblem(Log.WARN,
9188 "Error in package manager settings: <package> has no name at "
9189 + parser.getPositionDescription());
9190 } else if (codePathStr == null) {
9191 reportSettingsProblem(Log.WARN,
9192 "Error in package manager settings: <package> has no codePath at "
9193 + parser.getPositionDescription());
9194 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009195 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9196 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9197 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9199 + ": userId=" + userId + " pkg=" + packageSetting);
9200 if (packageSetting == null) {
9201 reportSettingsProblem(Log.ERROR,
9202 "Failure adding uid " + userId
9203 + " while parsing settings at "
9204 + parser.getPositionDescription());
9205 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009206 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009207 packageSetting.firstInstallTime = firstInstallTime;
9208 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009209 }
9210 } else if (sharedIdStr != null) {
9211 userId = sharedIdStr != null
9212 ? Integer.parseInt(sharedIdStr) : 0;
9213 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009214 packageSetting = new PendingPackage(name.intern(), realName,
9215 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009216 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009217 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009218 packageSetting.firstInstallTime = firstInstallTime;
9219 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009220 mPendingPackages.add((PendingPackage) packageSetting);
9221 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9222 + ": sharedUserId=" + userId + " pkg="
9223 + packageSetting);
9224 } else {
9225 reportSettingsProblem(Log.WARN,
9226 "Error in package manager settings: package "
9227 + name + " has bad sharedId " + sharedIdStr
9228 + " at " + parser.getPositionDescription());
9229 }
9230 } else {
9231 reportSettingsProblem(Log.WARN,
9232 "Error in package manager settings: package "
9233 + name + " has bad userId " + idStr + " at "
9234 + parser.getPositionDescription());
9235 }
9236 } catch (NumberFormatException e) {
9237 reportSettingsProblem(Log.WARN,
9238 "Error in package manager settings: package "
9239 + name + " has bad userId " + idStr + " at "
9240 + parser.getPositionDescription());
9241 }
9242 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009243 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009244 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009245 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009246 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009247 final String enabledStr = parser.getAttributeValue(null, "enabled");
9248 if (enabledStr != null) {
9249 if (enabledStr.equalsIgnoreCase("true")) {
9250 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9251 } else if (enabledStr.equalsIgnoreCase("false")) {
9252 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9253 } else if (enabledStr.equalsIgnoreCase("default")) {
9254 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9255 } else {
9256 reportSettingsProblem(Log.WARN,
9257 "Error in package manager settings: package "
9258 + name + " has bad enabled value: " + idStr
9259 + " at " + parser.getPositionDescription());
9260 }
9261 } else {
9262 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9263 }
9264 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9265 if (installStatusStr != null) {
9266 if (installStatusStr.equalsIgnoreCase("false")) {
9267 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9268 } else {
9269 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9270 }
9271 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273 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("disabled-components")) {
9285 readDisabledComponentsLP(packageSetting, parser);
9286 } else if (tagName.equals("enabled-components")) {
9287 readEnabledComponentsLP(packageSetting, parser);
9288 } else if (tagName.equals("sigs")) {
9289 packageSetting.signatures.readXml(parser, mPastSignatures);
9290 } else if (tagName.equals("perms")) {
9291 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009292 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009293 packageSetting.permissionsFixed = true;
9294 } else {
9295 reportSettingsProblem(Log.WARN,
9296 "Unknown element under <package>: "
9297 + parser.getName());
9298 XmlUtils.skipCurrentTag(parser);
9299 }
9300 }
9301 } else {
9302 XmlUtils.skipCurrentTag(parser);
9303 }
9304 }
9305
9306 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9307 XmlPullParser parser)
9308 throws IOException, XmlPullParserException {
9309 int outerDepth = parser.getDepth();
9310 int type;
9311 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9312 && (type != XmlPullParser.END_TAG
9313 || parser.getDepth() > outerDepth)) {
9314 if (type == XmlPullParser.END_TAG
9315 || type == XmlPullParser.TEXT) {
9316 continue;
9317 }
9318
9319 String tagName = parser.getName();
9320 if (tagName.equals("item")) {
9321 String name = parser.getAttributeValue(null, "name");
9322 if (name != null) {
9323 packageSetting.disabledComponents.add(name.intern());
9324 } else {
9325 reportSettingsProblem(Log.WARN,
9326 "Error in package manager settings: <disabled-components> has"
9327 + " no name at " + parser.getPositionDescription());
9328 }
9329 } else {
9330 reportSettingsProblem(Log.WARN,
9331 "Unknown element under <disabled-components>: "
9332 + parser.getName());
9333 }
9334 XmlUtils.skipCurrentTag(parser);
9335 }
9336 }
9337
9338 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9339 XmlPullParser parser)
9340 throws IOException, XmlPullParserException {
9341 int outerDepth = parser.getDepth();
9342 int type;
9343 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9344 && (type != XmlPullParser.END_TAG
9345 || parser.getDepth() > outerDepth)) {
9346 if (type == XmlPullParser.END_TAG
9347 || type == XmlPullParser.TEXT) {
9348 continue;
9349 }
9350
9351 String tagName = parser.getName();
9352 if (tagName.equals("item")) {
9353 String name = parser.getAttributeValue(null, "name");
9354 if (name != null) {
9355 packageSetting.enabledComponents.add(name.intern());
9356 } else {
9357 reportSettingsProblem(Log.WARN,
9358 "Error in package manager settings: <enabled-components> has"
9359 + " no name at " + parser.getPositionDescription());
9360 }
9361 } else {
9362 reportSettingsProblem(Log.WARN,
9363 "Unknown element under <enabled-components>: "
9364 + parser.getName());
9365 }
9366 XmlUtils.skipCurrentTag(parser);
9367 }
9368 }
9369
9370 private void readSharedUserLP(XmlPullParser parser)
9371 throws XmlPullParserException, IOException {
9372 String name = null;
9373 String idStr = null;
9374 int pkgFlags = 0;
9375 SharedUserSetting su = null;
9376 try {
9377 name = parser.getAttributeValue(null, "name");
9378 idStr = parser.getAttributeValue(null, "userId");
9379 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9380 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9381 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9382 }
9383 if (name == null) {
9384 reportSettingsProblem(Log.WARN,
9385 "Error in package manager settings: <shared-user> has no name at "
9386 + parser.getPositionDescription());
9387 } else if (userId == 0) {
9388 reportSettingsProblem(Log.WARN,
9389 "Error in package manager settings: shared-user "
9390 + name + " has bad userId " + idStr + " at "
9391 + parser.getPositionDescription());
9392 } else {
9393 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9394 reportSettingsProblem(Log.ERROR,
9395 "Occurred while parsing settings at "
9396 + parser.getPositionDescription());
9397 }
9398 }
9399 } catch (NumberFormatException e) {
9400 reportSettingsProblem(Log.WARN,
9401 "Error in package manager settings: package "
9402 + name + " has bad userId " + idStr + " at "
9403 + parser.getPositionDescription());
9404 };
9405
9406 if (su != null) {
9407 int outerDepth = parser.getDepth();
9408 int type;
9409 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9410 && (type != XmlPullParser.END_TAG
9411 || parser.getDepth() > outerDepth)) {
9412 if (type == XmlPullParser.END_TAG
9413 || type == XmlPullParser.TEXT) {
9414 continue;
9415 }
9416
9417 String tagName = parser.getName();
9418 if (tagName.equals("sigs")) {
9419 su.signatures.readXml(parser, mPastSignatures);
9420 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009421 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009422 } else {
9423 reportSettingsProblem(Log.WARN,
9424 "Unknown element under <shared-user>: "
9425 + parser.getName());
9426 XmlUtils.skipCurrentTag(parser);
9427 }
9428 }
9429
9430 } else {
9431 XmlUtils.skipCurrentTag(parser);
9432 }
9433 }
9434
9435 private void readGrantedPermissionsLP(XmlPullParser parser,
9436 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9437 int outerDepth = parser.getDepth();
9438 int type;
9439 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9440 && (type != XmlPullParser.END_TAG
9441 || parser.getDepth() > outerDepth)) {
9442 if (type == XmlPullParser.END_TAG
9443 || type == XmlPullParser.TEXT) {
9444 continue;
9445 }
9446
9447 String tagName = parser.getName();
9448 if (tagName.equals("item")) {
9449 String name = parser.getAttributeValue(null, "name");
9450 if (name != null) {
9451 outPerms.add(name.intern());
9452 } else {
9453 reportSettingsProblem(Log.WARN,
9454 "Error in package manager settings: <perms> has"
9455 + " no name at " + parser.getPositionDescription());
9456 }
9457 } else {
9458 reportSettingsProblem(Log.WARN,
9459 "Unknown element under <perms>: "
9460 + parser.getName());
9461 }
9462 XmlUtils.skipCurrentTag(parser);
9463 }
9464 }
9465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009466 private void readPreferredActivitiesLP(XmlPullParser parser)
9467 throws XmlPullParserException, IOException {
9468 int outerDepth = parser.getDepth();
9469 int type;
9470 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9471 && (type != XmlPullParser.END_TAG
9472 || parser.getDepth() > outerDepth)) {
9473 if (type == XmlPullParser.END_TAG
9474 || type == XmlPullParser.TEXT) {
9475 continue;
9476 }
9477
9478 String tagName = parser.getName();
9479 if (tagName.equals("item")) {
9480 PreferredActivity pa = new PreferredActivity(parser);
9481 if (pa.mParseError == null) {
9482 mPreferredActivities.addFilter(pa);
9483 } else {
9484 reportSettingsProblem(Log.WARN,
9485 "Error in package manager settings: <preferred-activity> "
9486 + pa.mParseError + " at "
9487 + parser.getPositionDescription());
9488 }
9489 } else {
9490 reportSettingsProblem(Log.WARN,
9491 "Unknown element under <preferred-activities>: "
9492 + parser.getName());
9493 XmlUtils.skipCurrentTag(parser);
9494 }
9495 }
9496 }
9497
9498 // Returns -1 if we could not find an available UserId to assign
9499 private int newUserIdLP(Object obj) {
9500 // Let's be stupidly inefficient for now...
9501 final int N = mUserIds.size();
9502 for (int i=0; i<N; i++) {
9503 if (mUserIds.get(i) == null) {
9504 mUserIds.set(i, obj);
9505 return FIRST_APPLICATION_UID + i;
9506 }
9507 }
9508
9509 // None left?
9510 if (N >= MAX_APPLICATION_UIDS) {
9511 return -1;
9512 }
9513
9514 mUserIds.add(obj);
9515 return FIRST_APPLICATION_UID + N;
9516 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009518 public PackageSetting getDisabledSystemPkg(String name) {
9519 synchronized(mPackages) {
9520 PackageSetting ps = mDisabledSysPackages.get(name);
9521 return ps;
9522 }
9523 }
9524
9525 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009526 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9527 return true;
9528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009529 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9530 if (Config.LOGV) {
9531 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9532 + " componentName = " + componentInfo.name);
9533 Log.v(TAG, "enabledComponents: "
9534 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9535 Log.v(TAG, "disabledComponents: "
9536 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9537 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009538 if (packageSettings == null) {
9539 if (false) {
9540 Log.w(TAG, "WAITING FOR DEBUGGER");
9541 Debug.waitForDebugger();
9542 Log.i(TAG, "We will crash!");
9543 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009544 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009545 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009546 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9547 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9548 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9549 return false;
9550 }
9551 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9552 return true;
9553 }
9554 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9555 return false;
9556 }
9557 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009558 }
9559 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009560
9561 // ------- apps on sdcard specific code -------
9562 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009563 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9564 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9565 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009566 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009567
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009568 private String getEncryptKey() {
9569 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009570 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9571 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009572 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009573 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9574 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009575 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009576 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009577 return null;
9578 }
9579 }
9580 return sdEncKey;
9581 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009582 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009583 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009584 } catch (IOException ioe) {
9585 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9586 + ioe);
9587 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009588 }
Rich Cannings8d578832010-09-09 15:12:40 -07009589
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009590 }
9591
Kenny Rootc78a8072010-07-27 15:18:38 -07009592 /* package */ static String getTempContainerId() {
9593 int tmpIdx = 1;
9594 String list[] = PackageHelper.getSecureContainerList();
9595 if (list != null) {
9596 for (final String name : list) {
9597 // Ignore null and non-temporary container entries
9598 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9599 continue;
9600 }
9601
9602 String subStr = name.substring(mTempContainerPrefix.length());
9603 try {
9604 int cid = Integer.parseInt(subStr);
9605 if (cid >= tmpIdx) {
9606 tmpIdx = cid + 1;
9607 }
9608 } catch (NumberFormatException e) {
9609 }
9610 }
9611 }
9612 return mTempContainerPrefix + tmpIdx;
9613 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009614
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009615 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009616 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009617 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009618 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9619 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9620 throw new SecurityException("Media status can only be updated by the system");
9621 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009622 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009623 Log.i(TAG, "Updating external media status from " +
9624 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9625 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009626 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9627 mediaStatus+", mMediaMounted=" + mMediaMounted);
9628 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009629 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9630 reportStatus ? 1 : 0, -1);
9631 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009632 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009633 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009634 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009635 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009636 // Queue up an async operation since the package installation may take a little while.
9637 mHandler.post(new Runnable() {
9638 public void run() {
9639 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009640 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009641 }
9642 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009643 }
9644
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009645 /*
9646 * Collect information of applications on external media, map them
9647 * against existing containers and update information based on current
9648 * mount status. Please note that we always have to report status
9649 * if reportStatus has been set to true especially when unloading packages.
9650 */
9651 private void updateExternalMediaStatusInner(boolean mediaStatus,
9652 boolean reportStatus) {
9653 // Collection of uids
9654 int uidArr[] = null;
9655 // Collection of stale containers
9656 HashSet<String> removeCids = new HashSet<String>();
9657 // Collection of packages on external media with valid containers.
9658 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9659 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009660 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009661 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009662 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009663 } else {
9664 // Process list of secure containers and categorize them
9665 // as active or stale based on their package internal state.
9666 int uidList[] = new int[list.length];
9667 int num = 0;
9668 synchronized (mPackages) {
9669 for (String cid : list) {
9670 SdInstallArgs args = new SdInstallArgs(cid);
9671 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009672 String pkgName = args.getPackageName();
9673 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009674 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9675 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009676 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009677 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009678 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9679 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009680 // The package status is changed only if the code path
9681 // matches between settings and the container id.
9682 if (ps != null && ps.codePathString != null &&
9683 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009684 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9685 " corresponds to pkg : " + pkgName +
9686 " at code path: " + ps.codePathString);
9687 // We do have a valid package installed on sdcard
9688 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009689 int uid = ps.userId;
9690 if (uid != -1) {
9691 uidList[num++] = uid;
9692 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009693 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009694 // Stale container on sdcard. Just delete
9695 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9696 removeCids.add(cid);
9697 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009698 }
9699 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009700
9701 if (num > 0) {
9702 // Sort uid list
9703 Arrays.sort(uidList, 0, num);
9704 // Throw away duplicates
9705 uidArr = new int[num];
9706 uidArr[0] = uidList[0];
9707 int di = 0;
9708 for (int i = 1; i < num; i++) {
9709 if (uidList[i-1] != uidList[i]) {
9710 uidArr[di++] = uidList[i];
9711 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009712 }
9713 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009714 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009715 // Process packages with valid entries.
9716 if (mediaStatus) {
9717 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009718 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009719 startCleaningPackages();
9720 } else {
9721 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009722 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009723 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009724 }
9725
9726 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009727 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009728 int size = pkgList.size();
9729 if (size > 0) {
9730 // Send broadcasts here
9731 Bundle extras = new Bundle();
9732 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9733 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009734 if (uidArr != null) {
9735 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9736 }
9737 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9738 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009739 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009740 }
9741 }
9742
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009743 /*
9744 * Look at potentially valid container ids from processCids
9745 * If package information doesn't match the one on record
9746 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009747 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009748 */
9749 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009750 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009751 ArrayList<String> pkgList = new ArrayList<String>();
9752 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009753 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009754 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009755 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009756 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9757 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009758 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009759 try {
9760 // Make sure there are no container errors first.
9761 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9762 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009763 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009764 " when installing from sdcard");
9765 continue;
9766 }
9767 // Check code path here.
9768 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009769 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009770 " does not match one in settings " + codePath);
9771 continue;
9772 }
9773 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009774 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009775 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009776 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009777 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009778 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009779 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009780 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009781 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009782 retCode = PackageManager.INSTALL_SUCCEEDED;
9783 pkgList.add(pkg.packageName);
9784 // Post process args
9785 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9786 }
9787 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009788 Slog.i(TAG, "Failed to install pkg from " +
9789 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009790 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009791 }
9792
9793 } finally {
9794 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9795 // Don't destroy container here. Wait till gc clears things up.
9796 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009797 }
9798 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009799 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009800 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009801 // If the platform SDK has changed since the last time we booted,
9802 // we need to re-grant app permission to catch any new ones that
9803 // appear. This is really a hack, and means that apps can in some
9804 // cases get permissions that the user didn't initially explicitly
9805 // allow... it would be nice to have some better way to handle
9806 // this situation.
9807 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9808 != mSdkVersion;
9809 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9810 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9811 + "; regranting permissions for external storage");
9812 mSettings.mExternalSdkPlatform = mSdkVersion;
9813
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009814 // Make sure group IDs have been assigned, and any permission
9815 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009816 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009817 // Persist settings
9818 mSettings.writeLP();
9819 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009820 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009821 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009822 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009823 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009824 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009825 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009826 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009827 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009828 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009829 if (removeCids != null) {
9830 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009831 if (cid.startsWith(mTempContainerPrefix)) {
9832 Log.i(TAG, "Destroying stale temporary container " + cid);
9833 PackageHelper.destroySdDir(cid);
9834 } else {
9835 Log.w(TAG, "Container " + cid + " is stale");
9836 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009837 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009838 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009839 }
9840
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009841 /*
9842 * Utility method to unload a list of specified containers
9843 */
9844 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9845 // Just unmount all valid containers.
9846 for (SdInstallArgs arg : cidArgs) {
9847 synchronized (mInstallLock) {
9848 arg.doPostDeleteLI(false);
9849 }
9850 }
9851 }
9852
9853 /*
9854 * Unload packages mounted on external media. This involves deleting
9855 * package data from internal structures, sending broadcasts about
9856 * diabled packages, gc'ing to free up references, unmounting all
9857 * secure containers corresponding to packages on external media, and
9858 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9859 * Please note that we always have to post this message if status has
9860 * been requested no matter what.
9861 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009862 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009863 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009864 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009865 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009866 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009867 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009868 for (SdInstallArgs args : keys) {
9869 String cid = args.cid;
9870 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009871 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009872 // Delete package internally
9873 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9874 synchronized (mInstallLock) {
9875 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009876 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009877 if (res) {
9878 pkgList.add(pkgName);
9879 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009880 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009881 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009882 }
9883 }
9884 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009885
9886 synchronized (mPackages) {
9887 // We didn't update the settings after removing each package;
9888 // write them now for all packages.
9889 mSettings.writeLP();
9890 }
9891
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009892 // We have to absolutely send UPDATED_MEDIA_STATUS only
9893 // after confirming that all the receivers processed the ordered
9894 // broadcast when packages get disabled, force a gc to clean things up.
9895 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009896 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009897 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9898 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9899 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009900 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9901 reportStatus ? 1 : 0, 1, keys);
9902 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009903 }
9904 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009905 } else {
9906 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9907 reportStatus ? 1 : 0, -1, keys);
9908 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009909 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009910 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009911
9912 public void movePackage(final String packageName,
9913 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009914 mContext.enforceCallingOrSelfPermission(
9915 android.Manifest.permission.MOVE_PACKAGE, null);
9916 int returnCode = PackageManager.MOVE_SUCCEEDED;
9917 int currFlags = 0;
9918 int newFlags = 0;
9919 synchronized (mPackages) {
9920 PackageParser.Package pkg = mPackages.get(packageName);
9921 if (pkg == null) {
9922 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009923 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009924 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009925 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009926 Slog.w(TAG, "Cannot move system application");
9927 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009928 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009929 Slog.w(TAG, "Cannot move forward locked app.");
9930 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009931 } else if (pkg.mOperationPending) {
9932 Slog.w(TAG, "Attempt to move package which has pending operations");
9933 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009934 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009935 // Find install location first
9936 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9937 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9938 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009939 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009940 } else {
9941 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9942 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009943 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9944 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009945 if (newFlags == currFlags) {
9946 Slog.w(TAG, "No move required. Trying to move to same location");
9947 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9948 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009949 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009950 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9951 pkg.mOperationPending = true;
9952 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009953 }
9954 }
9955 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009956 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009957 } else {
9958 Message msg = mHandler.obtainMessage(INIT_COPY);
9959 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009960 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9961 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9962 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009963 msg.obj = mp;
9964 mHandler.sendMessage(msg);
9965 }
9966 }
9967 }
9968
9969 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9970 // Queue up an async operation since the package deletion may take a little while.
9971 mHandler.post(new Runnable() {
9972 public void run() {
9973 mHandler.removeCallbacks(this);
9974 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009975 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9976 int uidArr[] = null;
9977 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009978 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009979 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009980 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009981 Slog.w(TAG, " Package " + mp.packageName +
9982 " doesn't exist. Aborting move");
9983 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9984 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9985 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9986 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9987 " Aborting move and returning error");
9988 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9989 } else {
9990 uidArr = new int[] { pkg.applicationInfo.uid };
9991 pkgList = new ArrayList<String>();
9992 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009993 }
9994 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009995 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9996 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009997 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009998 // Update package code and resource paths
9999 synchronized (mInstallLock) {
10000 synchronized (mPackages) {
10001 PackageParser.Package pkg = mPackages.get(mp.packageName);
10002 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010003 if (pkg == null) {
10004 Slog.w(TAG, " Package " + mp.packageName
10005 + " doesn't exist. Aborting move");
10006 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010007 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10008 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10009 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10010 " Aborting move and returning error");
10011 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10012 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010013 final String oldCodePath = pkg.mPath;
10014 final String newCodePath = mp.targetArgs.getCodePath();
10015 final String newResPath = mp.targetArgs.getResourcePath();
10016 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010017
10018 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10019 if (mInstaller
10020 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10021 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10022 } else {
10023 NativeLibraryHelper.copyNativeBinariesLI(
10024 new File(newCodePath), new File(newNativePath));
10025 }
10026 } else {
10027 if (mInstaller.linkNativeLibraryDirectory(
10028 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10029 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10030 }
10031 }
10032
10033 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10034 pkg.mPath = newCodePath;
10035 // Move dex files around
10036 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10037 // Moving of dex files failed. Set
10038 // error code and abort move.
10039 pkg.mPath = pkg.mScanPath;
10040 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10041 }
10042 }
10043
10044 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010045 pkg.mScanPath = newCodePath;
10046 pkg.applicationInfo.sourceDir = newCodePath;
10047 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010048 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010049 PackageSetting ps = (PackageSetting) pkg.mExtras;
10050 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10051 ps.codePathString = ps.codePath.getPath();
10052 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10053 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010054 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010055 // Set the application info flag correctly.
10056 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10057 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10058 } else {
10059 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10060 }
10061 ps.setFlags(pkg.applicationInfo.flags);
10062 mAppDirs.remove(oldCodePath);
10063 mAppDirs.put(newCodePath, pkg);
10064 // Persist settings
10065 mSettings.writeLP();
10066 }
10067 }
10068 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010069 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010070 // Send resources available broadcast
10071 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010072 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010073 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010074 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010075 // Clean up failed installation
10076 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010077 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010078 }
10079 } else {
10080 // Force a gc to clear things up.
10081 Runtime.getRuntime().gc();
10082 // Delete older code
10083 synchronized (mInstallLock) {
10084 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010085 }
10086 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010087
10088 // Allow more operations on this file if we didn't fail because
10089 // an operation was already pending for this package.
10090 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10091 synchronized (mPackages) {
10092 PackageParser.Package pkg = mPackages.get(mp.packageName);
10093 if (pkg != null) {
10094 pkg.mOperationPending = false;
10095 }
10096 }
10097 }
10098
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010099 IPackageMoveObserver observer = mp.observer;
10100 if (observer != null) {
10101 try {
10102 observer.packageMoved(mp.packageName, returnCode);
10103 } catch (RemoteException e) {
10104 Log.i(TAG, "Observer no longer exists.");
10105 }
10106 }
10107 }
10108 });
10109 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010110
10111 public boolean setInstallLocation(int loc) {
10112 mContext.enforceCallingOrSelfPermission(
10113 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10114 if (getInstallLocation() == loc) {
10115 return true;
10116 }
10117 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10118 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10119 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10120 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10121 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10122 return true;
10123 }
10124 return false;
10125 }
10126
10127 public int getInstallLocation() {
10128 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10129 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10130 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010131}