blob: 58ea4db6d643449ba102461c72da51e5179aad7b [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
57import android.content.pm.PackageStats;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
Kenny Root9f306d72010-09-26 11:19:47 -070094import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.FileReader;
101import java.io.FilenameFilter;
102import java.io.IOException;
103import java.io.InputStream;
104import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800105import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
108import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700109import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Collections;
111import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800112import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.Enumeration;
114import java.util.HashMap;
115import java.util.HashSet;
116import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700117import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.List;
119import java.util.Map;
120import java.util.Set;
121import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800122import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import java.util.zip.ZipFile;
124import java.util.zip.ZipOutputStream;
125
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700126/**
127 * Keep track of all those .apks everywhere.
128 *
129 * This is very central to the platform's security; please run the unit
130 * tests whenever making modifications here:
131 *
132mmm frameworks/base/tests/AndroidTests
133adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
134adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
135 *
136 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137class PackageManagerService extends IPackageManager.Stub {
138 private static final String TAG = "PackageManager";
139 private static final boolean DEBUG_SETTINGS = false;
140 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800141 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800142 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700143 private static final boolean DEBUG_NATIVE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
145 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
146 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400147 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private static final int FIRST_APPLICATION_UID =
149 Process.FIRST_APPLICATION_UID;
150 private static final int MAX_APPLICATION_UIDS = 1000;
151
152 private static final boolean SHOW_INFO = false;
153
154 private static final boolean GET_CERTIFICATES = true;
155
Oscar Montemayora8529f62009-11-18 10:14:20 -0800156 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private static final int REMOVE_EVENTS =
159 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
160 private static final int ADD_EVENTS =
161 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
162
163 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800164 // Suffix used during package installation when copying/moving
165 // package apks to install directory.
166 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800168 /**
169 * Indicates the state of installation. Used by PackageManager to
170 * figure out incomplete installations. Say a package is being installed
171 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
172 * the package installation is successful or unsuccesful lin which case
173 * the PackageManager will no longer maintain state information associated
174 * with the package. If some exception(like device freeze or battery being
175 * pulled out) occurs during installation of a package, the PackageManager
176 * needs this information to clean up the previously failed installation.
177 */
178 private static final int PKG_INSTALL_INCOMPLETE = 0;
179 private static final int PKG_INSTALL_COMPLETE = 1;
180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final int SCAN_MONITOR = 1<<0;
182 static final int SCAN_NO_DEX = 1<<1;
183 static final int SCAN_FORCE_DEX = 1<<2;
184 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800185 static final int SCAN_NEW_INSTALL = 1<<4;
186 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700188 static final int REMOVE_CHATTY = 1<<16;
189
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800190 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
191 "com.android.defcontainer",
192 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700193
Kenny Root85387d72010-08-26 10:13:11 -0700194 private static final String LIB_DIR_NAME = "lib";
195
Kenny Rootc78a8072010-07-27 15:18:38 -0700196 static final String mTempContainerPrefix = "smdl2tmp";
197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
199 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700200 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn851a5412009-05-08 12:06:44 -0700202 final int mSdkVersion = Build.VERSION.SDK_INT;
203 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
204 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 final Context mContext;
207 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700208 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 final DisplayMetrics mMetrics;
210 final int mDefParseFlags;
211 final String[] mSeparateProcesses;
212
213 // This is where all application persistent data goes.
214 final File mAppDataDir;
215
Oscar Montemayora8529f62009-11-18 10:14:20 -0800216 // If Encrypted File System feature is enabled, all application persistent data
217 // should go here instead.
218 final File mSecureAppDataDir;
219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 // This is the object monitoring the framework dir.
221 final FileObserver mFrameworkInstallObserver;
222
223 // This is the object monitoring the system app dir.
224 final FileObserver mSystemInstallObserver;
225
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700226 // This is the object monitoring the system app dir.
227 final FileObserver mVendorInstallObserver;
228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // This is the object monitoring mAppInstallDir.
230 final FileObserver mAppInstallObserver;
231
232 // This is the object monitoring mDrmAppPrivateInstallDir.
233 final FileObserver mDrmAppInstallObserver;
234
235 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
236 // LOCK HELD. Can be called with mInstallLock held.
237 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 final File mFrameworkDir;
240 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700241 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700243 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
245 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
246 // apps.
247 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // Lock for state used when installing and doing other long running
252 // operations. Methods that must be called with this lock held have
253 // the prefix "LI".
254 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 // These are the directories in the 3rd party applications installed dir
257 // that we have currently loaded packages from. Keys are the application's
258 // installed zip file (absolute codePath), and values are Package.
259 final HashMap<String, PackageParser.Package> mAppDirs =
260 new HashMap<String, PackageParser.Package>();
261
262 // Information for the parser to write more useful error messages.
263 File mScanningPath;
264 int mLastScanError;
265
266 final int[] mOutPermissions = new int[3];
267
268 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // Keys are String (package name), values are Package. This also serves
271 // as the lock for the global state. Methods that must be called with
272 // this lock held have the prefix "LP".
273 final HashMap<String, PackageParser.Package> mPackages =
274 new HashMap<String, PackageParser.Package>();
275
276 final Settings mSettings;
277 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278
279 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
280 int[] mGlobalGids;
281
282 // These are the built-in uid -> permission mappings that were read from the
283 // etc/permissions.xml file.
284 final SparseArray<HashSet<String>> mSystemPermissions =
285 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 // These are the built-in shared libraries that were read from the
288 // etc/permissions.xml file.
289 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800290
Dianne Hackborn49237342009-08-27 20:08:01 -0700291 // Temporary for building the final shared libraries for an .apk.
292 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
Dianne Hackborn49237342009-08-27 20:08:01 -0700294 // These are the features this devices supports that were read from the
295 // etc/permissions.xml file.
296 final HashMap<String, FeatureInfo> mAvailableFeatures =
297 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 // All available activities, for your resolving pleasure.
300 final ActivityIntentResolver mActivities =
301 new ActivityIntentResolver();
302
303 // All available receivers, for your resolving pleasure.
304 final ActivityIntentResolver mReceivers =
305 new ActivityIntentResolver();
306
307 // All available services, for your resolving pleasure.
308 final ServiceIntentResolver mServices = new ServiceIntentResolver();
309
310 // Keys are String (provider class name), values are Provider.
311 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
312 new HashMap<ComponentName, PackageParser.Provider>();
313
314 // Mapping from provider base names (first directory in content URI codePath)
315 // to the provider information.
316 final HashMap<String, PackageParser.Provider> mProviders =
317 new HashMap<String, PackageParser.Provider>();
318
319 // Mapping from instrumentation class names to info about them.
320 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
321 new HashMap<ComponentName, PackageParser.Instrumentation>();
322
323 // Mapping from permission names to info about them.
324 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
325 new HashMap<String, PackageParser.PermissionGroup>();
326
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800327 // Packages whose data we have transfered into another package, thus
328 // should no longer exist.
329 final HashSet<String> mTransferedPackages = new HashSet<String>();
330
Dianne Hackborn854060af2009-07-09 18:14:31 -0700331 // Broadcast actions that are only available to the system.
332 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 boolean mSystemReady;
335 boolean mSafeMode;
336 boolean mHasSystemUidErrors;
337
338 ApplicationInfo mAndroidApplication;
339 final ActivityInfo mResolveActivity = new ActivityInfo();
340 final ResolveInfo mResolveInfo = new ResolveInfo();
341 ComponentName mResolveComponentName;
342 PackageParser.Package mPlatformPackage;
343
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700344 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800345 final HashMap<String, ArrayList<String>> mPendingBroadcasts
346 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800347 // Service Connection to remote media container service to copy
348 // package uri's from external media onto secure containers
349 // or internal storage.
350 private IMediaContainerService mContainerService = null;
351
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700352 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800353 static final int MCS_BOUND = 3;
354 static final int END_COPY = 4;
355 static final int INIT_COPY = 5;
356 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800357 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800358 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800359 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800360 static final int MCS_RECONNECT = 10;
361 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700362 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700363 static final int WRITE_SETTINGS = 13;
364
365 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800366
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700367 // Delay time in millisecs
368 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369 final private DefaultContainerConnection mDefContainerConn =
370 new DefaultContainerConnection();
371 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800372 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800373 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800374 IMediaContainerService imcs =
375 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800376 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800377 }
378
379 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800380 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800381 }
382 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700383
Christopher Tate1bb69062010-02-19 17:02:12 -0800384 // Recordkeeping of restore-after-install operations that are currently in flight
385 // between the Package Manager and the Backup Manager
386 class PostInstallData {
387 public InstallArgs args;
388 public PackageInstalledInfo res;
389
390 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
391 args = _a;
392 res = _r;
393 }
394 };
395 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
396 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
397
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700398 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800399 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800400 final ArrayList<HandlerParams> mPendingInstalls =
401 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402
403 private boolean connectToService() {
404 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
405 " DefaultContainerService");
406 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700407 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800408 if (mContext.bindService(service, mDefContainerConn,
409 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800411 mBound = true;
412 return true;
413 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800415 return false;
416 }
417
418 private void disconnectService() {
419 mContainerService = null;
420 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700421 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800422 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700423 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800424 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800425
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700426 PackageHandler(Looper looper) {
427 super(looper);
428 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700429
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700430 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700431 try {
432 doHandleMessage(msg);
433 } finally {
434 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
435 }
436 }
437
438 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700439 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800440 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800441 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800442 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800443 int idx = mPendingInstalls.size();
444 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
445 // If a bind was already initiated we dont really
446 // need to do anything. The pending install
447 // will be processed later on.
448 if (!mBound) {
449 // If this is the only one pending we might
450 // have to bind to the service again.
451 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800452 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800453 params.serviceError();
454 return;
455 } else {
456 // Once we bind to the service, the first
457 // pending request will be processed.
458 mPendingInstalls.add(idx, params);
459 }
460 } else {
461 mPendingInstalls.add(idx, params);
462 // Already bound to the service. Just make
463 // sure we trigger off processing the first request.
464 if (idx == 0) {
465 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800466 }
467 }
468 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800469 }
470 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800471 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800472 if (msg.obj != null) {
473 mContainerService = (IMediaContainerService) msg.obj;
474 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800475 if (mContainerService == null) {
476 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800477 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 for (HandlerParams params : mPendingInstalls) {
479 mPendingInstalls.remove(0);
480 // Indicate service bind error
481 params.serviceError();
482 }
483 mPendingInstalls.clear();
484 } else if (mPendingInstalls.size() > 0) {
485 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800486 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 params.startCopy();
488 }
489 } else {
490 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800491 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800492 }
493 break;
494 }
495 case MCS_RECONNECT : {
496 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
497 if (mPendingInstalls.size() > 0) {
498 if (mBound) {
499 disconnectService();
500 }
501 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800502 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800503 for (HandlerParams params : mPendingInstalls) {
504 mPendingInstalls.remove(0);
505 // Indicate service bind error
506 params.serviceError();
507 }
508 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800509 }
510 }
511 break;
512 }
513 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800514 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
515 // Delete pending install
516 if (mPendingInstalls.size() > 0) {
517 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800518 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800519 if (mPendingInstalls.size() == 0) {
520 if (mBound) {
521 disconnectService();
522 }
523 } else {
524 // There are more pending requests in queue.
525 // Just post MCS_BOUND message to trigger processing
526 // of next pending install.
527 mHandler.sendEmptyMessage(MCS_BOUND);
528 }
529 break;
530 }
531 case MCS_GIVE_UP: {
532 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
533 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800534 break;
535 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700536 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800537 String packages[];
538 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700540 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700541 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800543 if (mPendingBroadcasts == null) {
544 return;
545 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700546 size = mPendingBroadcasts.size();
547 if (size <= 0) {
548 // Nothing to be done. Just return
549 return;
550 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800551 packages = new String[size];
552 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700553 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 Iterator<HashMap.Entry<String, ArrayList<String>>>
555 it = mPendingBroadcasts.entrySet().iterator();
556 int i = 0;
557 while (it.hasNext() && i < size) {
558 HashMap.Entry<String, ArrayList<String>> ent = it.next();
559 packages[i] = ent.getKey();
560 components[i] = ent.getValue();
561 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700562 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800563 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700564 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800565 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700566 mPendingBroadcasts.clear();
567 }
568 // Send broadcasts
569 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800570 sendPackageChangedBroadcast(packages[i], true,
571 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700572 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700573 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700574 break;
575 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800576 case START_CLEANING_PACKAGE: {
577 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700578 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800579 synchronized (mPackages) {
580 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
581 mSettings.mPackagesToBeCleaned.add(packageName);
582 }
583 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700584 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800585 startCleaningPackages();
586 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800587 case POST_INSTALL: {
588 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
589 PostInstallData data = mRunningInstalls.get(msg.arg1);
590 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700591 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800592
593 if (data != null) {
594 InstallArgs args = data.args;
595 PackageInstalledInfo res = data.res;
596
597 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700598 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800599 Bundle extras = new Bundle(1);
600 extras.putInt(Intent.EXTRA_UID, res.uid);
601 final boolean update = res.removedInfo.removedPackage != null;
602 if (update) {
603 extras.putBoolean(Intent.EXTRA_REPLACING, true);
604 }
605 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
606 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700607 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800608 if (update) {
609 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
610 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700611 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800612 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700613 if (res.removedInfo.args != null) {
614 // Remove the replaced package's older resources safely now
615 deleteOld = true;
616 }
617 }
618 // Force a gc to clear up things
619 Runtime.getRuntime().gc();
620 // We delete after a gc for applications on sdcard.
621 if (deleteOld) {
622 synchronized (mInstallLock) {
623 res.removedInfo.args.doPostDeleteLI(true);
624 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800625 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800626 if (args.observer != null) {
627 try {
628 args.observer.packageInstalled(res.name, res.returnCode);
629 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800630 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800631 }
632 }
633 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800634 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800635 }
636 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700637 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700638 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
639 boolean reportStatus = msg.arg1 == 1;
640 boolean doGc = msg.arg2 == 1;
641 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
642 if (doGc) {
643 // Force a gc to clear up stale containers.
644 Runtime.getRuntime().gc();
645 }
646 if (msg.obj != null) {
647 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
648 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
649 // Unload containers
650 unloadAllContainers(args);
651 }
652 if (reportStatus) {
653 try {
654 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
655 PackageHelper.getMountService().finishMediaUpdate();
656 } catch (RemoteException e) {
657 Log.e(TAG, "MountService not running?");
658 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700659 }
660 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700661 case WRITE_SETTINGS: {
662 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
663 synchronized (mPackages) {
664 removeMessages(WRITE_SETTINGS);
665 mSettings.writeLP();
666 }
667 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
668 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700669 }
670 }
671 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800672
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700673 void scheduleWriteSettingsLocked() {
674 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
675 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
676 }
677 }
678
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800679 static boolean installOnSd(int flags) {
680 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700681 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800682 return false;
683 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700684 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
685 return true;
686 }
687 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800688 }
689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 public static final IPackageManager main(Context context, boolean factoryTest) {
691 PackageManagerService m = new PackageManagerService(context, factoryTest);
692 ServiceManager.addService("package", m);
693 return m;
694 }
695
696 static String[] splitString(String str, char sep) {
697 int count = 1;
698 int i = 0;
699 while ((i=str.indexOf(sep, i)) >= 0) {
700 count++;
701 i++;
702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 String[] res = new String[count];
705 i=0;
706 count = 0;
707 int lastI=0;
708 while ((i=str.indexOf(sep, i)) >= 0) {
709 res[count] = str.substring(lastI, i);
710 count++;
711 i++;
712 lastI = i;
713 }
714 res[count] = str.substring(lastI, str.length());
715 return res;
716 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800723 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 mContext = context;
727 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700728 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 mMetrics = new DisplayMetrics();
730 mSettings = new Settings();
731 mSettings.addSharedUserLP("android.uid.system",
732 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
733 mSettings.addSharedUserLP("android.uid.phone",
734 MULTIPLE_APPLICATION_UIDS
735 ? RADIO_UID : FIRST_APPLICATION_UID,
736 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400737 mSettings.addSharedUserLP("android.uid.log",
738 MULTIPLE_APPLICATION_UIDS
739 ? LOG_UID : FIRST_APPLICATION_UID,
740 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741
742 String separateProcesses = SystemProperties.get("debug.separate_processes");
743 if (separateProcesses != null && separateProcesses.length() > 0) {
744 if ("*".equals(separateProcesses)) {
745 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
746 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800747 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 } else {
749 mDefParseFlags = 0;
750 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800751 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 + separateProcesses);
753 }
754 } else {
755 mDefParseFlags = 0;
756 mSeparateProcesses = null;
757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 Installer installer = new Installer();
760 // Little hacky thing to check if installd is here, to determine
761 // whether we are running on the simulator and thus need to take
762 // care of building the /data file structure ourself.
763 // (apparently the sim now has a working installer)
764 if (installer.ping() && Process.supportsProcesses()) {
765 mInstaller = installer;
766 } else {
767 mInstaller = null;
768 }
769
770 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
771 Display d = wm.getDefaultDisplay();
772 d.getMetrics(mMetrics);
773
774 synchronized (mInstallLock) {
775 synchronized (mPackages) {
776 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700777 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 File dataDir = Environment.getDataDirectory();
780 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800781 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
783
784 if (mInstaller == null) {
785 // Make sure these dirs exist, when we are running in
786 // the simulator.
787 // Make a wide-open directory for random misc stuff.
788 File miscDir = new File(dataDir, "misc");
789 miscDir.mkdirs();
790 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800791 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 mDrmAppPrivateInstallDir.mkdirs();
793 }
794
795 readPermissions();
796
797 mRestoredSettings = mSettings.readLP();
798 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800799
800 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800802
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800803 // Set flag to monitor and not change apk file paths when
804 // scanning install directories.
805 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700806 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800807 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800808 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700814 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700817 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 /**
820 * Out of paranoia, ensure that everything in the boot class
821 * path has been dexed.
822 */
823 String bootClassPath = System.getProperty("java.boot.class.path");
824 if (bootClassPath != null) {
825 String[] paths = splitString(bootClassPath, ':');
826 for (int i=0; i<paths.length; i++) {
827 try {
828 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
829 libFiles.add(paths[i]);
830 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700831 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800834 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800836 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 }
838 }
839 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800840 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 /**
844 * Also ensure all external libraries have had dexopt run on them.
845 */
846 if (mSharedLibraries.size() > 0) {
847 Iterator<String> libs = mSharedLibraries.values().iterator();
848 while (libs.hasNext()) {
849 String lib = libs.next();
850 try {
851 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
852 libFiles.add(lib);
853 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700854 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800857 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800859 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
861 }
862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 // Gross hack for now: we know this file doesn't contain any
865 // code, so don't dexopt it to avoid the resulting log spew.
866 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 /**
869 * And there are a number of commands implemented in Java, which
870 * we currently need to do the dexopt on so that they can be
871 * run from a non-root shell.
872 */
873 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700874 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 for (int i=0; i<frameworkFiles.length; i++) {
876 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
877 String path = libPath.getPath();
878 // Skip the file if we alrady did it.
879 if (libFiles.contains(path)) {
880 continue;
881 }
882 // Skip the file if it is not a type we want to dexopt.
883 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
884 continue;
885 }
886 try {
887 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
888 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700889 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
891 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800892 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800894 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
896 }
897 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800898
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700899 if (didDexOpt) {
900 // If we had to do a dexopt of one of the previous
901 // things, then something on the system has changed.
902 // Consider this significant, and wipe away all other
903 // existing dexopt files to ensure we don't leave any
904 // dangling around.
905 String[] files = mDalvikCacheDir.list();
906 if (files != null) {
907 for (int i=0; i<files.length; i++) {
908 String fn = files[i];
909 if (fn.startsWith("data@app@")
910 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800911 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700912 (new File(mDalvikCacheDir, fn)).delete();
913 }
914 }
915 }
916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800918
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800919 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 mFrameworkInstallObserver = new AppDirObserver(
921 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
922 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700923 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
924 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800925 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800926
927 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
929 mSystemInstallObserver = new AppDirObserver(
930 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
931 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700932 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
933 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800934
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700935 // Collect all vendor packages.
936 mVendorAppDir = new File("/vendor/app");
937 mVendorInstallObserver = new AppDirObserver(
938 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
939 mVendorInstallObserver.startWatching();
940 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
941 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
942
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800943 if (mInstaller != null) {
944 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
945 mInstaller.moveFiles();
946 }
947
948 // Prune any system packages that no longer exist.
949 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
950 while (psit.hasNext()) {
951 PackageSetting ps = psit.next();
952 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800953 && !mPackages.containsKey(ps.name)
954 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800955 psit.remove();
956 String msg = "System package " + ps.name
957 + " no longer exists; wiping its data";
958 reportSettingsProblem(Log.WARN, msg);
959 if (mInstaller != null) {
960 // XXX how to set useEncryptedFSDir for packages that
961 // are not encrypted?
962 mInstaller.remove(ps.name, true);
963 }
964 }
965 }
966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 mAppInstallDir = new File(dataDir, "app");
968 if (mInstaller == null) {
969 // Make sure these dirs exist, when we are running in
970 // the simulator.
971 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
972 }
973 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800974 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 //clean up list
976 for(int i = 0; i < deletePkgsList.size(); i++) {
977 //clean up here
978 cleanupInstallFailedPackage(deletePkgsList.get(i));
979 }
980 //delete tmp files
981 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982
983 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 SystemClock.uptimeMillis());
985 mAppInstallObserver = new AppDirObserver(
986 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
987 mAppInstallObserver.startWatching();
988 scanDirLI(mAppInstallDir, 0, scanMode);
989
990 mDrmAppInstallObserver = new AppDirObserver(
991 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
992 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800993 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800995 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800997 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 + ((SystemClock.uptimeMillis()-startTime)/1000f)
999 + " seconds");
1000
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001001 // If the platform SDK has changed since the last time we booted,
1002 // we need to re-grant app permission to catch any new ones that
1003 // appear. This is really a hack, and means that apps can in some
1004 // cases get permissions that the user didn't initially explicitly
1005 // allow... it would be nice to have some better way to handle
1006 // this situation.
1007 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1008 != mSdkVersion;
1009 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1010 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1011 + "; regranting permissions for internal storage");
1012 mSettings.mInternalSdkPlatform = mSdkVersion;
1013
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001014 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015
1016 mSettings.writeLP();
1017
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001018 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 // Now after opening every single application zip, make sure they
1022 // are all flushed. Not really needed, but keeps things nice and
1023 // tidy.
1024 Runtime.getRuntime().gc();
1025 } // synchronized (mPackages)
1026 } // synchronized (mInstallLock)
1027 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 @Override
1030 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1031 throws RemoteException {
1032 try {
1033 return super.onTransact(code, data, reply, flags);
1034 } catch (RuntimeException e) {
1035 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001036 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038 throw e;
1039 }
1040 }
1041
Dianne Hackborne6620b22010-01-22 14:46:21 -08001042 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001043 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001045 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1046 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001048 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001049 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051 } else {
1052 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001053 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 File dataDir = new File(pkg.applicationInfo.dataDir);
1055 dataDir.delete();
1056 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001057 if (ps.codePath != null) {
1058 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001059 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001060 }
1061 }
1062 if (ps.resourcePath != null) {
1063 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001064 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001065 }
1066 }
1067 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069
1070 void readPermissions() {
1071 // Read permissions from .../etc/permission directory.
1072 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1073 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001074 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 return;
1076 }
1077 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001078 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 return;
1080 }
1081
1082 // Iterate over the files in the directory and scan .xml files
1083 for (File f : libraryDir.listFiles()) {
1084 // We'll read platform.xml last
1085 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1086 continue;
1087 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001089 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001090 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 continue;
1092 }
1093 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001094 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 continue;
1096 }
1097
1098 readPermissionsFromXml(f);
1099 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001100
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1102 final File permFile = new File(Environment.getRootDirectory(),
1103 "etc/permissions/platform.xml");
1104 readPermissionsFromXml(permFile);
1105 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001106
1107 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 FileReader permReader = null;
1109 try {
1110 permReader = new FileReader(permFile);
1111 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001112 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 return;
1114 }
1115
1116 try {
1117 XmlPullParser parser = Xml.newPullParser();
1118 parser.setInput(permReader);
1119
1120 XmlUtils.beginDocument(parser, "permissions");
1121
1122 while (true) {
1123 XmlUtils.nextElement(parser);
1124 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1125 break;
1126 }
1127
1128 String name = parser.getName();
1129 if ("group".equals(name)) {
1130 String gidStr = parser.getAttributeValue(null, "gid");
1131 if (gidStr != null) {
1132 int gid = Integer.parseInt(gidStr);
1133 mGlobalGids = appendInt(mGlobalGids, gid);
1134 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001135 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001136 + parser.getPositionDescription());
1137 }
1138
1139 XmlUtils.skipCurrentTag(parser);
1140 continue;
1141 } else if ("permission".equals(name)) {
1142 String perm = parser.getAttributeValue(null, "name");
1143 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001144 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 + parser.getPositionDescription());
1146 XmlUtils.skipCurrentTag(parser);
1147 continue;
1148 }
1149 perm = perm.intern();
1150 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 } else if ("assign-permission".equals(name)) {
1153 String perm = parser.getAttributeValue(null, "name");
1154 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001155 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 + parser.getPositionDescription());
1157 XmlUtils.skipCurrentTag(parser);
1158 continue;
1159 }
1160 String uidStr = parser.getAttributeValue(null, "uid");
1161 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001162 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 + parser.getPositionDescription());
1164 XmlUtils.skipCurrentTag(parser);
1165 continue;
1166 }
1167 int uid = Process.getUidForName(uidStr);
1168 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001169 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 + uidStr + "\" at "
1171 + parser.getPositionDescription());
1172 XmlUtils.skipCurrentTag(parser);
1173 continue;
1174 }
1175 perm = perm.intern();
1176 HashSet<String> perms = mSystemPermissions.get(uid);
1177 if (perms == null) {
1178 perms = new HashSet<String>();
1179 mSystemPermissions.put(uid, perms);
1180 }
1181 perms.add(perm);
1182 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 } else if ("library".equals(name)) {
1185 String lname = parser.getAttributeValue(null, "name");
1186 String lfile = parser.getAttributeValue(null, "file");
1187 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001188 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 + parser.getPositionDescription());
1190 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001191 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 + parser.getPositionDescription());
1193 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001194 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001195 mSharedLibraries.put(lname, lfile);
1196 }
1197 XmlUtils.skipCurrentTag(parser);
1198 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001199
Dianne Hackborn49237342009-08-27 20:08:01 -07001200 } else if ("feature".equals(name)) {
1201 String fname = parser.getAttributeValue(null, "name");
1202 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001203 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001204 + parser.getPositionDescription());
1205 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001206 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001207 FeatureInfo fi = new FeatureInfo();
1208 fi.name = fname;
1209 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211 XmlUtils.skipCurrentTag(parser);
1212 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001213
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 } else {
1215 XmlUtils.skipCurrentTag(parser);
1216 continue;
1217 }
1218
1219 }
1220 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001221 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001223 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
1225 }
1226
1227 void readPermission(XmlPullParser parser, String name)
1228 throws IOException, XmlPullParserException {
1229
1230 name = name.intern();
1231
1232 BasePermission bp = mSettings.mPermissions.get(name);
1233 if (bp == null) {
1234 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1235 mSettings.mPermissions.put(name, bp);
1236 }
1237 int outerDepth = parser.getDepth();
1238 int type;
1239 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1240 && (type != XmlPullParser.END_TAG
1241 || parser.getDepth() > outerDepth)) {
1242 if (type == XmlPullParser.END_TAG
1243 || type == XmlPullParser.TEXT) {
1244 continue;
1245 }
1246
1247 String tagName = parser.getName();
1248 if ("group".equals(tagName)) {
1249 String gidStr = parser.getAttributeValue(null, "gid");
1250 if (gidStr != null) {
1251 int gid = Process.getGidForName(gidStr);
1252 bp.gids = appendInt(bp.gids, gid);
1253 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001254 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 + parser.getPositionDescription());
1256 }
1257 }
1258 XmlUtils.skipCurrentTag(parser);
1259 }
1260 }
1261
1262 static int[] appendInt(int[] cur, int val) {
1263 if (cur == null) {
1264 return new int[] { val };
1265 }
1266 final int N = cur.length;
1267 for (int i=0; i<N; i++) {
1268 if (cur[i] == val) {
1269 return cur;
1270 }
1271 }
1272 int[] ret = new int[N+1];
1273 System.arraycopy(cur, 0, ret, 0, N);
1274 ret[N] = val;
1275 return ret;
1276 }
1277
1278 static int[] appendInts(int[] cur, int[] add) {
1279 if (add == null) return cur;
1280 if (cur == null) return add;
1281 final int N = add.length;
1282 for (int i=0; i<N; i++) {
1283 cur = appendInt(cur, add[i]);
1284 }
1285 return cur;
1286 }
1287
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001288 static int[] removeInt(int[] cur, int val) {
1289 if (cur == null) {
1290 return null;
1291 }
1292 final int N = cur.length;
1293 for (int i=0; i<N; i++) {
1294 if (cur[i] == val) {
1295 int[] ret = new int[N-1];
1296 if (i > 0) {
1297 System.arraycopy(cur, 0, ret, 0, i);
1298 }
1299 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001300 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001301 }
1302 return ret;
1303 }
1304 }
1305 return cur;
1306 }
1307
1308 static int[] removeInts(int[] cur, int[] rem) {
1309 if (rem == null) return cur;
1310 if (cur == null) return cur;
1311 final int N = rem.length;
1312 for (int i=0; i<N; i++) {
1313 cur = removeInt(cur, rem[i]);
1314 }
1315 return cur;
1316 }
1317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001319 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1320 // The package has been uninstalled but has retained data and resources.
1321 return PackageParser.generatePackageInfo(p, null, flags);
1322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 final PackageSetting ps = (PackageSetting)p.mExtras;
1324 if (ps == null) {
1325 return null;
1326 }
1327 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1328 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1329 }
1330
1331 public PackageInfo getPackageInfo(String packageName, int flags) {
1332 synchronized (mPackages) {
1333 PackageParser.Package p = mPackages.get(packageName);
1334 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001335 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 + ": " + p);
1337 if (p != null) {
1338 return generatePackageInfo(p, flags);
1339 }
1340 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1341 return generatePackageInfoFromSettingsLP(packageName, flags);
1342 }
1343 }
1344 return null;
1345 }
1346
Dianne Hackborn47096932010-02-11 15:57:09 -08001347 public String[] currentToCanonicalPackageNames(String[] names) {
1348 String[] out = new String[names.length];
1349 synchronized (mPackages) {
1350 for (int i=names.length-1; i>=0; i--) {
1351 PackageSetting ps = mSettings.mPackages.get(names[i]);
1352 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1353 }
1354 }
1355 return out;
1356 }
1357
1358 public String[] canonicalToCurrentPackageNames(String[] names) {
1359 String[] out = new String[names.length];
1360 synchronized (mPackages) {
1361 for (int i=names.length-1; i>=0; i--) {
1362 String cur = mSettings.mRenamedPackages.get(names[i]);
1363 out[i] = cur != null ? cur : names[i];
1364 }
1365 }
1366 return out;
1367 }
1368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 public int getPackageUid(String packageName) {
1370 synchronized (mPackages) {
1371 PackageParser.Package p = mPackages.get(packageName);
1372 if(p != null) {
1373 return p.applicationInfo.uid;
1374 }
1375 PackageSetting ps = mSettings.mPackages.get(packageName);
1376 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1377 return -1;
1378 }
1379 p = ps.pkg;
1380 return p != null ? p.applicationInfo.uid : -1;
1381 }
1382 }
1383
1384 public int[] getPackageGids(String packageName) {
1385 synchronized (mPackages) {
1386 PackageParser.Package p = mPackages.get(packageName);
1387 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001388 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 + ": " + p);
1390 if (p != null) {
1391 final PackageSetting ps = (PackageSetting)p.mExtras;
1392 final SharedUserSetting suid = ps.sharedUser;
1393 return suid != null ? suid.gids : ps.gids;
1394 }
1395 }
1396 // stupid thing to indicate an error.
1397 return new int[0];
1398 }
1399
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001400 static final PermissionInfo generatePermissionInfo(
1401 BasePermission bp, int flags) {
1402 if (bp.perm != null) {
1403 return PackageParser.generatePermissionInfo(bp.perm, flags);
1404 }
1405 PermissionInfo pi = new PermissionInfo();
1406 pi.name = bp.name;
1407 pi.packageName = bp.sourcePackage;
1408 pi.nonLocalizedLabel = bp.name;
1409 pi.protectionLevel = bp.protectionLevel;
1410 return pi;
1411 }
1412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 public PermissionInfo getPermissionInfo(String name, int flags) {
1414 synchronized (mPackages) {
1415 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001416 if (p != null) {
1417 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419 return null;
1420 }
1421 }
1422
1423 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1424 synchronized (mPackages) {
1425 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1426 for (BasePermission p : mSettings.mPermissions.values()) {
1427 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001428 if (p.perm == null || p.perm.info.group == null) {
1429 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 }
1431 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001432 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1434 }
1435 }
1436 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 if (out.size() > 0) {
1439 return out;
1440 }
1441 return mPermissionGroups.containsKey(group) ? out : null;
1442 }
1443 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1446 synchronized (mPackages) {
1447 return PackageParser.generatePermissionGroupInfo(
1448 mPermissionGroups.get(name), flags);
1449 }
1450 }
1451
1452 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1453 synchronized (mPackages) {
1454 final int N = mPermissionGroups.size();
1455 ArrayList<PermissionGroupInfo> out
1456 = new ArrayList<PermissionGroupInfo>(N);
1457 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1458 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1459 }
1460 return out;
1461 }
1462 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1465 PackageSetting ps = mSettings.mPackages.get(packageName);
1466 if(ps != null) {
1467 if(ps.pkg == null) {
1468 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1469 if(pInfo != null) {
1470 return pInfo.applicationInfo;
1471 }
1472 return null;
1473 }
1474 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1475 }
1476 return null;
1477 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001479 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1480 PackageSetting ps = mSettings.mPackages.get(packageName);
1481 if(ps != null) {
1482 if(ps.pkg == null) {
1483 ps.pkg = new PackageParser.Package(packageName);
1484 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001485 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1486 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1487 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1488 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001489 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001490 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492 return generatePackageInfo(ps.pkg, flags);
1493 }
1494 return null;
1495 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1498 synchronized (mPackages) {
1499 PackageParser.Package p = mPackages.get(packageName);
1500 if (Config.LOGV) Log.v(
1501 TAG, "getApplicationInfo " + packageName
1502 + ": " + p);
1503 if (p != null) {
1504 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001505 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507 if ("android".equals(packageName)||"system".equals(packageName)) {
1508 return mAndroidApplication;
1509 }
1510 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1511 return generateApplicationInfoFromSettingsLP(packageName, flags);
1512 }
1513 }
1514 return null;
1515 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001516
1517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1519 mContext.enforceCallingOrSelfPermission(
1520 android.Manifest.permission.CLEAR_APP_CACHE, null);
1521 // Queue up an async operation since clearing cache may take a little while.
1522 mHandler.post(new Runnable() {
1523 public void run() {
1524 mHandler.removeCallbacks(this);
1525 int retCode = -1;
1526 if (mInstaller != null) {
1527 retCode = mInstaller.freeCache(freeStorageSize);
1528 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001529 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
1531 } //end if mInstaller
1532 if (observer != null) {
1533 try {
1534 observer.onRemoveCompleted(null, (retCode >= 0));
1535 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001536 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538 }
1539 }
1540 });
1541 }
1542
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001543 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001544 mContext.enforceCallingOrSelfPermission(
1545 android.Manifest.permission.CLEAR_APP_CACHE, null);
1546 // Queue up an async operation since clearing cache may take a little while.
1547 mHandler.post(new Runnable() {
1548 public void run() {
1549 mHandler.removeCallbacks(this);
1550 int retCode = -1;
1551 if (mInstaller != null) {
1552 retCode = mInstaller.freeCache(freeStorageSize);
1553 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001554 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001555 }
1556 }
1557 if(pi != null) {
1558 try {
1559 // Callback via pending intent
1560 int code = (retCode >= 0) ? 1 : 0;
1561 pi.sendIntent(null, code, null,
1562 null, null);
1563 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001564 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001565 }
1566 }
1567 }
1568 });
1569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1572 synchronized (mPackages) {
1573 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001574
1575 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001577 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
1579 if (mResolveComponentName.equals(component)) {
1580 return mResolveActivity;
1581 }
1582 }
1583 return null;
1584 }
1585
1586 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1587 synchronized (mPackages) {
1588 PackageParser.Activity a = mReceivers.mActivities.get(component);
1589 if (Config.LOGV) Log.v(
1590 TAG, "getReceiverInfo " + component + ": " + a);
1591 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1592 return PackageParser.generateActivityInfo(a, flags);
1593 }
1594 }
1595 return null;
1596 }
1597
1598 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1599 synchronized (mPackages) {
1600 PackageParser.Service s = mServices.mServices.get(component);
1601 if (Config.LOGV) Log.v(
1602 TAG, "getServiceInfo " + component + ": " + s);
1603 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1604 return PackageParser.generateServiceInfo(s, flags);
1605 }
1606 }
1607 return null;
1608 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001609
Dianne Hackborn361199b2010-08-30 17:42:07 -07001610 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1611 synchronized (mPackages) {
1612 PackageParser.Provider p = mProvidersByComponent.get(component);
1613 if (Config.LOGV) Log.v(
1614 TAG, "getProviderInfo " + component + ": " + p);
1615 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1616 return PackageParser.generateProviderInfo(p, flags);
1617 }
1618 }
1619 return null;
1620 }
1621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 public String[] getSystemSharedLibraryNames() {
1623 Set<String> libSet;
1624 synchronized (mPackages) {
1625 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001626 int size = libSet.size();
1627 if (size > 0) {
1628 String[] libs = new String[size];
1629 libSet.toArray(libs);
1630 return libs;
1631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001633 return null;
1634 }
1635
1636 public FeatureInfo[] getSystemAvailableFeatures() {
1637 Collection<FeatureInfo> featSet;
1638 synchronized (mPackages) {
1639 featSet = mAvailableFeatures.values();
1640 int size = featSet.size();
1641 if (size > 0) {
1642 FeatureInfo[] features = new FeatureInfo[size+1];
1643 featSet.toArray(features);
1644 FeatureInfo fi = new FeatureInfo();
1645 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1646 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1647 features[size] = fi;
1648 return features;
1649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001650 }
1651 return null;
1652 }
1653
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001654 public boolean hasSystemFeature(String name) {
1655 synchronized (mPackages) {
1656 return mAvailableFeatures.containsKey(name);
1657 }
1658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 public int checkPermission(String permName, String pkgName) {
1661 synchronized (mPackages) {
1662 PackageParser.Package p = mPackages.get(pkgName);
1663 if (p != null && p.mExtras != null) {
1664 PackageSetting ps = (PackageSetting)p.mExtras;
1665 if (ps.sharedUser != null) {
1666 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1667 return PackageManager.PERMISSION_GRANTED;
1668 }
1669 } else if (ps.grantedPermissions.contains(permName)) {
1670 return PackageManager.PERMISSION_GRANTED;
1671 }
1672 }
1673 }
1674 return PackageManager.PERMISSION_DENIED;
1675 }
1676
1677 public int checkUidPermission(String permName, int uid) {
1678 synchronized (mPackages) {
1679 Object obj = mSettings.getUserIdLP(uid);
1680 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001681 GrantedPermissions gp = (GrantedPermissions)obj;
1682 if (gp.grantedPermissions.contains(permName)) {
1683 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
1685 } else {
1686 HashSet<String> perms = mSystemPermissions.get(uid);
1687 if (perms != null && perms.contains(permName)) {
1688 return PackageManager.PERMISSION_GRANTED;
1689 }
1690 }
1691 }
1692 return PackageManager.PERMISSION_DENIED;
1693 }
1694
1695 private BasePermission findPermissionTreeLP(String permName) {
1696 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1697 if (permName.startsWith(bp.name) &&
1698 permName.length() > bp.name.length() &&
1699 permName.charAt(bp.name.length()) == '.') {
1700 return bp;
1701 }
1702 }
1703 return null;
1704 }
1705
1706 private BasePermission checkPermissionTreeLP(String permName) {
1707 if (permName != null) {
1708 BasePermission bp = findPermissionTreeLP(permName);
1709 if (bp != null) {
1710 if (bp.uid == Binder.getCallingUid()) {
1711 return bp;
1712 }
1713 throw new SecurityException("Calling uid "
1714 + Binder.getCallingUid()
1715 + " is not allowed to add to permission tree "
1716 + bp.name + " owned by uid " + bp.uid);
1717 }
1718 }
1719 throw new SecurityException("No permission tree found for " + permName);
1720 }
1721
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001722 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1723 if (s1 == null) {
1724 return s2 == null;
1725 }
1726 if (s2 == null) {
1727 return false;
1728 }
1729 if (s1.getClass() != s2.getClass()) {
1730 return false;
1731 }
1732 return s1.equals(s2);
1733 }
1734
1735 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1736 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001737 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001738 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1739 if (!compareStrings(pi1.name, pi2.name)) return false;
1740 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1741 // We'll take care of setting this one.
1742 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1743 // These are not currently stored in settings.
1744 //if (!compareStrings(pi1.group, pi2.group)) return false;
1745 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1746 //if (pi1.labelRes != pi2.labelRes) return false;
1747 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1748 return true;
1749 }
1750
1751 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1752 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1753 throw new SecurityException("Label must be specified in permission");
1754 }
1755 BasePermission tree = checkPermissionTreeLP(info.name);
1756 BasePermission bp = mSettings.mPermissions.get(info.name);
1757 boolean added = bp == null;
1758 boolean changed = true;
1759 if (added) {
1760 bp = new BasePermission(info.name, tree.sourcePackage,
1761 BasePermission.TYPE_DYNAMIC);
1762 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1763 throw new SecurityException(
1764 "Not allowed to modify non-dynamic permission "
1765 + info.name);
1766 } else {
1767 if (bp.protectionLevel == info.protectionLevel
1768 && bp.perm.owner.equals(tree.perm.owner)
1769 && bp.uid == tree.uid
1770 && comparePermissionInfos(bp.perm.info, info)) {
1771 changed = false;
1772 }
1773 }
1774 bp.protectionLevel = info.protectionLevel;
1775 bp.perm = new PackageParser.Permission(tree.perm.owner,
1776 new PermissionInfo(info));
1777 bp.perm.info.packageName = tree.perm.info.packageName;
1778 bp.uid = tree.uid;
1779 if (added) {
1780 mSettings.mPermissions.put(info.name, bp);
1781 }
1782 if (changed) {
1783 if (!async) {
1784 mSettings.writeLP();
1785 } else {
1786 scheduleWriteSettingsLocked();
1787 }
1788 }
1789 return added;
1790 }
1791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 public boolean addPermission(PermissionInfo info) {
1793 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001794 return addPermissionLocked(info, false);
1795 }
1796 }
1797
1798 public boolean addPermissionAsync(PermissionInfo info) {
1799 synchronized (mPackages) {
1800 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801 }
1802 }
1803
1804 public void removePermission(String name) {
1805 synchronized (mPackages) {
1806 checkPermissionTreeLP(name);
1807 BasePermission bp = mSettings.mPermissions.get(name);
1808 if (bp != null) {
1809 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1810 throw new SecurityException(
1811 "Not allowed to modify non-dynamic permission "
1812 + name);
1813 }
1814 mSettings.mPermissions.remove(name);
1815 mSettings.writeLP();
1816 }
1817 }
1818 }
1819
Dianne Hackborn854060af2009-07-09 18:14:31 -07001820 public boolean isProtectedBroadcast(String actionName) {
1821 synchronized (mPackages) {
1822 return mProtectedBroadcasts.contains(actionName);
1823 }
1824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 public int checkSignatures(String pkg1, String pkg2) {
1827 synchronized (mPackages) {
1828 PackageParser.Package p1 = mPackages.get(pkg1);
1829 PackageParser.Package p2 = mPackages.get(pkg2);
1830 if (p1 == null || p1.mExtras == null
1831 || p2 == null || p2.mExtras == null) {
1832 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1833 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001834 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836 }
1837
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001838 public int checkUidSignatures(int uid1, int uid2) {
1839 synchronized (mPackages) {
1840 Signature[] s1;
1841 Signature[] s2;
1842 Object obj = mSettings.getUserIdLP(uid1);
1843 if (obj != null) {
1844 if (obj instanceof SharedUserSetting) {
1845 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1846 } else if (obj instanceof PackageSetting) {
1847 s1 = ((PackageSetting)obj).signatures.mSignatures;
1848 } else {
1849 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1850 }
1851 } else {
1852 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1853 }
1854 obj = mSettings.getUserIdLP(uid2);
1855 if (obj != null) {
1856 if (obj instanceof SharedUserSetting) {
1857 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1858 } else if (obj instanceof PackageSetting) {
1859 s2 = ((PackageSetting)obj).signatures.mSignatures;
1860 } else {
1861 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1862 }
1863 } else {
1864 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1865 }
1866 return checkSignaturesLP(s1, s2);
1867 }
1868 }
1869
1870 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1871 if (s1 == null) {
1872 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1874 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1875 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001876 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1878 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001879 HashSet<Signature> set1 = new HashSet<Signature>();
1880 for (Signature sig : s1) {
1881 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001883 HashSet<Signature> set2 = new HashSet<Signature>();
1884 for (Signature sig : s2) {
1885 set2.add(sig);
1886 }
1887 // Make sure s2 contains all signatures in s1.
1888 if (set1.equals(set2)) {
1889 return PackageManager.SIGNATURE_MATCH;
1890 }
1891 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893
1894 public String[] getPackagesForUid(int uid) {
1895 synchronized (mPackages) {
1896 Object obj = mSettings.getUserIdLP(uid);
1897 if (obj instanceof SharedUserSetting) {
1898 SharedUserSetting sus = (SharedUserSetting)obj;
1899 final int N = sus.packages.size();
1900 String[] res = new String[N];
1901 Iterator<PackageSetting> it = sus.packages.iterator();
1902 int i=0;
1903 while (it.hasNext()) {
1904 res[i++] = it.next().name;
1905 }
1906 return res;
1907 } else if (obj instanceof PackageSetting) {
1908 PackageSetting ps = (PackageSetting)obj;
1909 return new String[] { ps.name };
1910 }
1911 }
1912 return null;
1913 }
1914
1915 public String getNameForUid(int uid) {
1916 synchronized (mPackages) {
1917 Object obj = mSettings.getUserIdLP(uid);
1918 if (obj instanceof SharedUserSetting) {
1919 SharedUserSetting sus = (SharedUserSetting)obj;
1920 return sus.name + ":" + sus.userId;
1921 } else if (obj instanceof PackageSetting) {
1922 PackageSetting ps = (PackageSetting)obj;
1923 return ps.name;
1924 }
1925 }
1926 return null;
1927 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001929 public int getUidForSharedUser(String sharedUserName) {
1930 if(sharedUserName == null) {
1931 return -1;
1932 }
1933 synchronized (mPackages) {
1934 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1935 if(suid == null) {
1936 return -1;
1937 }
1938 return suid.userId;
1939 }
1940 }
1941
1942 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1943 int flags) {
1944 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001945 return chooseBestActivity(intent, resolvedType, flags, query);
1946 }
1947
Mihai Predaeae850c2009-05-13 10:13:48 +02001948 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1949 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001950 if (query != null) {
1951 final int N = query.size();
1952 if (N == 1) {
1953 return query.get(0);
1954 } else if (N > 1) {
1955 // If there is more than one activity with the same priority,
1956 // then let the user decide between them.
1957 ResolveInfo r0 = query.get(0);
1958 ResolveInfo r1 = query.get(1);
1959 if (false) {
1960 System.out.println(r0.activityInfo.name +
1961 "=" + r0.priority + " vs " +
1962 r1.activityInfo.name +
1963 "=" + r1.priority);
1964 }
1965 // If the first activity has a higher priority, or a different
1966 // default, then it is always desireable to pick it.
1967 if (r0.priority != r1.priority
1968 || r0.preferredOrder != r1.preferredOrder
1969 || r0.isDefault != r1.isDefault) {
1970 return query.get(0);
1971 }
1972 // If we have saved a preference for a preferred activity for
1973 // this Intent, use that.
1974 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1975 flags, query, r0.priority);
1976 if (ri != null) {
1977 return ri;
1978 }
1979 return mResolveInfo;
1980 }
1981 }
1982 return null;
1983 }
1984
1985 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1986 int flags, List<ResolveInfo> query, int priority) {
1987 synchronized (mPackages) {
1988 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1989 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001990 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1992 if (prefs != null && prefs.size() > 0) {
1993 // First figure out how good the original match set is.
1994 // We will only allow preferred activities that came
1995 // from the same match quality.
1996 int match = 0;
1997 final int N = query.size();
1998 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1999 for (int j=0; j<N; j++) {
2000 ResolveInfo ri = query.get(j);
2001 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2002 + ": 0x" + Integer.toHexString(match));
2003 if (ri.match > match) match = ri.match;
2004 }
2005 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2006 + Integer.toHexString(match));
2007 match &= IntentFilter.MATCH_CATEGORY_MASK;
2008 final int M = prefs.size();
2009 for (int i=0; i<M; i++) {
2010 PreferredActivity pa = prefs.get(i);
2011 if (pa.mMatch != match) {
2012 continue;
2013 }
2014 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2015 if (DEBUG_PREFERRED) {
2016 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002017 if (ai != null) {
2018 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2019 } else {
2020 Log.v(TAG, " null");
2021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 }
2023 if (ai != null) {
2024 for (int j=0; j<N; j++) {
2025 ResolveInfo ri = query.get(j);
2026 if (!ri.activityInfo.applicationInfo.packageName
2027 .equals(ai.applicationInfo.packageName)) {
2028 continue;
2029 }
2030 if (!ri.activityInfo.name.equals(ai.name)) {
2031 continue;
2032 }
2033
2034 // Okay we found a previously set preferred app.
2035 // If the result set is different from when this
2036 // was created, we need to clear it and re-ask the
2037 // user their preference.
2038 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002039 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002040 + intent + " type " + resolvedType);
2041 mSettings.mPreferredActivities.removeFilter(pa);
2042 return null;
2043 }
2044
2045 // Yay!
2046 return ri;
2047 }
2048 }
2049 }
2050 }
2051 }
2052 return null;
2053 }
2054
2055 public List<ResolveInfo> queryIntentActivities(Intent intent,
2056 String resolvedType, int flags) {
2057 ComponentName comp = intent.getComponent();
2058 if (comp != null) {
2059 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2060 ActivityInfo ai = getActivityInfo(comp, flags);
2061 if (ai != null) {
2062 ResolveInfo ri = new ResolveInfo();
2063 ri.activityInfo = ai;
2064 list.add(ri);
2065 }
2066 return list;
2067 }
2068
2069 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002070 String pkgName = intent.getPackage();
2071 if (pkgName == null) {
2072 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2073 resolvedType, flags);
2074 }
2075 PackageParser.Package pkg = mPackages.get(pkgName);
2076 if (pkg != null) {
2077 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2078 resolvedType, flags, pkg.activities);
2079 }
2080 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 }
2082 }
2083
2084 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2085 Intent[] specifics, String[] specificTypes, Intent intent,
2086 String resolvedType, int flags) {
2087 final String resultsAction = intent.getAction();
2088
2089 List<ResolveInfo> results = queryIntentActivities(
2090 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2091 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2092
2093 int specificsPos = 0;
2094 int N;
2095
2096 // todo: note that the algorithm used here is O(N^2). This
2097 // isn't a problem in our current environment, but if we start running
2098 // into situations where we have more than 5 or 10 matches then this
2099 // should probably be changed to something smarter...
2100
2101 // First we go through and resolve each of the specific items
2102 // that were supplied, taking care of removing any corresponding
2103 // duplicate items in the generic resolve list.
2104 if (specifics != null) {
2105 for (int i=0; i<specifics.length; i++) {
2106 final Intent sintent = specifics[i];
2107 if (sintent == null) {
2108 continue;
2109 }
2110
2111 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2112 String action = sintent.getAction();
2113 if (resultsAction != null && resultsAction.equals(action)) {
2114 // If this action was explicitly requested, then don't
2115 // remove things that have it.
2116 action = null;
2117 }
2118 ComponentName comp = sintent.getComponent();
2119 ResolveInfo ri = null;
2120 ActivityInfo ai = null;
2121 if (comp == null) {
2122 ri = resolveIntent(
2123 sintent,
2124 specificTypes != null ? specificTypes[i] : null,
2125 flags);
2126 if (ri == null) {
2127 continue;
2128 }
2129 if (ri == mResolveInfo) {
2130 // ACK! Must do something better with this.
2131 }
2132 ai = ri.activityInfo;
2133 comp = new ComponentName(ai.applicationInfo.packageName,
2134 ai.name);
2135 } else {
2136 ai = getActivityInfo(comp, flags);
2137 if (ai == null) {
2138 continue;
2139 }
2140 }
2141
2142 // Look for any generic query activities that are duplicates
2143 // of this specific one, and remove them from the results.
2144 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2145 N = results.size();
2146 int j;
2147 for (j=specificsPos; j<N; j++) {
2148 ResolveInfo sri = results.get(j);
2149 if ((sri.activityInfo.name.equals(comp.getClassName())
2150 && sri.activityInfo.applicationInfo.packageName.equals(
2151 comp.getPackageName()))
2152 || (action != null && sri.filter.matchAction(action))) {
2153 results.remove(j);
2154 if (Config.LOGV) Log.v(
2155 TAG, "Removing duplicate item from " + j
2156 + " due to specific " + specificsPos);
2157 if (ri == null) {
2158 ri = sri;
2159 }
2160 j--;
2161 N--;
2162 }
2163 }
2164
2165 // Add this specific item to its proper place.
2166 if (ri == null) {
2167 ri = new ResolveInfo();
2168 ri.activityInfo = ai;
2169 }
2170 results.add(specificsPos, ri);
2171 ri.specificIndex = i;
2172 specificsPos++;
2173 }
2174 }
2175
2176 // Now we go through the remaining generic results and remove any
2177 // duplicate actions that are found here.
2178 N = results.size();
2179 for (int i=specificsPos; i<N-1; i++) {
2180 final ResolveInfo rii = results.get(i);
2181 if (rii.filter == null) {
2182 continue;
2183 }
2184
2185 // Iterate over all of the actions of this result's intent
2186 // filter... typically this should be just one.
2187 final Iterator<String> it = rii.filter.actionsIterator();
2188 if (it == null) {
2189 continue;
2190 }
2191 while (it.hasNext()) {
2192 final String action = it.next();
2193 if (resultsAction != null && resultsAction.equals(action)) {
2194 // If this action was explicitly requested, then don't
2195 // remove things that have it.
2196 continue;
2197 }
2198 for (int j=i+1; j<N; j++) {
2199 final ResolveInfo rij = results.get(j);
2200 if (rij.filter != null && rij.filter.hasAction(action)) {
2201 results.remove(j);
2202 if (Config.LOGV) Log.v(
2203 TAG, "Removing duplicate item from " + j
2204 + " due to action " + action + " at " + i);
2205 j--;
2206 N--;
2207 }
2208 }
2209 }
2210
2211 // If the caller didn't request filter information, drop it now
2212 // so we don't have to marshall/unmarshall it.
2213 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2214 rii.filter = null;
2215 }
2216 }
2217
2218 // Filter out the caller activity if so requested.
2219 if (caller != null) {
2220 N = results.size();
2221 for (int i=0; i<N; i++) {
2222 ActivityInfo ainfo = results.get(i).activityInfo;
2223 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2224 && caller.getClassName().equals(ainfo.name)) {
2225 results.remove(i);
2226 break;
2227 }
2228 }
2229 }
2230
2231 // If the caller didn't request filter information,
2232 // drop them now so we don't have to
2233 // marshall/unmarshall it.
2234 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2235 N = results.size();
2236 for (int i=0; i<N; i++) {
2237 results.get(i).filter = null;
2238 }
2239 }
2240
2241 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2242 return results;
2243 }
2244
2245 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2246 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002247 ComponentName comp = intent.getComponent();
2248 if (comp != null) {
2249 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2250 ActivityInfo ai = getReceiverInfo(comp, flags);
2251 if (ai != null) {
2252 ResolveInfo ri = new ResolveInfo();
2253 ri.activityInfo = ai;
2254 list.add(ri);
2255 }
2256 return list;
2257 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002259 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002260 String pkgName = intent.getPackage();
2261 if (pkgName == null) {
2262 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2263 resolvedType, flags);
2264 }
2265 PackageParser.Package pkg = mPackages.get(pkgName);
2266 if (pkg != null) {
2267 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2268 resolvedType, flags, pkg.receivers);
2269 }
2270 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 }
2272 }
2273
2274 public ResolveInfo resolveService(Intent intent, String resolvedType,
2275 int flags) {
2276 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2277 flags);
2278 if (query != null) {
2279 if (query.size() >= 1) {
2280 // If there is more than one service with the same priority,
2281 // just arbitrarily pick the first one.
2282 return query.get(0);
2283 }
2284 }
2285 return null;
2286 }
2287
2288 public List<ResolveInfo> queryIntentServices(Intent intent,
2289 String resolvedType, int flags) {
2290 ComponentName comp = intent.getComponent();
2291 if (comp != null) {
2292 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2293 ServiceInfo si = getServiceInfo(comp, flags);
2294 if (si != null) {
2295 ResolveInfo ri = new ResolveInfo();
2296 ri.serviceInfo = si;
2297 list.add(ri);
2298 }
2299 return list;
2300 }
2301
2302 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002303 String pkgName = intent.getPackage();
2304 if (pkgName == null) {
2305 return (List<ResolveInfo>)mServices.queryIntent(intent,
2306 resolvedType, flags);
2307 }
2308 PackageParser.Package pkg = mPackages.get(pkgName);
2309 if (pkg != null) {
2310 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2311 resolvedType, flags, pkg.services);
2312 }
2313 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002314 }
2315 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 public List<PackageInfo> getInstalledPackages(int flags) {
2318 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2319
2320 synchronized (mPackages) {
2321 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2322 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2323 while (i.hasNext()) {
2324 final PackageSetting ps = i.next();
2325 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2326 if(psPkg != null) {
2327 finalList.add(psPkg);
2328 }
2329 }
2330 }
2331 else {
2332 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2333 while (i.hasNext()) {
2334 final PackageParser.Package p = i.next();
2335 if (p.applicationInfo != null) {
2336 PackageInfo pi = generatePackageInfo(p, flags);
2337 if(pi != null) {
2338 finalList.add(pi);
2339 }
2340 }
2341 }
2342 }
2343 }
2344 return finalList;
2345 }
2346
2347 public List<ApplicationInfo> getInstalledApplications(int flags) {
2348 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2349 synchronized(mPackages) {
2350 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2351 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2352 while (i.hasNext()) {
2353 final PackageSetting ps = i.next();
2354 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2355 if(ai != null) {
2356 finalList.add(ai);
2357 }
2358 }
2359 }
2360 else {
2361 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2362 while (i.hasNext()) {
2363 final PackageParser.Package p = i.next();
2364 if (p.applicationInfo != null) {
2365 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2366 if(ai != null) {
2367 finalList.add(ai);
2368 }
2369 }
2370 }
2371 }
2372 }
2373 return finalList;
2374 }
2375
2376 public List<ApplicationInfo> getPersistentApplications(int flags) {
2377 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2378
2379 synchronized (mPackages) {
2380 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2381 while (i.hasNext()) {
2382 PackageParser.Package p = i.next();
2383 if (p.applicationInfo != null
2384 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002385 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002386 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 }
2388 }
2389 }
2390
2391 return finalList;
2392 }
2393
2394 public ProviderInfo resolveContentProvider(String name, int flags) {
2395 synchronized (mPackages) {
2396 final PackageParser.Provider provider = mProviders.get(name);
2397 return provider != null
2398 && mSettings.isEnabledLP(provider.info, flags)
2399 && (!mSafeMode || (provider.info.applicationInfo.flags
2400 &ApplicationInfo.FLAG_SYSTEM) != 0)
2401 ? PackageParser.generateProviderInfo(provider, flags)
2402 : null;
2403 }
2404 }
2405
Fred Quintana718d8a22009-04-29 17:53:20 -07002406 /**
2407 * @deprecated
2408 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 public void querySyncProviders(List outNames, List outInfo) {
2410 synchronized (mPackages) {
2411 Iterator<Map.Entry<String, PackageParser.Provider>> i
2412 = mProviders.entrySet().iterator();
2413
2414 while (i.hasNext()) {
2415 Map.Entry<String, PackageParser.Provider> entry = i.next();
2416 PackageParser.Provider p = entry.getValue();
2417
2418 if (p.syncable
2419 && (!mSafeMode || (p.info.applicationInfo.flags
2420 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2421 outNames.add(entry.getKey());
2422 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2423 }
2424 }
2425 }
2426 }
2427
2428 public List<ProviderInfo> queryContentProviders(String processName,
2429 int uid, int flags) {
2430 ArrayList<ProviderInfo> finalList = null;
2431
2432 synchronized (mPackages) {
2433 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2434 while (i.hasNext()) {
2435 PackageParser.Provider p = i.next();
2436 if (p.info.authority != null
2437 && (processName == null ||
2438 (p.info.processName.equals(processName)
2439 && p.info.applicationInfo.uid == uid))
2440 && mSettings.isEnabledLP(p.info, flags)
2441 && (!mSafeMode || (p.info.applicationInfo.flags
2442 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2443 if (finalList == null) {
2444 finalList = new ArrayList<ProviderInfo>(3);
2445 }
2446 finalList.add(PackageParser.generateProviderInfo(p,
2447 flags));
2448 }
2449 }
2450 }
2451
2452 if (finalList != null) {
2453 Collections.sort(finalList, mProviderInitOrderSorter);
2454 }
2455
2456 return finalList;
2457 }
2458
2459 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2460 int flags) {
2461 synchronized (mPackages) {
2462 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2463 return PackageParser.generateInstrumentationInfo(i, flags);
2464 }
2465 }
2466
2467 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2468 int flags) {
2469 ArrayList<InstrumentationInfo> finalList =
2470 new ArrayList<InstrumentationInfo>();
2471
2472 synchronized (mPackages) {
2473 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2474 while (i.hasNext()) {
2475 PackageParser.Instrumentation p = i.next();
2476 if (targetPackage == null
2477 || targetPackage.equals(p.info.targetPackage)) {
2478 finalList.add(PackageParser.generateInstrumentationInfo(p,
2479 flags));
2480 }
2481 }
2482 }
2483
2484 return finalList;
2485 }
2486
2487 private void scanDirLI(File dir, int flags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002488 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002489 if (files == null) {
2490 Log.d(TAG, "No files in app dir " + dir);
2491 return;
2492 }
2493
2494 Log.d(TAG, "Scanning app dir " + dir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495
2496 int i;
2497 for (i=0; i<files.length; i++) {
2498 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002499 if (!isPackageFilename(files[i])) {
2500 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002501 continue;
2502 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002503 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002505 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002506 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2507 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002508 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002509 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002510 file.delete();
2511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 }
2513 }
2514
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002515 private static File getSettingsProblemFile() {
2516 File dataDir = Environment.getDataDirectory();
2517 File systemDir = new File(dataDir, "system");
2518 File fname = new File(systemDir, "uiderrors.txt");
2519 return fname;
2520 }
2521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 private static void reportSettingsProblem(int priority, String msg) {
2523 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002524 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 FileOutputStream out = new FileOutputStream(fname, true);
2526 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002527 SimpleDateFormat formatter = new SimpleDateFormat();
2528 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2529 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 pw.close();
2531 FileUtils.setPermissions(
2532 fname.toString(),
2533 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2534 -1, -1);
2535 } catch (java.io.IOException e) {
2536 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002537 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 }
2539
2540 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2541 PackageParser.Package pkg, File srcFile, int parseFlags) {
2542 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002543 if (ps != null
2544 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002545 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002546 if (ps.signatures.mSignatures != null
2547 && ps.signatures.mSignatures.length != 0) {
2548 // Optimization: reuse the existing cached certificates
2549 // if the package appears to be unchanged.
2550 pkg.mSignatures = ps.signatures.mSignatures;
2551 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 }
Jeff Browne7600722010-04-07 18:28:23 -07002553
2554 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002555 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002556 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2557 }
2558
2559 if (!pp.collectCertificates(pkg, parseFlags)) {
2560 mLastScanError = pp.getParseError();
2561 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 }
2563 }
2564 return true;
2565 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 /*
2568 * Scan a package and return the newly parsed package.
2569 * Returns null in case of errors and the error code is stored in mLastScanError
2570 */
2571 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002572 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002574 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002576 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002579 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 if (pkg == null) {
2581 mLastScanError = pp.getParseError();
2582 return null;
2583 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002584 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 PackageSetting updatedPkg;
2586 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002587 // Look to see if we already know about this package.
2588 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002589 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002590 // This package has been renamed to its original name. Let's
2591 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002592 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002593 }
2594 // If there was no original package, see one for the real package name.
2595 if (ps == null) {
2596 ps = mSettings.peekPackageLP(pkg.packageName);
2597 }
2598 // Check to see if this package could be hiding/updating a system
2599 // package. Must look for it either under the original or real
2600 // package name depending on our state.
2601 updatedPkg = mSettings.mDisabledSysPackages.get(
2602 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002604 // First check if this is a system package that may involve an update
2605 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002606 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002607 // The path has changed from what was last scanned... check the
2608 // version of the new path against what we have stored to determine
2609 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002610 if (pkg.mVersionCode < ps.versionCode) {
2611 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002612 // Ignore entry. Skip it.
2613 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002614 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002615 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002616 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2617 return null;
2618 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 // The current app on the system partion is better than
2620 // what we have updated to on the data partition; switch
2621 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002622 // At this point, its safely assumed that package installation for
2623 // apps in system partition will go through. If not there won't be a working
2624 // version of the app
2625 synchronized (mPackages) {
2626 // Just remove the loaded entries from package lists.
2627 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002628 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002629 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002630 + "reverting from " + ps.codePathString
2631 + ": new version " + pkg.mVersionCode
2632 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002633 InstallArgs args = new FileInstallArgs(ps.codePathString,
2634 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002635 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002636 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 }
2639 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002640 if (updatedPkg != null) {
2641 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2642 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2643 }
2644 // Verify certificates against what was last scanned
2645 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002646 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002647 return null;
2648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 // The apk is forward locked (not public) if its code and resources
2650 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002651 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002653 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002654 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002655
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002656 String codePath = null;
2657 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002658 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2659 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002660 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002661 } else {
2662 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002663 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002664 }
2665 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002666 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002667 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002668 codePath = pkg.mScanPath;
2669 // Set application objects path explicitly.
2670 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002672 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 }
2674
Kenny Root85387d72010-08-26 10:13:11 -07002675 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2676 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002677 pkg.mPath = pkg.mScanPath = destCodePath;
2678 pkg.applicationInfo.sourceDir = destCodePath;
2679 pkg.applicationInfo.publicSourceDir = destResPath;
2680 }
2681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 private static String fixProcessName(String defProcessName,
2683 String processName, int uid) {
2684 if (processName == null) {
2685 return defProcessName;
2686 }
2687 return processName;
2688 }
2689
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002690 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002691 PackageParser.Package pkg) {
2692 if (pkgSetting.signatures.mSignatures != null) {
2693 // Already existing package. Make sure signatures match
2694 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2695 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002696 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002697 + " signatures do not match the previously installed version; ignoring!");
2698 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 return false;
2700 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002701 }
2702 // Check for shared user signatures
2703 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2704 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2705 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2706 Slog.e(TAG, "Package " + pkg.packageName
2707 + " has no signatures that match those in shared user "
2708 + pkgSetting.sharedUser.name + "; ignoring!");
2709 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2710 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 }
2713 return true;
2714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002715
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002716 public boolean performDexOpt(String packageName) {
2717 if (!mNoDexOpt) {
2718 return false;
2719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002720
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002721 PackageParser.Package p;
2722 synchronized (mPackages) {
2723 p = mPackages.get(packageName);
2724 if (p == null || p.mDidDexOpt) {
2725 return false;
2726 }
2727 }
2728 synchronized (mInstallLock) {
2729 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2730 }
2731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002733 static final int DEX_OPT_SKIPPED = 0;
2734 static final int DEX_OPT_PERFORMED = 1;
2735 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2738 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002739 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002740 String path = pkg.mScanPath;
2741 int ret = 0;
2742 try {
2743 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002744 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002745 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002746 pkg.mDidDexOpt = true;
2747 performed = true;
2748 }
2749 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002750 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002751 ret = -1;
2752 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002753 Slog.w(TAG, "IOException reading apk: " + path, e);
2754 ret = -1;
2755 } catch (dalvik.system.StaleDexCacheError e) {
2756 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2757 ret = -1;
2758 } catch (Exception e) {
2759 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002760 ret = -1;
2761 }
2762 if (ret < 0) {
2763 //error from installer
2764 return DEX_OPT_FAILED;
2765 }
2766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002767
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002768 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2769 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002770
2771 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2772 return Environment.isEncryptedFilesystemEnabled() &&
2773 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2774 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002775
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002776 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2777 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002778 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002779 + " to " + newPkg.packageName
2780 + ": old package not in system partition");
2781 return false;
2782 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002783 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002784 + " to " + newPkg.packageName
2785 + ": old package still exists");
2786 return false;
2787 }
2788 return true;
2789 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002790
2791 private File getDataPathForPackage(PackageParser.Package pkg) {
2792 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2793 File dataPath;
2794 if (useEncryptedFSDir) {
2795 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2796 } else {
2797 dataPath = new File(mAppDataDir, pkg.packageName);
2798 }
2799 return dataPath;
2800 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002801
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002802 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2803 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002804 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002805 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2806 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002807 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002808 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002809 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2810 return null;
2811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 mScanningPath = scanFile;
2813 if (pkg == null) {
2814 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2815 return null;
2816 }
2817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2819 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2820 }
2821
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002822 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 synchronized (mPackages) {
2824 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002825 Slog.w(TAG, "*************************************************");
2826 Slog.w(TAG, "Core android package being redefined. Skipping.");
2827 Slog.w(TAG, " file=" + mScanningPath);
2828 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2830 return null;
2831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 // Set up information for our fall-back user intent resolution
2834 // activity.
2835 mPlatformPackage = pkg;
2836 pkg.mVersionCode = mSdkVersion;
2837 mAndroidApplication = pkg.applicationInfo;
2838 mResolveActivity.applicationInfo = mAndroidApplication;
2839 mResolveActivity.name = ResolverActivity.class.getName();
2840 mResolveActivity.packageName = mAndroidApplication.packageName;
2841 mResolveActivity.processName = mAndroidApplication.processName;
2842 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2843 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2844 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2845 mResolveActivity.exported = true;
2846 mResolveActivity.enabled = true;
2847 mResolveInfo.activityInfo = mResolveActivity;
2848 mResolveInfo.priority = 0;
2849 mResolveInfo.preferredOrder = 0;
2850 mResolveInfo.match = 0;
2851 mResolveComponentName = new ComponentName(
2852 mAndroidApplication.packageName, mResolveActivity.name);
2853 }
2854 }
2855
2856 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002857 TAG, "Scanning package " + pkg.packageName);
2858 if (mPackages.containsKey(pkg.packageName)
2859 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002860 Slog.w(TAG, "*************************************************");
2861 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002863 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2865 return null;
2866 }
2867
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002868 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002869 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2870 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 SharedUserSetting suid = null;
2873 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002874
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002875 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2876 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002877 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002878 pkg.mRealPackage = null;
2879 pkg.mAdoptPermissions = null;
2880 }
2881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 synchronized (mPackages) {
2883 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002884 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2885 if (mTmpSharedLibraries == null ||
2886 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2887 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2888 }
2889 int num = 0;
2890 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2891 for (int i=0; i<N; i++) {
2892 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002894 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002896 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2898 return null;
2899 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002900 mTmpSharedLibraries[num] = file;
2901 num++;
2902 }
2903 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2904 for (int i=0; i<N; i++) {
2905 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2906 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002907 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002908 + " desires unavailable shared library "
2909 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2910 } else {
2911 mTmpSharedLibraries[num] = file;
2912 num++;
2913 }
2914 }
2915 if (num > 0) {
2916 pkg.usesLibraryFiles = new String[num];
2917 System.arraycopy(mTmpSharedLibraries, 0,
2918 pkg.usesLibraryFiles, 0, num);
2919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002920
Dianne Hackborn49237342009-08-27 20:08:01 -07002921 if (pkg.reqFeatures != null) {
2922 N = pkg.reqFeatures.size();
2923 for (int i=0; i<N; i++) {
2924 FeatureInfo fi = pkg.reqFeatures.get(i);
2925 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2926 // Don't care.
2927 continue;
2928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002929
Dianne Hackborn49237342009-08-27 20:08:01 -07002930 if (fi.name != null) {
2931 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002932 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002933 + " requires unavailable feature "
2934 + fi.name + "; failing!");
2935 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2936 return null;
2937 }
2938 }
2939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 if (pkg.mSharedUserId != null) {
2944 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2945 pkg.applicationInfo.flags, true);
2946 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002947 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 + " for shared user failed");
2949 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2950 return null;
2951 }
2952 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2953 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2954 + suid.userId + "): packages=" + suid.packages);
2955 }
2956 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002957
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002958 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002959 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 Log.w(TAG, "WAITING FOR DEBUGGER");
2961 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002962 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2963 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002964 }
2965 }
2966
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002967 // Check if we are renaming from an original package name.
2968 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002969 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002970 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002971 // This package may need to be renamed to a previously
2972 // installed name. Let's check on that...
2973 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002974 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 // This package had originally been installed as the
2976 // original name, and we have already taken care of
2977 // transitioning to the new one. Just update the new
2978 // one to continue using the old name.
2979 realName = pkg.mRealPackage;
2980 if (!pkg.packageName.equals(renamed)) {
2981 // Callers into this function may have already taken
2982 // care of renaming the package; only do it here if
2983 // it is not already done.
2984 pkg.setPackageName(renamed);
2985 }
2986
Dianne Hackbornc1552392010-03-03 16:19:01 -08002987 } else {
2988 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2989 if ((origPackage=mSettings.peekPackageLP(
2990 pkg.mOriginalPackages.get(i))) != null) {
2991 // We do have the package already installed under its
2992 // original name... should we use it?
2993 if (!verifyPackageUpdate(origPackage, pkg)) {
2994 // New package is not compatible with original.
2995 origPackage = null;
2996 continue;
2997 } else if (origPackage.sharedUser != null) {
2998 // Make sure uid is compatible between packages.
2999 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003000 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003001 + " to " + pkg.packageName + ": old uid "
3002 + origPackage.sharedUser.name
3003 + " differs from " + pkg.mSharedUserId);
3004 origPackage = null;
3005 continue;
3006 }
3007 } else {
3008 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3009 + pkg.packageName + " to old name " + origPackage.name);
3010 }
3011 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003012 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003013 }
3014 }
3015 }
3016
3017 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003018 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003019 + " was transferred to another, but its .apk remains");
3020 }
3021
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003022 // Just create the setting, don't add it yet. For already existing packages
3023 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003024 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003025 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3026 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003028 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3030 return null;
3031 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003032
3033 if (pkgSetting.origPackage != null) {
3034 // If we are first transitioning from an original package,
3035 // fix up the new package's name now. We need to do this after
3036 // looking up the package under its new name, so getPackageLP
3037 // can take care of fiddling things correctly.
3038 pkg.setPackageName(origPackage.name);
3039
3040 // File a report about this.
3041 String msg = "New package " + pkgSetting.realName
3042 + " renamed to replace old package " + pkgSetting.name;
3043 reportSettingsProblem(Log.WARN, msg);
3044
3045 // Make a note of it.
3046 mTransferedPackages.add(origPackage.name);
3047
3048 // No longer need to retain this.
3049 pkgSetting.origPackage = null;
3050 }
3051
3052 if (realName != null) {
3053 // Make a note of it.
3054 mTransferedPackages.add(pkg.packageName);
3055 }
3056
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003057 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 pkg.applicationInfo.uid = pkgSetting.userId;
3062 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003063
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003064 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003065 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 return null;
3067 }
3068 // The signature has changed, but this package is in the system
3069 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003070 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 // However... if this package is part of a shared user, but it
3072 // doesn't match the signature of the shared user, let's fail.
3073 // What this means is that you can't change the signatures
3074 // associated with an overall shared user, which doesn't seem all
3075 // that unreasonable.
3076 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003077 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3078 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3079 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3081 return null;
3082 }
3083 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003084 // File a report about this.
3085 String msg = "System package " + pkg.packageName
3086 + " signature changed; retaining data.";
3087 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003089
The Android Open Source Project10592532009-03-18 17:39:46 -07003090 // Verify that this new package doesn't have any content providers
3091 // that conflict with existing packages. Only do this if the
3092 // package isn't already installed, since we don't want to break
3093 // things that are installed.
3094 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3095 int N = pkg.providers.size();
3096 int i;
3097 for (i=0; i<N; i++) {
3098 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003099 if (p.info.authority != null) {
3100 String names[] = p.info.authority.split(";");
3101 for (int j = 0; j < names.length; j++) {
3102 if (mProviders.containsKey(names[j])) {
3103 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003104 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003105 " (in package " + pkg.applicationInfo.packageName +
3106 ") is already used by "
3107 + ((other != null && other.getComponentName() != null)
3108 ? other.getComponentName().getPackageName() : "?"));
3109 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3110 return null;
3111 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003112 }
3113 }
3114 }
3115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 }
3117
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003118 final String pkgName = pkg.packageName;
3119
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003120 if (pkg.mAdoptPermissions != null) {
3121 // This package wants to adopt ownership of permissions from
3122 // another package.
3123 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3124 String origName = pkg.mAdoptPermissions.get(i);
3125 PackageSetting orig = mSettings.peekPackageLP(origName);
3126 if (orig != null) {
3127 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003128 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003129 + origName + " to " + pkg.packageName);
3130 mSettings.transferPermissions(origName, pkg.packageName);
3131 }
3132 }
3133 }
3134 }
3135
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 long scanFileTime = scanFile.lastModified();
3137 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003138 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 pkg.applicationInfo.processName = fixProcessName(
3140 pkg.applicationInfo.packageName,
3141 pkg.applicationInfo.processName,
3142 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143
3144 File dataPath;
3145 if (mPlatformPackage == pkg) {
3146 // The system package is special.
3147 dataPath = new File (Environment.getDataDirectory(), "system");
3148 pkg.applicationInfo.dataDir = dataPath.getPath();
3149 } else {
3150 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003151 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003152 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003153
3154 boolean uidError = false;
3155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 if (dataPath.exists()) {
3157 mOutPermissions[1] = 0;
3158 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003159
3160 // If we have mismatched owners for the data path, we have a
3161 // problem (unless we're running in the simulator.)
3162 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 boolean recovered = false;
3164 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3165 // If this is a system app, we can at least delete its
3166 // current data so the application will still work.
3167 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003168 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003169 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 // Old data gone!
3171 String msg = "System package " + pkg.packageName
3172 + " has changed from uid: "
3173 + mOutPermissions[1] + " to "
3174 + pkg.applicationInfo.uid + "; old data erased";
3175 reportSettingsProblem(Log.WARN, msg);
3176 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003179 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 pkg.applicationInfo.uid);
3181 if (ret == -1) {
3182 // Ack should not happen!
3183 msg = "System package " + pkg.packageName
3184 + " could not have data directory re-created after delete.";
3185 reportSettingsProblem(Log.WARN, msg);
3186 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3187 return null;
3188 }
3189 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 if (!recovered) {
3192 mHasSystemUidErrors = true;
3193 }
3194 }
3195 if (!recovered) {
3196 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3197 + pkg.applicationInfo.uid + "/fs_"
3198 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003199 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 String msg = "Package " + pkg.packageName
3201 + " has mismatched uid: "
3202 + mOutPermissions[1] + " on disk, "
3203 + pkg.applicationInfo.uid + " in settings";
3204 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003205 mSettings.mReadMessages.append(msg);
3206 mSettings.mReadMessages.append('\n');
3207 uidError = true;
3208 if (!pkgSetting.uidError) {
3209 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 }
3212 }
3213 }
3214 pkg.applicationInfo.dataDir = dataPath.getPath();
3215 } else {
3216 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3217 Log.v(TAG, "Want this data dir: " + dataPath);
3218 //invoke installer to do the actual installation
3219 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003220 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 pkg.applicationInfo.uid);
3222 if(ret < 0) {
3223 // Error from installer
3224 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3225 return null;
3226 }
3227 } else {
3228 dataPath.mkdirs();
3229 if (dataPath.exists()) {
3230 FileUtils.setPermissions(
3231 dataPath.toString(),
3232 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3233 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3234 }
3235 }
3236 if (dataPath.exists()) {
3237 pkg.applicationInfo.dataDir = dataPath.getPath();
3238 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003239 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 pkg.applicationInfo.dataDir = null;
3241 }
3242 }
Kenny Root85387d72010-08-26 10:13:11 -07003243
3244 /*
3245 * Set the data dir to the default "/data/data/<package name>/lib"
3246 * if we got here without anyone telling us different (e.g., apps
3247 * stored on SD card have their native libraries stored in the ASEC
3248 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003249 *
3250 * This happens during an upgrade from a package settings file that
3251 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003252 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003253 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3254 if (pkgSetting.nativeLibraryPathString == null) {
3255 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3256 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3257 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3258 } else {
3259 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3260 }
Kenny Root85387d72010-08-26 10:13:11 -07003261 }
3262
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003263 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 }
3265
Kenny Root85387d72010-08-26 10:13:11 -07003266 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 if (mInstaller != null) {
3268 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003269 /* Note: We don't want to unpack the native binaries for
3270 * system applications, unless they have been updated
3271 * (the binaries are already under /system/lib).
3272 * Also, don't unpack libs for apps on the external card
3273 * since they should have their libraries in the ASEC
3274 * container already.
3275 *
3276 * In other words, we're going to unpack the binaries
3277 * only for non-system apps and system app upgrades.
3278 */
3279 if ((!isSystemApp(pkg) || isUpdatedSystemApp(pkg)) && !isExternal(pkg)) {
3280 Log.i(TAG, path + " changed; unpacking");
3281 File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root85387d72010-08-26 10:13:11 -07003282 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003284 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003285
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003286 if ((scanMode&SCAN_NO_DEX) == 0) {
3287 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3289 return null;
3290 }
3291 }
3292 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 if (mFactoryTest && pkg.requestedPermissions.contains(
3295 android.Manifest.permission.FACTORY_TEST)) {
3296 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3297 }
3298
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003299 // Request the ActivityManager to kill the process(only for existing packages)
3300 // so that we do not end up in a confused state while the user is still using the older
3301 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003302 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003303 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003304 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003305 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003308 // We don't expect installation to fail beyond this point,
3309 if ((scanMode&SCAN_MONITOR) != 0) {
3310 mAppDirs.put(pkg.mPath, pkg);
3311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003313 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003315 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003316 // Make sure we don't accidentally delete its data.
3317 mSettings.mPackagesToBeCleaned.remove(pkgName);
3318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 int N = pkg.providers.size();
3320 StringBuilder r = null;
3321 int i;
3322 for (i=0; i<N; i++) {
3323 PackageParser.Provider p = pkg.providers.get(i);
3324 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3325 p.info.processName, pkg.applicationInfo.uid);
3326 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3327 p.info.name), p);
3328 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003329 if (p.info.authority != null) {
3330 String names[] = p.info.authority.split(";");
3331 p.info.authority = null;
3332 for (int j = 0; j < names.length; j++) {
3333 if (j == 1 && p.syncable) {
3334 // We only want the first authority for a provider to possibly be
3335 // syncable, so if we already added this provider using a different
3336 // authority clear the syncable flag. We copy the provider before
3337 // changing it because the mProviders object contains a reference
3338 // to a provider that we don't want to change.
3339 // Only do this for the second authority since the resulting provider
3340 // object can be the same for all future authorities for this provider.
3341 p = new PackageParser.Provider(p);
3342 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003344 if (!mProviders.containsKey(names[j])) {
3345 mProviders.put(names[j], p);
3346 if (p.info.authority == null) {
3347 p.info.authority = names[j];
3348 } else {
3349 p.info.authority = p.info.authority + ";" + names[j];
3350 }
3351 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3352 Log.d(TAG, "Registered content provider: " + names[j] +
3353 ", className = " + p.info.name +
3354 ", isSyncable = " + p.info.isSyncable);
3355 } else {
3356 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003357 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003358 " (in package " + pkg.applicationInfo.packageName +
3359 "): name already used by "
3360 + ((other != null && other.getComponentName() != null)
3361 ? other.getComponentName().getPackageName() : "?"));
3362 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 }
3364 }
3365 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3366 if (r == null) {
3367 r = new StringBuilder(256);
3368 } else {
3369 r.append(' ');
3370 }
3371 r.append(p.info.name);
3372 }
3373 }
3374 if (r != null) {
3375 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3376 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003377
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 N = pkg.services.size();
3379 r = null;
3380 for (i=0; i<N; i++) {
3381 PackageParser.Service s = pkg.services.get(i);
3382 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3383 s.info.processName, pkg.applicationInfo.uid);
3384 mServices.addService(s);
3385 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3386 if (r == null) {
3387 r = new StringBuilder(256);
3388 } else {
3389 r.append(' ');
3390 }
3391 r.append(s.info.name);
3392 }
3393 }
3394 if (r != null) {
3395 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3396 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 N = pkg.receivers.size();
3399 r = null;
3400 for (i=0; i<N; i++) {
3401 PackageParser.Activity a = pkg.receivers.get(i);
3402 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3403 a.info.processName, pkg.applicationInfo.uid);
3404 mReceivers.addActivity(a, "receiver");
3405 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3406 if (r == null) {
3407 r = new StringBuilder(256);
3408 } else {
3409 r.append(' ');
3410 }
3411 r.append(a.info.name);
3412 }
3413 }
3414 if (r != null) {
3415 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3416 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 N = pkg.activities.size();
3419 r = null;
3420 for (i=0; i<N; i++) {
3421 PackageParser.Activity a = pkg.activities.get(i);
3422 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3423 a.info.processName, pkg.applicationInfo.uid);
3424 mActivities.addActivity(a, "activity");
3425 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3426 if (r == null) {
3427 r = new StringBuilder(256);
3428 } else {
3429 r.append(' ');
3430 }
3431 r.append(a.info.name);
3432 }
3433 }
3434 if (r != null) {
3435 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3436 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003437
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 N = pkg.permissionGroups.size();
3439 r = null;
3440 for (i=0; i<N; i++) {
3441 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3442 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3443 if (cur == null) {
3444 mPermissionGroups.put(pg.info.name, pg);
3445 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3446 if (r == null) {
3447 r = new StringBuilder(256);
3448 } else {
3449 r.append(' ');
3450 }
3451 r.append(pg.info.name);
3452 }
3453 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003454 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 + pg.info.packageName + " ignored: original from "
3456 + cur.info.packageName);
3457 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3458 if (r == null) {
3459 r = new StringBuilder(256);
3460 } else {
3461 r.append(' ');
3462 }
3463 r.append("DUP:");
3464 r.append(pg.info.name);
3465 }
3466 }
3467 }
3468 if (r != null) {
3469 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 N = pkg.permissions.size();
3473 r = null;
3474 for (i=0; i<N; i++) {
3475 PackageParser.Permission p = pkg.permissions.get(i);
3476 HashMap<String, BasePermission> permissionMap =
3477 p.tree ? mSettings.mPermissionTrees
3478 : mSettings.mPermissions;
3479 p.group = mPermissionGroups.get(p.info.group);
3480 if (p.info.group == null || p.group != null) {
3481 BasePermission bp = permissionMap.get(p.info.name);
3482 if (bp == null) {
3483 bp = new BasePermission(p.info.name, p.info.packageName,
3484 BasePermission.TYPE_NORMAL);
3485 permissionMap.put(p.info.name, bp);
3486 }
3487 if (bp.perm == null) {
3488 if (bp.sourcePackage == null
3489 || bp.sourcePackage.equals(p.info.packageName)) {
3490 BasePermission tree = findPermissionTreeLP(p.info.name);
3491 if (tree == null
3492 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003493 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 bp.perm = p;
3495 bp.uid = pkg.applicationInfo.uid;
3496 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3497 if (r == null) {
3498 r = new StringBuilder(256);
3499 } else {
3500 r.append(' ');
3501 }
3502 r.append(p.info.name);
3503 }
3504 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003505 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 + p.info.packageName + " ignored: base tree "
3507 + tree.name + " is from package "
3508 + tree.sourcePackage);
3509 }
3510 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003511 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 + p.info.packageName + " ignored: original from "
3513 + bp.sourcePackage);
3514 }
3515 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3516 if (r == null) {
3517 r = new StringBuilder(256);
3518 } else {
3519 r.append(' ');
3520 }
3521 r.append("DUP:");
3522 r.append(p.info.name);
3523 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003524 if (bp.perm == p) {
3525 bp.protectionLevel = p.info.protectionLevel;
3526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003528 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 + p.info.packageName + " ignored: no group "
3530 + p.group);
3531 }
3532 }
3533 if (r != null) {
3534 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3535 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 N = pkg.instrumentation.size();
3538 r = null;
3539 for (i=0; i<N; i++) {
3540 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3541 a.info.packageName = pkg.applicationInfo.packageName;
3542 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3543 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3544 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003545 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003546 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3548 if (r == null) {
3549 r = new StringBuilder(256);
3550 } else {
3551 r.append(' ');
3552 }
3553 r.append(a.info.name);
3554 }
3555 }
3556 if (r != null) {
3557 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3558 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003559
Dianne Hackborn854060af2009-07-09 18:14:31 -07003560 if (pkg.protectedBroadcasts != null) {
3561 N = pkg.protectedBroadcasts.size();
3562 for (i=0; i<N; i++) {
3563 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3564 }
3565 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 pkgSetting.setTimeStamp(scanFileTime);
3568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 return pkg;
3571 }
3572
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003573 private void killApplication(String pkgName, int uid) {
3574 // Request the ActivityManager to kill the process(only for existing packages)
3575 // so that we do not end up in a confused state while the user is still using the older
3576 // version of the application while the new one gets installed.
3577 IActivityManager am = ActivityManagerNative.getDefault();
3578 if (am != null) {
3579 try {
3580 am.killApplicationWithUid(pkgName, uid);
3581 } catch (RemoteException e) {
3582 }
3583 }
3584 }
3585
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003586 // Return the path of the directory that will contain the native binaries
3587 // of a given installed package. This is relative to the data path.
3588 //
Kenny Root85387d72010-08-26 10:13:11 -07003589 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3590 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3591 if (nativeLibraryDir != null) {
3592 return new File(nativeLibraryDir);
3593 } else {
3594 // Fall back for old packages
3595 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3596 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003597 }
3598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3600 if (chatty && Config.LOGD) Log.d(
3601 TAG, "Removing package " + pkg.applicationInfo.packageName );
3602
3603 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606 mPackages.remove(pkg.applicationInfo.packageName);
3607 if (pkg.mPath != null) {
3608 mAppDirs.remove(pkg.mPath);
3609 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 PackageSetting ps = (PackageSetting)pkg.mExtras;
3612 if (ps != null && ps.sharedUser != null) {
3613 // XXX don't do this until the data is removed.
3614 if (false) {
3615 ps.sharedUser.packages.remove(ps);
3616 if (ps.sharedUser.packages.size() == 0) {
3617 // Remove.
3618 }
3619 }
3620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 int N = pkg.providers.size();
3623 StringBuilder r = null;
3624 int i;
3625 for (i=0; i<N; i++) {
3626 PackageParser.Provider p = pkg.providers.get(i);
3627 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3628 p.info.name));
3629 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 /* The is another ContentProvider with this authority when
3632 * this app was installed so this authority is null,
3633 * Ignore it as we don't have to unregister the provider.
3634 */
3635 continue;
3636 }
3637 String names[] = p.info.authority.split(";");
3638 for (int j = 0; j < names.length; j++) {
3639 if (mProviders.get(names[j]) == p) {
3640 mProviders.remove(names[j]);
3641 if (chatty && Config.LOGD) Log.d(
3642 TAG, "Unregistered content provider: " + names[j] +
3643 ", className = " + p.info.name +
3644 ", isSyncable = " + p.info.isSyncable);
3645 }
3646 }
3647 if (chatty) {
3648 if (r == null) {
3649 r = new StringBuilder(256);
3650 } else {
3651 r.append(' ');
3652 }
3653 r.append(p.info.name);
3654 }
3655 }
3656 if (r != null) {
3657 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 N = pkg.services.size();
3661 r = null;
3662 for (i=0; i<N; i++) {
3663 PackageParser.Service s = pkg.services.get(i);
3664 mServices.removeService(s);
3665 if (chatty) {
3666 if (r == null) {
3667 r = new StringBuilder(256);
3668 } else {
3669 r.append(' ');
3670 }
3671 r.append(s.info.name);
3672 }
3673 }
3674 if (r != null) {
3675 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 N = pkg.receivers.size();
3679 r = null;
3680 for (i=0; i<N; i++) {
3681 PackageParser.Activity a = pkg.receivers.get(i);
3682 mReceivers.removeActivity(a, "receiver");
3683 if (chatty) {
3684 if (r == null) {
3685 r = new StringBuilder(256);
3686 } else {
3687 r.append(' ');
3688 }
3689 r.append(a.info.name);
3690 }
3691 }
3692 if (r != null) {
3693 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3694 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 N = pkg.activities.size();
3697 r = null;
3698 for (i=0; i<N; i++) {
3699 PackageParser.Activity a = pkg.activities.get(i);
3700 mActivities.removeActivity(a, "activity");
3701 if (chatty) {
3702 if (r == null) {
3703 r = new StringBuilder(256);
3704 } else {
3705 r.append(' ');
3706 }
3707 r.append(a.info.name);
3708 }
3709 }
3710 if (r != null) {
3711 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 N = pkg.permissions.size();
3715 r = null;
3716 for (i=0; i<N; i++) {
3717 PackageParser.Permission p = pkg.permissions.get(i);
3718 boolean tree = false;
3719 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3720 if (bp == null) {
3721 tree = true;
3722 bp = mSettings.mPermissionTrees.get(p.info.name);
3723 }
3724 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003725 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 if (chatty) {
3727 if (r == null) {
3728 r = new StringBuilder(256);
3729 } else {
3730 r.append(' ');
3731 }
3732 r.append(p.info.name);
3733 }
3734 }
3735 }
3736 if (r != null) {
3737 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 N = pkg.instrumentation.size();
3741 r = null;
3742 for (i=0; i<N; i++) {
3743 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003744 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 if (chatty) {
3746 if (r == null) {
3747 r = new StringBuilder(256);
3748 } else {
3749 r.append(' ');
3750 }
3751 r.append(a.info.name);
3752 }
3753 }
3754 if (r != null) {
3755 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3756 }
3757 }
3758 }
3759
3760 private static final boolean isPackageFilename(String name) {
3761 return name != null && name.endsWith(".apk");
3762 }
3763
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003764 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3765 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3766 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3767 return true;
3768 }
3769 }
3770 return false;
3771 }
3772
3773 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003774 PackageParser.Package pkgInfo, boolean grantPermissions,
3775 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 // Make sure there are no dangling permission trees.
3777 Iterator<BasePermission> it = mSettings.mPermissionTrees
3778 .values().iterator();
3779 while (it.hasNext()) {
3780 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003781 if (bp.packageSetting == null) {
3782 // We may not yet have parsed the package, so just see if
3783 // we still know about its settings.
3784 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3785 }
3786 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003787 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003788 + " from package " + bp.sourcePackage);
3789 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003790 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3791 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3792 Slog.i(TAG, "Removing old permission tree: " + bp.name
3793 + " from package " + bp.sourcePackage);
3794 grantPermissions = true;
3795 it.remove();
3796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003797 }
3798 }
3799
3800 // Make sure all dynamic permissions have been assigned to a package,
3801 // and make sure there are no dangling permissions.
3802 it = mSettings.mPermissions.values().iterator();
3803 while (it.hasNext()) {
3804 BasePermission bp = it.next();
3805 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3806 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3807 + bp.name + " pkg=" + bp.sourcePackage
3808 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003809 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 BasePermission tree = findPermissionTreeLP(bp.name);
3811 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003812 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 bp.perm = new PackageParser.Permission(tree.perm.owner,
3814 new PermissionInfo(bp.pendingInfo));
3815 bp.perm.info.packageName = tree.perm.info.packageName;
3816 bp.perm.info.name = bp.name;
3817 bp.uid = tree.uid;
3818 }
3819 }
3820 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003821 if (bp.packageSetting == null) {
3822 // We may not yet have parsed the package, so just see if
3823 // we still know about its settings.
3824 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3825 }
3826 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003827 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828 + " from package " + bp.sourcePackage);
3829 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003830 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3831 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3832 Slog.i(TAG, "Removing old permission: " + bp.name
3833 + " from package " + bp.sourcePackage);
3834 grantPermissions = true;
3835 it.remove();
3836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 }
3838 }
3839
3840 // Now update the permissions for all packages, in particular
3841 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003842 if (grantPermissions) {
3843 for (PackageParser.Package pkg : mPackages.values()) {
3844 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003845 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003846 }
3847 }
3848 }
3849
3850 if (pkgInfo != null) {
3851 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 }
3853 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3856 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3857 if (ps == null) {
3858 return;
3859 }
3860 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003861 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 if (replace) {
3864 ps.permissionsFixed = false;
3865 if (gp == ps) {
3866 gp.grantedPermissions.clear();
3867 gp.gids = mGlobalGids;
3868 }
3869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003871 if (gp.gids == null) {
3872 gp.gids = mGlobalGids;
3873 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003875 final int N = pkg.requestedPermissions.size();
3876 for (int i=0; i<N; i++) {
3877 String name = pkg.requestedPermissions.get(i);
3878 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003879 if (false) {
3880 if (gp != ps) {
3881 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003882 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 }
3884 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003885 if (bp != null && bp.packageSetting != null) {
3886 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003888 boolean allowedSig = false;
3889 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3890 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003892 } else if (bp.packageSetting == null) {
3893 // This permission is invalid; skip it.
3894 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003895 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3896 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3897 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003898 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003899 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003901 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003902 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 // For updated system applications, the signatureOrSystem permission
3904 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003905 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3907 if(sysPs.grantedPermissions.contains(perm)) {
3908 allowed = true;
3909 } else {
3910 allowed = false;
3911 }
3912 } else {
3913 allowed = true;
3914 }
3915 }
3916 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003917 if (allowed) {
3918 allowedSig = true;
3919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 } else {
3921 allowed = false;
3922 }
3923 if (false) {
3924 if (gp != ps) {
3925 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3926 }
3927 }
3928 if (allowed) {
3929 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3930 && ps.permissionsFixed) {
3931 // If this is an existing, non-system package, then
3932 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003933 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003934 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003935 // Except... if this is a permission that was added
3936 // to the platform (note: need to only do this when
3937 // updating the platform).
3938 final int NP = PackageParser.NEW_PERMISSIONS.length;
3939 for (int ip=0; ip<NP; ip++) {
3940 final PackageParser.NewPermissionInfo npi
3941 = PackageParser.NEW_PERMISSIONS[ip];
3942 if (npi.name.equals(perm)
3943 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3944 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003945 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003946 + pkg.packageName);
3947 break;
3948 }
3949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 }
3951 }
3952 if (allowed) {
3953 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003954 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003955 gp.grantedPermissions.add(perm);
3956 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003957 } else if (!ps.haveGids) {
3958 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 }
3960 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003961 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003962 + " to package " + pkg.packageName
3963 + " because it was previously installed without");
3964 }
3965 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003966 if (gp.grantedPermissions.remove(perm)) {
3967 changedPermission = true;
3968 gp.gids = removeInts(gp.gids, bp.gids);
3969 Slog.i(TAG, "Un-granting permission " + perm
3970 + " from package " + pkg.packageName
3971 + " (protectionLevel=" + bp.protectionLevel
3972 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3973 + ")");
3974 } else {
3975 Slog.w(TAG, "Not granting permission " + perm
3976 + " to package " + pkg.packageName
3977 + " (protectionLevel=" + bp.protectionLevel
3978 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3979 + ")");
3980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003981 }
3982 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003983 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 + " in package " + pkg.packageName);
3985 }
3986 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003987
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003988 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003989 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3990 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 // This is the first that we have heard about this package, so the
3992 // permissions we have now selected are fixed until explicitly
3993 // changed.
3994 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003995 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003996 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 private final class ActivityIntentResolver
4000 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004001 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004003 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 }
4005
Mihai Preda074edef2009-05-18 17:13:31 +02004006 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004007 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004008 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4010 }
4011
Mihai Predaeae850c2009-05-13 10:13:48 +02004012 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4013 ArrayList<PackageParser.Activity> packageActivities) {
4014 if (packageActivities == null) {
4015 return null;
4016 }
4017 mFlags = flags;
4018 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4019 int N = packageActivities.size();
4020 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4021 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004022
4023 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004024 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004025 intentFilters = packageActivities.get(i).intents;
4026 if (intentFilters != null && intentFilters.size() > 0) {
4027 listCut.add(intentFilters);
4028 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004029 }
4030 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4031 }
4032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004034 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 if (SHOW_INFO || Config.LOGV) Log.v(
4036 TAG, " " + type + " " +
4037 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4038 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4039 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004040 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4042 if (SHOW_INFO || Config.LOGV) {
4043 Log.v(TAG, " IntentFilter:");
4044 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4045 }
4046 if (!intent.debugCheck()) {
4047 Log.w(TAG, "==> For Activity " + a.info.name);
4048 }
4049 addFilter(intent);
4050 }
4051 }
4052
4053 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004054 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 if (SHOW_INFO || Config.LOGV) Log.v(
4056 TAG, " " + type + " " +
4057 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4058 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4059 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004060 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4062 if (SHOW_INFO || Config.LOGV) {
4063 Log.v(TAG, " IntentFilter:");
4064 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4065 }
4066 removeFilter(intent);
4067 }
4068 }
4069
4070 @Override
4071 protected boolean allowFilterResult(
4072 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4073 ActivityInfo filterAi = filter.activity.info;
4074 for (int i=dest.size()-1; i>=0; i--) {
4075 ActivityInfo destAi = dest.get(i).activityInfo;
4076 if (destAi.name == filterAi.name
4077 && destAi.packageName == filterAi.packageName) {
4078 return false;
4079 }
4080 }
4081 return true;
4082 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004083
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004085 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4086 return info.activity.owner.packageName;
4087 }
4088
4089 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4091 int match) {
4092 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4093 return null;
4094 }
4095 final PackageParser.Activity activity = info.activity;
4096 if (mSafeMode && (activity.info.applicationInfo.flags
4097 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4098 return null;
4099 }
4100 final ResolveInfo res = new ResolveInfo();
4101 res.activityInfo = PackageParser.generateActivityInfo(activity,
4102 mFlags);
4103 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4104 res.filter = info;
4105 }
4106 res.priority = info.getPriority();
4107 res.preferredOrder = activity.owner.mPreferredOrder;
4108 //System.out.println("Result: " + res.activityInfo.className +
4109 // " = " + res.priority);
4110 res.match = match;
4111 res.isDefault = info.hasDefault;
4112 res.labelRes = info.labelRes;
4113 res.nonLocalizedLabel = info.nonLocalizedLabel;
4114 res.icon = info.icon;
4115 return res;
4116 }
4117
4118 @Override
4119 protected void sortResults(List<ResolveInfo> results) {
4120 Collections.sort(results, mResolvePrioritySorter);
4121 }
4122
4123 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004124 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004125 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004126 out.print(prefix); out.print(
4127 Integer.toHexString(System.identityHashCode(filter.activity)));
4128 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004129 out.print(filter.activity.getComponentShortName());
4130 out.print(" filter ");
4131 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 }
4133
4134// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4135// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4136// final List<ResolveInfo> retList = Lists.newArrayList();
4137// while (i.hasNext()) {
4138// final ResolveInfo resolveInfo = i.next();
4139// if (isEnabledLP(resolveInfo.activityInfo)) {
4140// retList.add(resolveInfo);
4141// }
4142// }
4143// return retList;
4144// }
4145
4146 // Keys are String (activity class name), values are Activity.
4147 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4148 = new HashMap<ComponentName, PackageParser.Activity>();
4149 private int mFlags;
4150 }
4151
4152 private final class ServiceIntentResolver
4153 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004154 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004155 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004156 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 }
4158
Mihai Preda074edef2009-05-18 17:13:31 +02004159 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004161 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4163 }
4164
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004165 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4166 ArrayList<PackageParser.Service> packageServices) {
4167 if (packageServices == null) {
4168 return null;
4169 }
4170 mFlags = flags;
4171 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4172 int N = packageServices.size();
4173 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4174 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4175
4176 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4177 for (int i = 0; i < N; ++i) {
4178 intentFilters = packageServices.get(i).intents;
4179 if (intentFilters != null && intentFilters.size() > 0) {
4180 listCut.add(intentFilters);
4181 }
4182 }
4183 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4184 }
4185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004187 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 if (SHOW_INFO || Config.LOGV) Log.v(
4189 TAG, " " + (s.info.nonLocalizedLabel != null
4190 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4191 if (SHOW_INFO || Config.LOGV) Log.v(
4192 TAG, " Class=" + s.info.name);
4193 int NI = s.intents.size();
4194 int j;
4195 for (j=0; j<NI; j++) {
4196 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4197 if (SHOW_INFO || Config.LOGV) {
4198 Log.v(TAG, " IntentFilter:");
4199 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4200 }
4201 if (!intent.debugCheck()) {
4202 Log.w(TAG, "==> For Service " + s.info.name);
4203 }
4204 addFilter(intent);
4205 }
4206 }
4207
4208 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004209 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 if (SHOW_INFO || Config.LOGV) Log.v(
4211 TAG, " " + (s.info.nonLocalizedLabel != null
4212 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4213 if (SHOW_INFO || Config.LOGV) Log.v(
4214 TAG, " Class=" + s.info.name);
4215 int NI = s.intents.size();
4216 int j;
4217 for (j=0; j<NI; j++) {
4218 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4219 if (SHOW_INFO || Config.LOGV) {
4220 Log.v(TAG, " IntentFilter:");
4221 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4222 }
4223 removeFilter(intent);
4224 }
4225 }
4226
4227 @Override
4228 protected boolean allowFilterResult(
4229 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4230 ServiceInfo filterSi = filter.service.info;
4231 for (int i=dest.size()-1; i>=0; i--) {
4232 ServiceInfo destAi = dest.get(i).serviceInfo;
4233 if (destAi.name == filterSi.name
4234 && destAi.packageName == filterSi.packageName) {
4235 return false;
4236 }
4237 }
4238 return true;
4239 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004242 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4243 return info.service.owner.packageName;
4244 }
4245
4246 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4248 int match) {
4249 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4250 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4251 return null;
4252 }
4253 final PackageParser.Service service = info.service;
4254 if (mSafeMode && (service.info.applicationInfo.flags
4255 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4256 return null;
4257 }
4258 final ResolveInfo res = new ResolveInfo();
4259 res.serviceInfo = PackageParser.generateServiceInfo(service,
4260 mFlags);
4261 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4262 res.filter = filter;
4263 }
4264 res.priority = info.getPriority();
4265 res.preferredOrder = service.owner.mPreferredOrder;
4266 //System.out.println("Result: " + res.activityInfo.className +
4267 // " = " + res.priority);
4268 res.match = match;
4269 res.isDefault = info.hasDefault;
4270 res.labelRes = info.labelRes;
4271 res.nonLocalizedLabel = info.nonLocalizedLabel;
4272 res.icon = info.icon;
4273 return res;
4274 }
4275
4276 @Override
4277 protected void sortResults(List<ResolveInfo> results) {
4278 Collections.sort(results, mResolvePrioritySorter);
4279 }
4280
4281 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004282 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004283 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004284 out.print(prefix); out.print(
4285 Integer.toHexString(System.identityHashCode(filter.service)));
4286 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004287 out.print(filter.service.getComponentShortName());
4288 out.print(" filter ");
4289 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 }
4291
4292// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4293// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4294// final List<ResolveInfo> retList = Lists.newArrayList();
4295// while (i.hasNext()) {
4296// final ResolveInfo resolveInfo = (ResolveInfo) i;
4297// if (isEnabledLP(resolveInfo.serviceInfo)) {
4298// retList.add(resolveInfo);
4299// }
4300// }
4301// return retList;
4302// }
4303
4304 // Keys are String (activity class name), values are Activity.
4305 private final HashMap<ComponentName, PackageParser.Service> mServices
4306 = new HashMap<ComponentName, PackageParser.Service>();
4307 private int mFlags;
4308 };
4309
4310 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4311 new Comparator<ResolveInfo>() {
4312 public int compare(ResolveInfo r1, ResolveInfo r2) {
4313 int v1 = r1.priority;
4314 int v2 = r2.priority;
4315 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4316 if (v1 != v2) {
4317 return (v1 > v2) ? -1 : 1;
4318 }
4319 v1 = r1.preferredOrder;
4320 v2 = r2.preferredOrder;
4321 if (v1 != v2) {
4322 return (v1 > v2) ? -1 : 1;
4323 }
4324 if (r1.isDefault != r2.isDefault) {
4325 return r1.isDefault ? -1 : 1;
4326 }
4327 v1 = r1.match;
4328 v2 = r2.match;
4329 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4330 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4331 }
4332 };
4333
4334 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4335 new Comparator<ProviderInfo>() {
4336 public int compare(ProviderInfo p1, ProviderInfo p2) {
4337 final int v1 = p1.initOrder;
4338 final int v2 = p2.initOrder;
4339 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4340 }
4341 };
4342
Kenny Root93565c4b2010-06-18 15:46:06 -07004343 private static final boolean DEBUG_OBB = false;
4344
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004345 private static final void sendPackageBroadcast(String action, String pkg,
4346 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004347 IActivityManager am = ActivityManagerNative.getDefault();
4348 if (am != null) {
4349 try {
4350 final Intent intent = new Intent(action,
4351 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4352 if (extras != null) {
4353 intent.putExtras(extras);
4354 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004355 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004356 am.broadcastIntent(null, intent, null, finishedReceiver,
4357 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004358 } catch (RemoteException ex) {
4359 }
4360 }
4361 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004362
4363 public String nextPackageToClean(String lastPackage) {
4364 synchronized (mPackages) {
4365 if (!mMediaMounted) {
4366 // If the external storage is no longer mounted at this point,
4367 // the caller may not have been able to delete all of this
4368 // packages files and can not delete any more. Bail.
4369 return null;
4370 }
4371 if (lastPackage != null) {
4372 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4373 }
4374 return mSettings.mPackagesToBeCleaned.size() > 0
4375 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4376 }
4377 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004379 void schedulePackageCleaning(String packageName) {
4380 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4381 }
4382
4383 void startCleaningPackages() {
4384 synchronized (mPackages) {
4385 if (!mMediaMounted) {
4386 return;
4387 }
4388 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4389 return;
4390 }
4391 }
4392 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4393 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4394 IActivityManager am = ActivityManagerNative.getDefault();
4395 if (am != null) {
4396 try {
4397 am.startService(null, intent, null);
4398 } catch (RemoteException e) {
4399 }
4400 }
4401 }
4402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 private final class AppDirObserver extends FileObserver {
4404 public AppDirObserver(String path, int mask, boolean isrom) {
4405 super(path, mask);
4406 mRootDir = path;
4407 mIsRom = isrom;
4408 }
4409
4410 public void onEvent(int event, String path) {
4411 String removedPackage = null;
4412 int removedUid = -1;
4413 String addedPackage = null;
4414 int addedUid = -1;
4415
4416 synchronized (mInstallLock) {
4417 String fullPathStr = null;
4418 File fullPath = null;
4419 if (path != null) {
4420 fullPath = new File(mRootDir, path);
4421 fullPathStr = fullPath.getPath();
4422 }
4423
4424 if (Config.LOGV) Log.v(
4425 TAG, "File " + fullPathStr + " changed: "
4426 + Integer.toHexString(event));
4427
4428 if (!isPackageFilename(path)) {
4429 if (Config.LOGV) Log.v(
4430 TAG, "Ignoring change of non-package file: " + fullPathStr);
4431 return;
4432 }
4433
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004434 // Ignore packages that are being installed or
4435 // have just been installed.
4436 if (ignoreCodePath(fullPathStr)) {
4437 return;
4438 }
4439 PackageParser.Package p = null;
4440 synchronized (mPackages) {
4441 p = mAppDirs.get(fullPathStr);
4442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004443 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004444 if (p != null) {
4445 removePackageLI(p, true);
4446 removedPackage = p.applicationInfo.packageName;
4447 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004448 }
4449 }
4450
4451 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004453 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004454 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4455 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 PackageParser.PARSE_CHATTY |
4457 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004458 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004459 if (p != null) {
4460 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004461 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004462 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004463 }
4464 addedPackage = p.applicationInfo.packageName;
4465 addedUid = p.applicationInfo.uid;
4466 }
4467 }
4468 }
4469
4470 synchronized (mPackages) {
4471 mSettings.writeLP();
4472 }
4473 }
4474
4475 if (removedPackage != null) {
4476 Bundle extras = new Bundle(1);
4477 extras.putInt(Intent.EXTRA_UID, removedUid);
4478 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004479 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4480 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 }
4482 if (addedPackage != null) {
4483 Bundle extras = new Bundle(1);
4484 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004485 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4486 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 }
4488 }
4489
4490 private final String mRootDir;
4491 private final boolean mIsRom;
4492 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 /* Called when a downloaded package installation has been confirmed by the user */
4495 public void installPackage(
4496 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004497 installPackage(packageURI, observer, flags, null);
4498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004499
Jacek Surazski65e13172009-04-28 15:26:38 +02004500 /* Called when a downloaded package installation has been confirmed by the user */
4501 public void installPackage(
4502 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4503 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 mContext.enforceCallingOrSelfPermission(
4505 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004506
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004507 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004508 msg.obj = new InstallParams(packageURI, observer, flags,
4509 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004510 mHandler.sendMessage(msg);
4511 }
4512
Christopher Tate1bb69062010-02-19 17:02:12 -08004513 public void finishPackageInstall(int token) {
4514 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4515 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4516 mHandler.sendMessage(msg);
4517 }
4518
Kenny Root93565c4b2010-06-18 15:46:06 -07004519 public void setPackageObbPath(String packageName, String path) {
4520 if (DEBUG_OBB)
4521 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4522 PackageSetting pkgSetting;
4523 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004524 final int permission = mContext.checkCallingPermission(
4525 android.Manifest.permission.INSTALL_PACKAGES);
4526 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004527 synchronized (mPackages) {
4528 pkgSetting = mSettings.mPackages.get(packageName);
4529 if (pkgSetting == null) {
4530 throw new IllegalArgumentException("Unknown package: " + packageName);
4531 }
4532 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4533 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4534 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4535 + pkgSetting.userId);
4536 }
4537 pkgSetting.obbPathString = path;
4538 mSettings.writeLP();
4539 }
4540 }
4541
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004542 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004543 // Queue up an async operation since the package installation may take a little while.
4544 mHandler.post(new Runnable() {
4545 public void run() {
4546 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004547 // Result object to be returned
4548 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004549 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004550 res.uid = -1;
4551 res.pkg = null;
4552 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004553 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004554 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004555 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004556 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004557 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004558 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004559 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004560
4561 // A restore should be performed at this point if (a) the install
4562 // succeeded, (b) the operation is not an update, and (c) the new
4563 // package has a backupAgent defined.
4564 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004565 boolean doRestore = (!update
4566 && res.pkg != null
4567 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004568
4569 // Set up the post-install work request bookkeeping. This will be used
4570 // and cleaned up by the post-install event handling regardless of whether
4571 // there's a restore pass performed. Token values are >= 1.
4572 int token;
4573 if (mNextInstallToken < 0) mNextInstallToken = 1;
4574 token = mNextInstallToken++;
4575
4576 PostInstallData data = new PostInstallData(args, res);
4577 mRunningInstalls.put(token, data);
4578 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4579
4580 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4581 // Pass responsibility to the Backup Manager. It will perform a
4582 // restore if appropriate, then pass responsibility back to the
4583 // Package Manager to run the post-install observer callbacks
4584 // and broadcasts.
4585 IBackupManager bm = IBackupManager.Stub.asInterface(
4586 ServiceManager.getService(Context.BACKUP_SERVICE));
4587 if (bm != null) {
4588 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4589 + " to BM for possible restore");
4590 try {
4591 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4592 } catch (RemoteException e) {
4593 // can't happen; the backup manager is local
4594 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004595 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004596 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004597 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004598 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004599 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004600 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004602 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004603
4604 if (!doRestore) {
4605 // No restore possible, or the Backup Manager was mysteriously not
4606 // available -- just fire the post-install work request directly.
4607 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4608 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4609 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004610 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004611 }
4612 });
4613 }
4614
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004615 abstract class HandlerParams {
4616 final static int MAX_RETRIES = 4;
4617 int retry = 0;
4618 final void startCopy() {
4619 try {
4620 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4621 retry++;
4622 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004623 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004624 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4625 handleServiceError();
4626 return;
4627 } else {
4628 handleStartCopy();
4629 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4630 mHandler.sendEmptyMessage(MCS_UNBIND);
4631 }
4632 } catch (RemoteException e) {
4633 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4634 mHandler.sendEmptyMessage(MCS_RECONNECT);
4635 }
4636 handleReturnCode();
4637 }
4638
4639 final void serviceError() {
4640 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4641 handleServiceError();
4642 handleReturnCode();
4643 }
4644 abstract void handleStartCopy() throws RemoteException;
4645 abstract void handleServiceError();
4646 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004647 }
4648
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004649 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004650 final IPackageInstallObserver observer;
4651 int flags;
4652 final Uri packageURI;
4653 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004654 private InstallArgs mArgs;
4655 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004656 InstallParams(Uri packageURI,
4657 IPackageInstallObserver observer, int flags,
4658 String installerPackageName) {
4659 this.packageURI = packageURI;
4660 this.flags = flags;
4661 this.observer = observer;
4662 this.installerPackageName = installerPackageName;
4663 }
4664
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004665 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4666 String packageName = pkgLite.packageName;
4667 int installLocation = pkgLite.installLocation;
4668 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4669 synchronized (mPackages) {
4670 PackageParser.Package pkg = mPackages.get(packageName);
4671 if (pkg != null) {
4672 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4673 // Check for updated system application.
4674 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4675 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004676 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004677 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4678 }
4679 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4680 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004681 if (onSd) {
4682 // Install flag overrides everything.
4683 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4684 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004685 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004686 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4687 // Application explicitly specified internal.
4688 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4689 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4690 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004691 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004692 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004693 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004694 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4695 }
4696 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004697 }
4698 }
4699 } else {
4700 // Invalid install. Return error code
4701 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4702 }
4703 }
4704 }
4705 // All the special cases have been taken care of.
4706 // Return result based on recommended install location.
4707 if (onSd) {
4708 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4709 }
4710 return pkgLite.recommendedInstallLocation;
4711 }
4712
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004713 /*
4714 * Invoke remote method to get package information and install
4715 * location values. Override install location based on default
4716 * policy if needed and then create install arguments based
4717 * on the install location.
4718 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004719 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004720 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004721 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4722 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004723 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4724 if (onInt && onSd) {
4725 // Check if both bits are set.
4726 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4727 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4728 } else if (fwdLocked && onSd) {
4729 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004730 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004731 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004732 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004733 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004734 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004735 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004736 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4737 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4738 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4739 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4740 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004741 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4742 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4743 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004744 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4745 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004746 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004747 // Override with defaults if needed.
4748 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004749 if (!onSd && !onInt) {
4750 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004751 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4752 // Set the flag to install on external media.
4753 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004754 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004755 } else {
4756 // Make sure the flag for installing on external
4757 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004758 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004759 flags &= ~PackageManager.INSTALL_EXTERNAL;
4760 }
4761 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004762 }
4763 }
4764 // Create the file args now.
4765 mArgs = createInstallArgs(this);
4766 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4767 // Create copy only if we are not in an erroneous state.
4768 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004769 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004770 }
4771 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004772 }
4773
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004774 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004775 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004776 // If mArgs is null, then MCS couldn't be reached. When it
4777 // reconnects, it will try again to install. At that point, this
4778 // will succeed.
4779 if (mArgs != null) {
4780 processPendingInstall(mArgs, mRet);
4781 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004782 }
4783
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004784 @Override
4785 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004786 mArgs = createInstallArgs(this);
4787 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004788 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004789 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004790
4791 /*
4792 * Utility class used in movePackage api.
4793 * srcArgs and targetArgs are not set for invalid flags and make
4794 * sure to do null checks when invoking methods on them.
4795 * We probably want to return ErrorPrams for both failed installs
4796 * and moves.
4797 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004798 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004799 final IPackageMoveObserver observer;
4800 final int flags;
4801 final String packageName;
4802 final InstallArgs srcArgs;
4803 final InstallArgs targetArgs;
4804 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004805
4806 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4807 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004808 this.srcArgs = srcArgs;
4809 this.observer = observer;
4810 this.flags = flags;
4811 this.packageName = packageName;
4812 if (srcArgs != null) {
4813 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004814 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004815 } else {
4816 targetArgs = null;
4817 }
4818 }
4819
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004820 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004821 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4822 // Check for storage space on target medium
4823 if (!targetArgs.checkFreeStorage(mContainerService)) {
4824 Log.w(TAG, "Insufficient storage to install");
4825 return;
4826 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004827 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004828 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004829 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004830 if (DEBUG_SD_INSTALL) {
4831 StringBuilder builder = new StringBuilder();
4832 if (srcArgs != null) {
4833 builder.append("src: ");
4834 builder.append(srcArgs.getCodePath());
4835 }
4836 if (targetArgs != null) {
4837 builder.append(" target : ");
4838 builder.append(targetArgs.getCodePath());
4839 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004840 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004841 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004842 }
4843
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004844 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004845 void handleReturnCode() {
4846 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004847 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4848 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4849 currentStatus = PackageManager.MOVE_SUCCEEDED;
4850 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4851 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4852 }
4853 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004854 }
4855
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004856 @Override
4857 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004859 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004860 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004861
4862 private InstallArgs createInstallArgs(InstallParams params) {
4863 if (installOnSd(params.flags)) {
4864 return new SdInstallArgs(params);
4865 } else {
4866 return new FileInstallArgs(params);
4867 }
4868 }
4869
Kenny Root85387d72010-08-26 10:13:11 -07004870 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4871 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004872 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004873 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004874 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004875 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004876 }
4877 }
4878
Kenny Root85387d72010-08-26 10:13:11 -07004879 // Used by package mover
4880 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004881 if (installOnSd(flags)) {
4882 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4883 return new SdInstallArgs(packageURI, cid);
4884 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004885 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004886 }
4887 }
4888
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004889 static abstract class InstallArgs {
4890 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004891 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004892 final int flags;
4893 final Uri packageURI;
4894 final String installerPackageName;
4895
4896 InstallArgs(Uri packageURI,
4897 IPackageInstallObserver observer, int flags,
4898 String installerPackageName) {
4899 this.packageURI = packageURI;
4900 this.flags = flags;
4901 this.observer = observer;
4902 this.installerPackageName = installerPackageName;
4903 }
4904
4905 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004906 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004907 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004908 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004909 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004910 abstract String getCodePath();
4911 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004912 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004913 // Need installer lock especially for dex file removal.
4914 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004915 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004916 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004917 }
4918
4919 class FileInstallArgs extends InstallArgs {
4920 File installDir;
4921 String codeFileName;
4922 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004923 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004924 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004925
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004926 FileInstallArgs(InstallParams params) {
4927 super(params.packageURI, params.observer,
4928 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004929 }
4930
Kenny Root85387d72010-08-26 10:13:11 -07004931 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004932 super(null, null, 0, null);
4933 File codeFile = new File(fullCodePath);
4934 installDir = codeFile.getParentFile();
4935 codeFileName = fullCodePath;
4936 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004937 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004938 }
4939
Kenny Root85387d72010-08-26 10:13:11 -07004940 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004941 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004942 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004943 String apkName = getNextCodePath(null, pkgName, ".apk");
4944 codeFileName = new File(installDir, apkName + ".apk").getPath();
4945 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004946 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004947 }
4948
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004949 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4950 return imcs.checkFreeStorage(false, packageURI);
4951 }
4952
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004953 String getCodePath() {
4954 return codeFileName;
4955 }
4956
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004957 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004958 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004959 codeFileName = createTempPackageFile(installDir).getPath();
4960 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004962 }
4963
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004964 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004965 if (temp) {
4966 // Generate temp file name
4967 createCopyFile();
4968 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004969 // Get a ParcelFileDescriptor to write to the output file
4970 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004971 if (!created) {
4972 try {
4973 codeFile.createNewFile();
4974 // Set permissions
4975 if (!setPermissions()) {
4976 // Failed setting permissions.
4977 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4978 }
4979 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004980 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004981 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4982 }
4983 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004984 ParcelFileDescriptor out = null;
4985 try {
Kenny Root85387d72010-08-26 10:13:11 -07004986 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004987 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004988 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004989 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4990 }
4991 // Copy the resource now
4992 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4993 try {
4994 if (imcs.copyResource(packageURI, out)) {
4995 ret = PackageManager.INSTALL_SUCCEEDED;
4996 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004997 } finally {
4998 try { if (out != null) out.close(); } catch (IOException e) {}
4999 }
Kenny Root85387d72010-08-26 10:13:11 -07005000
5001 if (!temp) {
5002 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5003 }
5004
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005005 return ret;
5006 }
5007
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005008 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005009 if (status != PackageManager.INSTALL_SUCCEEDED) {
5010 cleanUp();
5011 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005012 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005013 }
5014
5015 boolean doRename(int status, final String pkgName, String oldCodePath) {
5016 if (status != PackageManager.INSTALL_SUCCEEDED) {
5017 cleanUp();
5018 return false;
5019 } else {
5020 // Rename based on packageName
5021 File codeFile = new File(getCodePath());
5022 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5023 File desFile = new File(installDir, apkName + ".apk");
5024 if (!codeFile.renameTo(desFile)) {
5025 return false;
5026 }
5027 // Reset paths since the file has been renamed.
5028 codeFileName = desFile.getPath();
5029 resourceFileName = getResourcePathFromCodePath();
5030 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005031 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005032 // Failed setting permissions.
5033 return false;
5034 }
5035 return true;
5036 }
5037 }
5038
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005039 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005040 if (status != PackageManager.INSTALL_SUCCEEDED) {
5041 cleanUp();
5042 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005043 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005044 }
5045
5046 String getResourcePath() {
5047 return resourceFileName;
5048 }
5049
5050 String getResourcePathFromCodePath() {
5051 String codePath = getCodePath();
5052 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5053 String apkNameOnly = getApkName(codePath);
5054 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5055 } else {
5056 return codePath;
5057 }
5058 }
5059
Kenny Root85387d72010-08-26 10:13:11 -07005060 @Override
5061 String getNativeLibraryPath() {
5062 return libraryPath;
5063 }
5064
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005065 private boolean cleanUp() {
5066 boolean ret = true;
5067 String sourceDir = getCodePath();
5068 String publicSourceDir = getResourcePath();
5069 if (sourceDir != null) {
5070 File sourceFile = new File(sourceDir);
5071 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005072 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005073 ret = false;
5074 }
5075 // Delete application's code and resources
5076 sourceFile.delete();
5077 }
5078 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5079 final File publicSourceFile = new File(publicSourceDir);
5080 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005081 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005082 }
5083 if (publicSourceFile.exists()) {
5084 publicSourceFile.delete();
5085 }
5086 }
5087 return ret;
5088 }
5089
5090 void cleanUpResourcesLI() {
5091 String sourceDir = getCodePath();
5092 if (cleanUp() && mInstaller != null) {
5093 int retCode = mInstaller.rmdex(sourceDir);
5094 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005095 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005096 + " at location "
5097 + sourceDir + ", retcode=" + retCode);
5098 // we don't consider this to be a failure of the core package deletion
5099 }
5100 }
Kenny Root85387d72010-08-26 10:13:11 -07005101 if (libraryPath != null) {
Kenny Root8f7cc022010-09-12 09:04:56 -07005102 NativeLibraryHelper.removeNativeBinariesLI(libraryPath);
Kenny Root85387d72010-08-26 10:13:11 -07005103 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005104 }
5105
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005106 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005108 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005109 final int filePermissions =
5110 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5111 |FileUtils.S_IROTH;
5112 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5113 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005114 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005115 getCodePath()
5116 + ". The return code was: " + retCode);
5117 // TODO Define new internal error
5118 return false;
5119 }
5120 return true;
5121 }
5122 return true;
5123 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005124
5125 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005126 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005127 cleanUpResourcesLI();
5128 return true;
5129 }
Kenny Root85387d72010-08-26 10:13:11 -07005130
5131 private boolean isFwdLocked() {
5132 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5133 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005134 }
5135
5136 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005137 static final String RES_FILE_NAME = "pkg.apk";
5138
Kenny Root85387d72010-08-26 10:13:11 -07005139 String cid;
5140 String packagePath;
5141 String libraryPath;
5142
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005143 SdInstallArgs(InstallParams params) {
5144 super(params.packageURI, params.observer,
5145 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005146 }
5147
Kenny Root85387d72010-08-26 10:13:11 -07005148 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005149 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005150 // Extract cid from fullCodePath
5151 int eidx = fullCodePath.lastIndexOf("/");
5152 String subStr1 = fullCodePath.substring(0, eidx);
5153 int sidx = subStr1.lastIndexOf("/");
5154 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005155 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005156 }
5157
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005158 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005159 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5160 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005161 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005162 }
5163
5164 SdInstallArgs(Uri packageURI, String cid) {
5165 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005166 this.cid = cid;
5167 }
5168
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005169 void createCopyFile() {
5170 cid = getTempContainerId();
5171 }
5172
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005173 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5174 return imcs.checkFreeStorage(true, packageURI);
5175 }
5176
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005177 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005178 if (temp) {
5179 createCopyFile();
5180 }
Kenny Root85387d72010-08-26 10:13:11 -07005181 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005182 packageURI, cid,
5183 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005184 if (newCachePath != null) {
5185 setCachePath(newCachePath);
5186 return PackageManager.INSTALL_SUCCEEDED;
5187 } else {
5188 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5189 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005190 }
5191
5192 @Override
5193 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005194 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005195 }
5196
5197 @Override
5198 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005199 return packagePath;
5200 }
5201
5202 @Override
5203 String getNativeLibraryPath() {
5204 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005205 }
5206
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005207 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005208 if (status != PackageManager.INSTALL_SUCCEEDED) {
5209 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005210 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005211 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005212 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005213 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005214 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5215 Process.SYSTEM_UID);
5216 if (newCachePath != null) {
5217 setCachePath(newCachePath);
5218 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005219 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5220 }
5221 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005222 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005223 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005224 }
5225
5226 boolean doRename(int status, final String pkgName,
5227 String oldCodePath) {
5228 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005229 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005230 if (PackageHelper.isContainerMounted(cid)) {
5231 // Unmount the container
5232 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005233 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005234 return false;
5235 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005236 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005237 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005238 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5239 " which might be stale. Will try to clean up.");
5240 // Clean up the stale container and proceed to recreate.
5241 if (!PackageHelper.destroySdDir(newCacheId)) {
5242 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5243 return false;
5244 }
5245 // Successfully cleaned up stale container. Try to rename again.
5246 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5247 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5248 + " inspite of cleaning it up.");
5249 return false;
5250 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005251 }
5252 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005253 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005254 newCachePath = PackageHelper.mountSdDir(newCacheId,
5255 getEncryptKey(), Process.SYSTEM_UID);
5256 } else {
5257 newCachePath = PackageHelper.getSdDir(newCacheId);
5258 }
5259 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005260 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005261 return false;
5262 }
5263 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005264 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005265 " at new path: " + newCachePath);
5266 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005267 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005268 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005269 }
5270
Kenny Root85387d72010-08-26 10:13:11 -07005271 private void setCachePath(String newCachePath) {
5272 File cachePath = new File(newCachePath);
5273 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5274 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5275 }
5276
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005277 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005278 if (status != PackageManager.INSTALL_SUCCEEDED) {
5279 cleanUp();
5280 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005281 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005282 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005283 PackageHelper.mountSdDir(cid,
5284 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005285 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005286 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005287 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005288 }
5289
5290 private void cleanUp() {
5291 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005292 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005293 }
5294
5295 void cleanUpResourcesLI() {
5296 String sourceFile = getCodePath();
5297 // Remove dex file
5298 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005299 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005300 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005301 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005302 + " at location "
5303 + sourceFile.toString() + ", retcode=" + retCode);
5304 // we don't consider this to be a failure of the core package deletion
5305 }
5306 }
5307 cleanUp();
5308 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005309
5310 boolean matchContainer(String app) {
5311 if (cid.startsWith(app)) {
5312 return true;
5313 }
5314 return false;
5315 }
5316
5317 String getPackageName() {
5318 int idx = cid.lastIndexOf("-");
5319 if (idx == -1) {
5320 return cid;
5321 }
5322 return cid.substring(0, idx);
5323 }
5324
5325 boolean doPostDeleteLI(boolean delete) {
5326 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005327 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005328 if (mounted) {
5329 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005330 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005331 }
5332 if (ret && delete) {
5333 cleanUpResourcesLI();
5334 }
5335 return ret;
5336 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005337 };
5338
5339 // Utility method used to create code paths based on package name and available index.
5340 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5341 String idxStr = "";
5342 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005343 // Fall back to default value of idx=1 if prefix is not
5344 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005345 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005346 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005347 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005348 if (subStr.endsWith(suffix)) {
5349 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005350 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005351 // If oldCodePath already contains prefix find out the
5352 // ending index to either increment or decrement.
5353 int sidx = subStr.lastIndexOf(prefix);
5354 if (sidx != -1) {
5355 subStr = subStr.substring(sidx + prefix.length());
5356 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005357 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5358 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005359 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005360 try {
5361 idx = Integer.parseInt(subStr);
5362 if (idx <= 1) {
5363 idx++;
5364 } else {
5365 idx--;
5366 }
5367 } catch(NumberFormatException e) {
5368 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005369 }
5370 }
5371 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005372 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005373 return prefix + idxStr;
5374 }
5375
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005376 // Utility method used to ignore ADD/REMOVE events
5377 // by directory observer.
5378 private static boolean ignoreCodePath(String fullPathStr) {
5379 String apkName = getApkName(fullPathStr);
5380 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5381 if (idx != -1 && ((idx+1) < apkName.length())) {
5382 // Make sure the package ends with a numeral
5383 String version = apkName.substring(idx+1);
5384 try {
5385 Integer.parseInt(version);
5386 return true;
5387 } catch (NumberFormatException e) {}
5388 }
5389 return false;
5390 }
5391
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005392 // Utility method that returns the relative package path with respect
5393 // to the installation directory. Like say for /data/data/com.test-1.apk
5394 // string com.test-1 is returned.
5395 static String getApkName(String codePath) {
5396 if (codePath == null) {
5397 return null;
5398 }
5399 int sidx = codePath.lastIndexOf("/");
5400 int eidx = codePath.lastIndexOf(".");
5401 if (eidx == -1) {
5402 eidx = codePath.length();
5403 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005404 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005405 return null;
5406 }
5407 return codePath.substring(sidx+1, eidx);
5408 }
5409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005410 class PackageInstalledInfo {
5411 String name;
5412 int uid;
5413 PackageParser.Package pkg;
5414 int returnCode;
5415 PackageRemovedInfo removedInfo;
5416 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005418 /*
5419 * Install a non-existing package.
5420 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005421 private void installNewPackageLI(PackageParser.Package pkg,
5422 int parseFlags,
5423 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005424 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005425 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005426 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005427
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005428 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005429 res.name = pkgName;
5430 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005431 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5432 // A package with the same name is already installed, though
5433 // it has been renamed to an older name. The package we
5434 // are trying to install should be installed as an update to
5435 // the existing one, but that has not been requested, so bail.
5436 Slog.w(TAG, "Attempt to re-install " + pkgName
5437 + " without first uninstalling package running as "
5438 + mSettings.mRenamedPackages.get(pkgName));
5439 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5440 return;
5441 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005442 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005444 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 + " without first uninstalling.");
5446 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5447 return;
5448 }
5449 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005451 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005453 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5455 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5456 }
5457 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005458 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005459 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005460 res);
5461 // delete the partially installed application. the data directory will have to be
5462 // restored if it was already existing
5463 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5464 // remove package from internal structures. Note that we want deletePackageX to
5465 // delete the package data and cache directories that it created in
5466 // scanPackageLocked, unless those directories existed before we even tried to
5467 // install.
5468 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005469 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005471 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 }
5473 }
5474 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005475
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005476 private void replacePackageLI(PackageParser.Package pkg,
5477 int parseFlags,
5478 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005479 String installerPackageName, PackageInstalledInfo res) {
5480
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005481 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005482 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 // First find the old package info and check signatures
5484 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005485 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005486 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005487 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5489 return;
5490 }
5491 }
Kenny Root85387d72010-08-26 10:13:11 -07005492 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005493 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005494 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005496 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497 }
5498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005500 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005501 PackageParser.Package pkg,
5502 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005503 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005504 PackageParser.Package newPackage = null;
5505 String pkgName = deletedPackage.packageName;
5506 boolean deletedPkg = true;
5507 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005508
Jacek Surazski65e13172009-04-28 15:26:38 +02005509 String oldInstallerPackageName = null;
5510 synchronized (mPackages) {
5511 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5512 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005515 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005516 res.removedInfo, true)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 // If the existing package was'nt successfully deleted
5518 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5519 deletedPkg = false;
5520 } else {
5521 // Successfully deleted the old package. Now proceed with re-installation
5522 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005523 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005525 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5527 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005528 }
5529 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005530 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005531 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 res);
5533 updatedSettings = true;
5534 }
5535 }
5536
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005537 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005538 // remove package from internal structures. Note that we want deletePackageX to
5539 // delete the package data and cache directories that it created in
5540 // scanPackageLocked, unless those directories existed before we even tried to
5541 // install.
5542 if(updatedSettings) {
5543 deletePackageLI(
5544 pkgName, true,
5545 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005546 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005547 }
5548 // Since we failed to install the new package we need to restore the old
5549 // package that we deleted.
5550 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005551 File restoreFile = new File(deletedPackage.mPath);
5552 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005553 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005554 return;
5555 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005556 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005557 boolean oldOnSd = isExternal(deletedPackage);
5558 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5559 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5560 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5561 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5562 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5563 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5564 return;
5565 }
5566 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005567 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005568 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005569 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005570 mSettings.writeLP();
5571 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005572 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 }
5574 }
5575 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005578 PackageParser.Package pkg,
5579 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005580 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 PackageParser.Package newPackage = null;
5582 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005583 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005584 PackageParser.PARSE_IS_SYSTEM;
5585 String packageName = deletedPackage.packageName;
5586 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5587 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005588 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005589 return;
5590 }
5591 PackageParser.Package oldPkg;
5592 PackageSetting oldPkgSetting;
5593 synchronized (mPackages) {
5594 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005595 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005596 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5597 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005598 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 return;
5600 }
5601 }
5602 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5603 res.removedInfo.removedPackage = packageName;
5604 // Remove existing system package
5605 removePackageLI(oldPkg, true);
5606 synchronized (mPackages) {
5607 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5608 }
5609
5610 // Successfully disabled the old package. Now proceed with re-installation
5611 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5612 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005613 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005615 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5617 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5618 }
5619 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005620 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 updatedSettings = true;
5622 }
5623
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005624 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 // Re installation failed. Restore old information
5626 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005627 if (newPackage != null) {
5628 removePackageLI(newPackage, true);
5629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005631 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005633 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 // Restore the old system information in Settings
5635 synchronized(mPackages) {
5636 if(updatedSettings) {
5637 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005638 mSettings.setInstallerPackageName(packageName,
5639 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005640 }
5641 mSettings.writeLP();
5642 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005643 } else {
5644 // If this is an update to an existing update, setup
5645 // to remove the existing update.
5646 synchronized (mPackages) {
5647 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5648 if (ps != null && ps.codePathString != null &&
5649 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5650 int installFlags = 0;
5651 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005652 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005653 }
5654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 }
5656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005657
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005658 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005659 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005660 int retCode;
5661 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5662 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5663 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005664 if (mNoDexOpt) {
5665 /*
5666 * If we're in an engineering build, programs are lazily run
5667 * through dexopt. If the .dex file doesn't exist yet, it
5668 * will be created when the program is run next.
5669 */
5670 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5671 } else {
5672 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5673 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5674 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005675 }
5676 }
5677 return PackageManager.INSTALL_SUCCEEDED;
5678 }
5679
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005680 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005681 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005682 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 synchronized (mPackages) {
5684 //write settings. the installStatus will be incomplete at this stage.
5685 //note that the new package setting would have already been
5686 //added to mPackages. It hasn't been persisted yet.
5687 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5688 mSettings.writeLP();
5689 }
5690
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005691 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005692 != PackageManager.INSTALL_SUCCEEDED) {
5693 // Discontinue if moving dex files failed.
5694 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005696 if((res.returnCode = setPermissionsLI(newPackage))
5697 != PackageManager.INSTALL_SUCCEEDED) {
5698 if (mInstaller != null) {
5699 mInstaller.rmdex(newPackage.mScanPath);
5700 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005701 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005703 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005706 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005707 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 res.name = pkgName;
5709 res.uid = newPackage.applicationInfo.uid;
5710 res.pkg = newPackage;
5711 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005712 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5714 //to update install status
5715 mSettings.writeLP();
5716 }
5717 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005718
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005719 private void installPackageLI(InstallArgs args,
5720 boolean newInstall, PackageInstalledInfo res) {
5721 int pFlags = args.flags;
5722 String installerPackageName = args.installerPackageName;
5723 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005724 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005725 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005726 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005727 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005728 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005729 // Result object to be returned
5730 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5731
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005732 // Retrieve PackageSettings and parse package
5733 int parseFlags = PackageParser.PARSE_CHATTY |
5734 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5735 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5736 parseFlags |= mDefParseFlags;
5737 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5738 pp.setSeparateProcesses(mSeparateProcesses);
5739 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5740 null, mMetrics, parseFlags);
5741 if (pkg == null) {
5742 res.returnCode = pp.getParseError();
5743 return;
5744 }
5745 String pkgName = res.name = pkg.packageName;
5746 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5747 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5748 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5749 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005750 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005751 }
5752 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5753 res.returnCode = pp.getParseError();
5754 return;
5755 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005756 // Get rid of all references to package scan path via parser.
5757 pp = null;
5758 String oldCodePath = null;
5759 boolean systemApp = false;
5760 synchronized (mPackages) {
5761 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005762 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5763 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005764 if (pkg.mOriginalPackages != null
5765 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005766 && mPackages.containsKey(oldName)) {
5767 // This package is derived from an original package,
5768 // and this device has been updating from that original
5769 // name. We must continue using the original name, so
5770 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005771 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005772 pkgName = pkg.packageName;
5773 replace = true;
5774 } else if (mPackages.containsKey(pkgName)) {
5775 // This package, under its official name, already exists
5776 // on the device; we should replace it.
5777 replace = true;
5778 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005779 }
5780 PackageSetting ps = mSettings.mPackages.get(pkgName);
5781 if (ps != null) {
5782 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5783 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5784 systemApp = (ps.pkg.applicationInfo.flags &
5785 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005786 }
5787 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005789
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005790 if (systemApp && onSd) {
5791 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005792 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005793 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5794 return;
5795 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005796
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005797 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5798 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5799 return;
5800 }
5801 // Set application objects path explicitly after the rename
5802 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005803 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005804 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005805 replacePackageLI(pkg, parseFlags, scanMode,
5806 installerPackageName, res);
5807 } else {
5808 installNewPackageLI(pkg, parseFlags, scanMode,
5809 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005810 }
5811 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005812
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005813 private int setPermissionsLI(PackageParser.Package newPackage) {
5814 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005815 int retCode = 0;
5816 // TODO Gross hack but fix later. Ideally move this to be a post installation
5817 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005818 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005819 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005820 try {
5821 extractPublicFiles(newPackage, destResourceFile);
5822 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005823 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 -08005824 " forward-locked app.");
5825 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5826 } finally {
5827 //TODO clean up the extracted public files
5828 }
5829 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005830 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 newPackage.applicationInfo.uid);
5832 } else {
5833 final int filePermissions =
5834 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005835 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005836 newPackage.applicationInfo.uid);
5837 }
5838 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005839 // The permissions on the resource file was set when it was copied for
5840 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005844 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005845 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005846 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005847 // TODO Define new internal error
5848 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 }
5850 return PackageManager.INSTALL_SUCCEEDED;
5851 }
5852
Kenny Root85387d72010-08-26 10:13:11 -07005853 private static boolean isForwardLocked(PackageParser.Package pkg) {
5854 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005855 }
5856
Kenny Root85387d72010-08-26 10:13:11 -07005857 private static boolean isExternal(PackageParser.Package pkg) {
5858 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5859 }
5860
5861 private static boolean isSystemApp(PackageParser.Package pkg) {
5862 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5863 }
5864
5865 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5866 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005867 }
5868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 private void extractPublicFiles(PackageParser.Package newPackage,
5870 File publicZipFile) throws IOException {
5871 final ZipOutputStream publicZipOutStream =
5872 new ZipOutputStream(new FileOutputStream(publicZipFile));
5873 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5874
5875 // Copy manifest, resources.arsc and res directory to public zip
5876
5877 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5878 while (privateZipEntries.hasMoreElements()) {
5879 final ZipEntry zipEntry = privateZipEntries.nextElement();
5880 final String zipEntryName = zipEntry.getName();
5881 if ("AndroidManifest.xml".equals(zipEntryName)
5882 || "resources.arsc".equals(zipEntryName)
5883 || zipEntryName.startsWith("res/")) {
5884 try {
5885 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5886 } catch (IOException e) {
5887 try {
5888 publicZipOutStream.close();
5889 throw e;
5890 } finally {
5891 publicZipFile.delete();
5892 }
5893 }
5894 }
5895 }
5896
5897 publicZipOutStream.close();
5898 FileUtils.setPermissions(
5899 publicZipFile.getAbsolutePath(),
5900 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5901 -1, -1);
5902 }
5903
5904 private static void copyZipEntry(ZipEntry zipEntry,
5905 ZipFile inZipFile,
5906 ZipOutputStream outZipStream) throws IOException {
5907 byte[] buffer = new byte[4096];
5908 int num;
5909
5910 ZipEntry newEntry;
5911 if (zipEntry.getMethod() == ZipEntry.STORED) {
5912 // Preserve the STORED method of the input entry.
5913 newEntry = new ZipEntry(zipEntry);
5914 } else {
5915 // Create a new entry so that the compressed len is recomputed.
5916 newEntry = new ZipEntry(zipEntry.getName());
5917 }
5918 outZipStream.putNextEntry(newEntry);
5919
5920 InputStream data = inZipFile.getInputStream(zipEntry);
5921 while ((num = data.read(buffer)) > 0) {
5922 outZipStream.write(buffer, 0, num);
5923 }
5924 outZipStream.flush();
5925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005927 private void deleteTempPackageFiles() {
5928 FilenameFilter filter = new FilenameFilter() {
5929 public boolean accept(File dir, String name) {
5930 return name.startsWith("vmdl") && name.endsWith(".tmp");
5931 }
5932 };
5933 String tmpFilesList[] = mAppInstallDir.list(filter);
5934 if(tmpFilesList == null) {
5935 return;
5936 }
5937 for(int i = 0; i < tmpFilesList.length; i++) {
5938 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5939 tmpFile.delete();
5940 }
5941 }
5942
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005943 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005944 File tmpPackageFile;
5945 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005946 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005947 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005948 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 return null;
5950 }
5951 try {
5952 FileUtils.setPermissions(
5953 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5954 -1, -1);
5955 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005956 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 return null;
5958 }
5959 return tmpPackageFile;
5960 }
5961
5962 public void deletePackage(final String packageName,
5963 final IPackageDeleteObserver observer,
5964 final int flags) {
5965 mContext.enforceCallingOrSelfPermission(
5966 android.Manifest.permission.DELETE_PACKAGES, null);
5967 // Queue up an async operation since the package deletion may take a little while.
5968 mHandler.post(new Runnable() {
5969 public void run() {
5970 mHandler.removeCallbacks(this);
5971 final boolean succeded = deletePackageX(packageName, true, true, flags);
5972 if (observer != null) {
5973 try {
5974 observer.packageDeleted(succeded);
5975 } catch (RemoteException e) {
5976 Log.i(TAG, "Observer no longer exists.");
5977 } //end catch
5978 } //end if
5979 } //end run
5980 });
5981 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005982
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005983 /**
5984 * This method is an internal method that could be get invoked either
5985 * to delete an installed package or to clean up a failed installation.
5986 * After deleting an installed package, a broadcast is sent to notify any
5987 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005988 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005989 * installation wouldn't have sent the initial broadcast either
5990 * The key steps in deleting a package are
5991 * deleting the package information in internal structures like mPackages,
5992 * deleting the packages base directories through installd
5993 * updating mSettings to reflect current status
5994 * persisting settings for later use
5995 * sending a broadcast if necessary
5996 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005997 private boolean deletePackageX(String packageName, boolean sendBroadCast,
5998 boolean deleteCodeAndResources, int flags) {
5999 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006000 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006002 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6003 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6004 try {
6005 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006006 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006007 return false;
6008 }
6009 } catch (RemoteException e) {
6010 }
6011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006013 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006014 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006018 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006019 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006020
6021 // If the removed package was a system update, the old system packaged
6022 // was re-enabled; we need to broadcast this information
6023 if (systemUpdate) {
6024 Bundle extras = new Bundle(1);
6025 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6026 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6027
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006028 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6029 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006032 // Force a gc here.
6033 Runtime.getRuntime().gc();
6034 // Delete the resources here after sending the broadcast to let
6035 // other processes clean up before deleting resources.
6036 if (info.args != null) {
6037 synchronized (mInstallLock) {
6038 info.args.doPostDeleteLI(deleteCodeAndResources);
6039 }
6040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 return res;
6042 }
6043
6044 static class PackageRemovedInfo {
6045 String removedPackage;
6046 int uid = -1;
6047 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006048 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006049 // Clean up resources deleted packages.
6050 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006051
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006052 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 Bundle extras = new Bundle(1);
6054 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6055 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6056 if (replacing) {
6057 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6058 }
6059 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006060 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006061 }
6062 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006063 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 }
6065 }
6066 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 /*
6069 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6070 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006071 * 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 -08006072 * delete a partially installed application.
6073 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006074 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006075 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006076 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006077 if (outInfo != null) {
6078 outInfo.removedPackage = packageName;
6079 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006080 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 // Retrieve object to delete permissions for shared user later on
6082 PackageSetting deletedPs;
6083 synchronized (mPackages) {
6084 deletedPs = mSettings.mPackages.get(packageName);
6085 }
6086 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006087 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006089 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006090 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006091 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006092 + packageName + ", retcode=" + retCode);
6093 // we don't consider this to be a failure of the core package deletion
6094 }
6095 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006096 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 PackageParser.Package pkg = mPackages.get(packageName);
6098 File dataDir = new File(pkg.applicationInfo.dataDir);
6099 dataDir.delete();
6100 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006101 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 }
6103 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006104 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006105 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6106 if (outInfo != null) {
6107 outInfo.removedUid = mSettings.removePackageLP(packageName);
6108 }
6109 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006110 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006111 if (deletedPs.sharedUser != null) {
6112 // remove permissions associated with package
6113 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6114 }
6115 }
6116 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006117 // remove from preferred activities.
6118 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6119 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6120 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6121 removed.add(pa);
6122 }
6123 }
6124 for (PreferredActivity pa : removed) {
6125 mSettings.mPreferredActivities.removeFilter(pa);
6126 }
6127 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006128 if (writeSettings) {
6129 // Save settings now
6130 mSettings.writeLP();
6131 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 }
6133 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 /*
6136 * Tries to delete system package.
6137 */
6138 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006139 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140 ApplicationInfo applicationInfo = p.applicationInfo;
6141 //applicable for non-partially installed applications only
6142 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006143 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 return false;
6145 }
6146 PackageSetting ps = null;
6147 // Confirm if the system package has been updated
6148 // An updated system app can be deleted. This will also have to restore
6149 // the system pkg from system partition
6150 synchronized (mPackages) {
6151 ps = mSettings.getDisabledSystemPkg(p.packageName);
6152 }
6153 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006154 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 return false;
6156 } else {
6157 Log.i(TAG, "Deleting system pkg from data partition");
6158 }
6159 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006160 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006161 final boolean deleteCodeAndResources;
6162 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006163 // Delete code and resources for downgrades
6164 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006165 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006166 } else {
6167 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006168 deleteCodeAndResources = false;
6169 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006170 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006171 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6172 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 if (!ret) {
6174 return false;
6175 }
6176 synchronized (mPackages) {
6177 // Reinstate the old system package
6178 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006179 // Remove any native libraries from the upgraded package.
6180 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 }
6182 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006183 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006185 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006188 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006189 return false;
6190 }
6191 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006192 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006193 if (writeSettings) {
6194 mSettings.writeLP();
6195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 }
6197 return true;
6198 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006201 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6202 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 ApplicationInfo applicationInfo = p.applicationInfo;
6204 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006205 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 return false;
6207 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006208 if (outInfo != null) {
6209 outInfo.uid = applicationInfo.uid;
6210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211
6212 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006213 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214
6215 // Delete application code and resources
6216 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006217 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006218 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6219 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6220 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6221 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 }
6223 return true;
6224 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 /*
6227 * This method handles package deletion in general
6228 */
6229 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006230 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6231 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006233 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 return false;
6235 }
6236 PackageParser.Package p;
6237 boolean dataOnly = false;
6238 synchronized (mPackages) {
6239 p = mPackages.get(packageName);
6240 if (p == null) {
6241 //this retrieves partially installed apps
6242 dataOnly = true;
6243 PackageSetting ps = mSettings.mPackages.get(packageName);
6244 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006245 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006246 return false;
6247 }
6248 p = ps.pkg;
6249 }
6250 }
6251 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006252 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 return false;
6254 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 if (dataOnly) {
6257 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006258 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 return true;
6260 }
6261 // At this point the package should have ApplicationInfo associated with it
6262 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006263 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 return false;
6265 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006266 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006267 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 Log.i(TAG, "Removing system package:"+p.packageName);
6269 // When an updated system application is deleted we delete the existing resources as well and
6270 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006271 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006272 } else {
6273 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006274 // Kill application pre-emptively especially for apps on sd.
6275 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006276 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6277 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006279 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006280 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 public void clearApplicationUserData(final String packageName,
6283 final IPackageDataObserver observer) {
6284 mContext.enforceCallingOrSelfPermission(
6285 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6286 // Queue up an async operation since the package deletion may take a little while.
6287 mHandler.post(new Runnable() {
6288 public void run() {
6289 mHandler.removeCallbacks(this);
6290 final boolean succeeded;
6291 synchronized (mInstallLock) {
6292 succeeded = clearApplicationUserDataLI(packageName);
6293 }
6294 if (succeeded) {
6295 // invoke DeviceStorageMonitor's update method to clear any notifications
6296 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6297 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6298 if (dsm != null) {
6299 dsm.updateMemory();
6300 }
6301 }
6302 if(observer != null) {
6303 try {
6304 observer.onRemoveCompleted(packageName, succeeded);
6305 } catch (RemoteException e) {
6306 Log.i(TAG, "Observer no longer exists.");
6307 }
6308 } //end if observer
6309 } //end run
6310 });
6311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 private boolean clearApplicationUserDataLI(String packageName) {
6314 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006315 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 return false;
6317 }
6318 PackageParser.Package p;
6319 boolean dataOnly = false;
6320 synchronized (mPackages) {
6321 p = mPackages.get(packageName);
6322 if(p == null) {
6323 dataOnly = true;
6324 PackageSetting ps = mSettings.mPackages.get(packageName);
6325 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006326 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 return false;
6328 }
6329 p = ps.pkg;
6330 }
6331 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006332 boolean useEncryptedFSDir = false;
6333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 if(!dataOnly) {
6335 //need to check this only for fully installed applications
6336 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006337 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 return false;
6339 }
6340 final ApplicationInfo applicationInfo = p.applicationInfo;
6341 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006342 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 return false;
6344 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006345 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 }
6347 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006348 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006350 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 + packageName);
6352 return false;
6353 }
6354 }
6355 return true;
6356 }
6357
6358 public void deleteApplicationCacheFiles(final String packageName,
6359 final IPackageDataObserver observer) {
6360 mContext.enforceCallingOrSelfPermission(
6361 android.Manifest.permission.DELETE_CACHE_FILES, null);
6362 // Queue up an async operation since the package deletion may take a little while.
6363 mHandler.post(new Runnable() {
6364 public void run() {
6365 mHandler.removeCallbacks(this);
6366 final boolean succeded;
6367 synchronized (mInstallLock) {
6368 succeded = deleteApplicationCacheFilesLI(packageName);
6369 }
6370 if(observer != null) {
6371 try {
6372 observer.onRemoveCompleted(packageName, succeded);
6373 } catch (RemoteException e) {
6374 Log.i(TAG, "Observer no longer exists.");
6375 }
6376 } //end if observer
6377 } //end run
6378 });
6379 }
6380
6381 private boolean deleteApplicationCacheFilesLI(String packageName) {
6382 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006383 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006384 return false;
6385 }
6386 PackageParser.Package p;
6387 synchronized (mPackages) {
6388 p = mPackages.get(packageName);
6389 }
6390 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006391 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 return false;
6393 }
6394 final ApplicationInfo applicationInfo = p.applicationInfo;
6395 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006396 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006397 return false;
6398 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006399 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006401 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006403 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 + packageName);
6405 return false;
6406 }
6407 }
6408 return true;
6409 }
6410
6411 public void getPackageSizeInfo(final String packageName,
6412 final IPackageStatsObserver observer) {
6413 mContext.enforceCallingOrSelfPermission(
6414 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6415 // Queue up an async operation since the package deletion may take a little while.
6416 mHandler.post(new Runnable() {
6417 public void run() {
6418 mHandler.removeCallbacks(this);
6419 PackageStats lStats = new PackageStats(packageName);
6420 final boolean succeded;
6421 synchronized (mInstallLock) {
6422 succeded = getPackageSizeInfoLI(packageName, lStats);
6423 }
6424 if(observer != null) {
6425 try {
6426 observer.onGetStatsCompleted(lStats, succeded);
6427 } catch (RemoteException e) {
6428 Log.i(TAG, "Observer no longer exists.");
6429 }
6430 } //end if observer
6431 } //end run
6432 });
6433 }
6434
6435 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6436 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006437 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006438 return false;
6439 }
6440 PackageParser.Package p;
6441 boolean dataOnly = false;
6442 synchronized (mPackages) {
6443 p = mPackages.get(packageName);
6444 if(p == null) {
6445 dataOnly = true;
6446 PackageSetting ps = mSettings.mPackages.get(packageName);
6447 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006448 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 return false;
6450 }
6451 p = ps.pkg;
6452 }
6453 }
6454 String publicSrcDir = null;
6455 if(!dataOnly) {
6456 final ApplicationInfo applicationInfo = p.applicationInfo;
6457 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006458 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 return false;
6460 }
6461 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6462 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006463 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 if (mInstaller != null) {
6465 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006466 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 if (res < 0) {
6468 return false;
6469 } else {
6470 return true;
6471 }
6472 }
6473 return true;
6474 }
6475
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006478 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 }
6480
6481 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006482 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006483 }
6484
6485 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006486 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 }
6488
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006489 int getUidTargetSdkVersionLockedLP(int uid) {
6490 Object obj = mSettings.getUserIdLP(uid);
6491 if (obj instanceof SharedUserSetting) {
6492 SharedUserSetting sus = (SharedUserSetting)obj;
6493 final int N = sus.packages.size();
6494 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6495 Iterator<PackageSetting> it = sus.packages.iterator();
6496 int i=0;
6497 while (it.hasNext()) {
6498 PackageSetting ps = it.next();
6499 if (ps.pkg != null) {
6500 int v = ps.pkg.applicationInfo.targetSdkVersion;
6501 if (v < vers) vers = v;
6502 }
6503 }
6504 return vers;
6505 } else if (obj instanceof PackageSetting) {
6506 PackageSetting ps = (PackageSetting)obj;
6507 if (ps.pkg != null) {
6508 return ps.pkg.applicationInfo.targetSdkVersion;
6509 }
6510 }
6511 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6512 }
6513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006514 public void addPreferredActivity(IntentFilter filter, int match,
6515 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006517 if (mContext.checkCallingOrSelfPermission(
6518 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6519 != PackageManager.PERMISSION_GRANTED) {
6520 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6521 < Build.VERSION_CODES.FROYO) {
6522 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6523 + Binder.getCallingUid());
6524 return;
6525 }
6526 mContext.enforceCallingOrSelfPermission(
6527 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6528 }
6529
6530 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6532 mSettings.mPreferredActivities.addFilter(
6533 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006534 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 }
6536 }
6537
Satish Sampath8dbe6122009-06-02 23:35:54 +01006538 public void replacePreferredActivity(IntentFilter filter, int match,
6539 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006540 if (filter.countActions() != 1) {
6541 throw new IllegalArgumentException(
6542 "replacePreferredActivity expects filter to have only 1 action.");
6543 }
6544 if (filter.countCategories() != 1) {
6545 throw new IllegalArgumentException(
6546 "replacePreferredActivity expects filter to have only 1 category.");
6547 }
6548 if (filter.countDataAuthorities() != 0
6549 || filter.countDataPaths() != 0
6550 || filter.countDataSchemes() != 0
6551 || filter.countDataTypes() != 0) {
6552 throw new IllegalArgumentException(
6553 "replacePreferredActivity expects filter to have no data authorities, " +
6554 "paths, schemes or types.");
6555 }
6556 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006557 if (mContext.checkCallingOrSelfPermission(
6558 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6559 != PackageManager.PERMISSION_GRANTED) {
6560 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6561 < Build.VERSION_CODES.FROYO) {
6562 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6563 + Binder.getCallingUid());
6564 return;
6565 }
6566 mContext.enforceCallingOrSelfPermission(
6567 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6568 }
6569
Satish Sampath8dbe6122009-06-02 23:35:54 +01006570 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6571 String action = filter.getAction(0);
6572 String category = filter.getCategory(0);
6573 while (it.hasNext()) {
6574 PreferredActivity pa = it.next();
6575 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6576 it.remove();
6577 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6578 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6579 }
6580 }
6581 addPreferredActivity(filter, match, set, activity);
6582 }
6583 }
6584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006585 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006587 int uid = Binder.getCallingUid();
6588 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006589 if (pkg == null || pkg.applicationInfo.uid != uid) {
6590 if (mContext.checkCallingOrSelfPermission(
6591 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6592 != PackageManager.PERMISSION_GRANTED) {
6593 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6594 < Build.VERSION_CODES.FROYO) {
6595 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6596 + Binder.getCallingUid());
6597 return;
6598 }
6599 mContext.enforceCallingOrSelfPermission(
6600 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6601 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006602 }
6603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006604 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006605 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 }
6607 }
6608 }
6609
6610 boolean clearPackagePreferredActivitiesLP(String packageName) {
6611 boolean changed = false;
6612 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6613 while (it.hasNext()) {
6614 PreferredActivity pa = it.next();
6615 if (pa.mActivity.getPackageName().equals(packageName)) {
6616 it.remove();
6617 changed = true;
6618 }
6619 }
6620 return changed;
6621 }
6622
6623 public int getPreferredActivities(List<IntentFilter> outFilters,
6624 List<ComponentName> outActivities, String packageName) {
6625
6626 int num = 0;
6627 synchronized (mPackages) {
6628 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6629 while (it.hasNext()) {
6630 PreferredActivity pa = it.next();
6631 if (packageName == null
6632 || pa.mActivity.getPackageName().equals(packageName)) {
6633 if (outFilters != null) {
6634 outFilters.add(new IntentFilter(pa));
6635 }
6636 if (outActivities != null) {
6637 outActivities.add(pa.mActivity);
6638 }
6639 }
6640 }
6641 }
6642
6643 return num;
6644 }
6645
6646 public void setApplicationEnabledSetting(String appPackageName,
6647 int newState, int flags) {
6648 setEnabledSetting(appPackageName, null, newState, flags);
6649 }
6650
6651 public void setComponentEnabledSetting(ComponentName componentName,
6652 int newState, int flags) {
6653 setEnabledSetting(componentName.getPackageName(),
6654 componentName.getClassName(), newState, flags);
6655 }
6656
6657 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006658 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6660 || newState == COMPONENT_ENABLED_STATE_ENABLED
6661 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6662 throw new IllegalArgumentException("Invalid new component state: "
6663 + newState);
6664 }
6665 PackageSetting pkgSetting;
6666 final int uid = Binder.getCallingUid();
6667 final int permission = mContext.checkCallingPermission(
6668 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6669 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006670 boolean sendNow = false;
6671 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006672 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006674 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006676 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006677 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006678 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006680 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 }
6682 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006683 "Unknown component: " + packageName
6684 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 }
6686 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6687 throw new SecurityException(
6688 "Permission Denial: attempt to change component state from pid="
6689 + Binder.getCallingPid()
6690 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6691 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006692 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006694 if (pkgSetting.enabled == newState) {
6695 // Nothing to do
6696 return;
6697 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006699 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006700 } else {
6701 // We're dealing with a component level state change
6702 switch (newState) {
6703 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006704 if (!pkgSetting.enableComponentLP(className)) {
6705 return;
6706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006707 break;
6708 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006709 if (!pkgSetting.disableComponentLP(className)) {
6710 return;
6711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006712 break;
6713 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006714 if (!pkgSetting.restoreComponentLP(className)) {
6715 return;
6716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 break;
6718 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006719 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006720 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 }
6722 }
6723 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006724 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006725 components = mPendingBroadcasts.get(packageName);
6726 boolean newPackage = components == null;
6727 if (newPackage) {
6728 components = new ArrayList<String>();
6729 }
6730 if (!components.contains(componentName)) {
6731 components.add(componentName);
6732 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006733 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6734 sendNow = true;
6735 // Purge entry from pending broadcast list if another one exists already
6736 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006737 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006738 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006739 if (newPackage) {
6740 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006741 }
6742 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6743 // Schedule a message
6744 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6745 }
6746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 long callingId = Binder.clearCallingIdentity();
6750 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006751 if (sendNow) {
6752 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006753 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 } finally {
6756 Binder.restoreCallingIdentity(callingId);
6757 }
6758 }
6759
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006760 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006761 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6762 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6763 + " components=" + componentNames);
6764 Bundle extras = new Bundle(4);
6765 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6766 String nameList[] = new String[componentNames.size()];
6767 componentNames.toArray(nameList);
6768 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006769 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6770 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006771 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006772 }
6773
Jacek Surazski65e13172009-04-28 15:26:38 +02006774 public String getInstallerPackageName(String packageName) {
6775 synchronized (mPackages) {
6776 PackageSetting pkg = mSettings.mPackages.get(packageName);
6777 if (pkg == null) {
6778 throw new IllegalArgumentException("Unknown package: " + packageName);
6779 }
6780 return pkg.installerPackageName;
6781 }
6782 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006784 public int getApplicationEnabledSetting(String appPackageName) {
6785 synchronized (mPackages) {
6786 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6787 if (pkg == null) {
6788 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6789 }
6790 return pkg.enabled;
6791 }
6792 }
6793
6794 public int getComponentEnabledSetting(ComponentName componentName) {
6795 synchronized (mPackages) {
6796 final String packageNameStr = componentName.getPackageName();
6797 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6798 if (pkg == null) {
6799 throw new IllegalArgumentException("Unknown component: " + componentName);
6800 }
6801 final String classNameStr = componentName.getClassName();
6802 return pkg.currentEnabledStateLP(classNameStr);
6803 }
6804 }
6805
6806 public void enterSafeMode() {
6807 if (!mSystemReady) {
6808 mSafeMode = true;
6809 }
6810 }
6811
6812 public void systemReady() {
6813 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006814
6815 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006816 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006817 mContext.getContentResolver(),
6818 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006819 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006820 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006821 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 }
6824
6825 public boolean isSafeMode() {
6826 return mSafeMode;
6827 }
6828
6829 public boolean hasSystemUidErrors() {
6830 return mHasSystemUidErrors;
6831 }
6832
6833 static String arrayToString(int[] array) {
6834 StringBuffer buf = new StringBuffer(128);
6835 buf.append('[');
6836 if (array != null) {
6837 for (int i=0; i<array.length; i++) {
6838 if (i > 0) buf.append(", ");
6839 buf.append(array[i]);
6840 }
6841 }
6842 buf.append(']');
6843 return buf.toString();
6844 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006846 @Override
6847 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6848 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6849 != PackageManager.PERMISSION_GRANTED) {
6850 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6851 + Binder.getCallingPid()
6852 + ", uid=" + Binder.getCallingUid()
6853 + " without permission "
6854 + android.Manifest.permission.DUMP);
6855 return;
6856 }
6857
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006858 boolean dumpStar = true;
6859 boolean dumpLibs = false;
6860 boolean dumpFeatures = false;
6861 boolean dumpResolvers = false;
6862 boolean dumpPermissions = false;
6863 boolean dumpPackages = false;
6864 boolean dumpSharedUsers = false;
6865 boolean dumpMessages = false;
6866 boolean dumpProviders = false;
6867
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006868 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006869 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006870
6871 int opti = 0;
6872 while (opti < args.length) {
6873 String opt = args[opti];
6874 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6875 break;
6876 }
6877 opti++;
6878 if ("-a".equals(opt)) {
6879 // Right now we only know how to print all.
6880 } else if ("-h".equals(opt)) {
6881 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006882 pw.println(" [-h] [-f] [cmd] ...");
6883 pw.println(" -f: print details of intent filters");
6884 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006885 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006886 pw.println(" l[ibraries]: list known shared libraries");
6887 pw.println(" f[ibraries]: list device features");
6888 pw.println(" r[esolvers]: dump intent resolvers");
6889 pw.println(" perm[issions]: dump permissions");
6890 pw.println(" prov[iders]: dump content providers");
6891 pw.println(" p[ackages]: dump installed packages");
6892 pw.println(" s[hared-users]: dump shared user IDs");
6893 pw.println(" m[essages]: print collected runtime messages");
6894 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006895 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006896 } else if ("-f".equals(opt)) {
6897 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006898 } else {
6899 pw.println("Unknown argument: " + opt + "; use -h for help");
6900 }
6901 }
6902
6903 // Is the caller requesting to dump a particular piece of data?
6904 if (opti < args.length) {
6905 String cmd = args[opti];
6906 opti++;
6907 // Is this a package name?
6908 if ("android".equals(cmd) || cmd.contains(".")) {
6909 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006910 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
6911 dumpStar = false;
6912 dumpLibs = true;
6913 } else if ("f".equals(cmd) || "features".equals(cmd)) {
6914 dumpStar = false;
6915 dumpFeatures = true;
6916 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
6917 dumpStar = false;
6918 dumpResolvers = true;
6919 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
6920 dumpStar = false;
6921 dumpPermissions = true;
6922 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
6923 dumpStar = false;
6924 dumpPackages = true;
6925 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
6926 dumpStar = false;
6927 dumpSharedUsers = true;
6928 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
6929 dumpStar = false;
6930 dumpProviders = true;
6931 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
6932 dumpStar = false;
6933 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006934 }
6935 }
6936
6937 boolean printedTitle = false;
6938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006939 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006940 if ((dumpStar || dumpLibs) && packageName == null) {
6941 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006942 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006943 pw.println("Libraries:");
6944 Iterator<String> it = mSharedLibraries.keySet().iterator();
6945 while (it.hasNext()) {
6946 String name = it.next();
6947 pw.print(" ");
6948 pw.print(name);
6949 pw.print(" -> ");
6950 pw.println(mSharedLibraries.get(name));
6951 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006952 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006953
6954 if ((dumpStar || dumpFeatures) && packageName == null) {
6955 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006956 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006957 pw.println("Features:");
6958 Iterator<String> it = mAvailableFeatures.keySet().iterator();
6959 while (it.hasNext()) {
6960 String name = it.next();
6961 pw.print(" ");
6962 pw.println(name);
6963 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006964 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006965
6966 if (dumpStar || dumpResolvers) {
6967 if (mActivities.dump(pw, printedTitle
6968 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
6969 " ", packageName, showFilters)) {
6970 printedTitle = true;
6971 }
6972 if (mReceivers.dump(pw, printedTitle
6973 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6974 " ", packageName, showFilters)) {
6975 printedTitle = true;
6976 }
6977 if (mServices.dump(pw, printedTitle
6978 ? "\nService Resolver Table:" : "Service Resolver Table:",
6979 " ", packageName, showFilters)) {
6980 printedTitle = true;
6981 }
6982 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6983 ? "\nPreferred Activities:" : "Preferred Activities:",
6984 " ", packageName, showFilters)) {
6985 printedTitle = true;
6986 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006987 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006988
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006989 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006990 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006992 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6993 continue;
6994 }
6995 if (!printedSomething) {
6996 if (printedTitle) pw.println(" ");
6997 pw.println("Permissions:");
6998 printedSomething = true;
6999 printedTitle = true;
7000 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007001 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7002 pw.print(Integer.toHexString(System.identityHashCode(p)));
7003 pw.println("):");
7004 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7005 pw.print(" uid="); pw.print(p.uid);
7006 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007007 pw.print(" type="); pw.print(p.type);
7008 pw.print(" prot="); pw.println(p.protectionLevel);
7009 if (p.packageSetting != null) {
7010 pw.print(" packageSetting="); pw.println(p.packageSetting);
7011 }
7012 if (p.perm != null) {
7013 pw.print(" perm="); pw.println(p.perm);
7014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007015 }
7016 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007017
7018 if (dumpStar || dumpProviders) {
7019 printedSomething = false;
7020 for (PackageParser.Provider p : mProviders.values()) {
7021 if (packageName != null && !packageName.equals(p.info.packageName)) {
7022 continue;
7023 }
7024 if (!printedSomething) {
7025 if (printedTitle) pw.println(" ");
7026 pw.println("Registered ContentProviders:");
7027 printedSomething = true;
7028 printedTitle = true;
7029 }
7030 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7031 pw.println(p.toString());
7032 }
7033 }
7034
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007035 printedSomething = false;
7036 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007037 if (dumpStar || dumpPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007039 if (packageName != null && !packageName.equals(ps.realName)
7040 && !packageName.equals(ps.name)) {
7041 continue;
7042 }
7043 if (!printedSomething) {
7044 if (printedTitle) pw.println(" ");
7045 pw.println("Packages:");
7046 printedSomething = true;
7047 printedTitle = true;
7048 }
7049 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007050 pw.print(" Package [");
7051 pw.print(ps.realName != null ? ps.realName : ps.name);
7052 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007053 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7054 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007055 if (ps.realName != null) {
7056 pw.print(" compat name="); pw.println(ps.name);
7057 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007058 pw.print(" userId="); pw.print(ps.userId);
7059 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7060 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7061 pw.print(" pkg="); pw.println(ps.pkg);
7062 pw.print(" codePath="); pw.println(ps.codePathString);
7063 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007064 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007065 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007066 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007067 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007068 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007069 if (ps.pkg.mOperationPending) {
7070 pw.println(" mOperationPending=true");
7071 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007072 pw.print(" supportsScreens=[");
7073 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007074 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007075 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7076 if (!first) pw.print(", ");
7077 first = false;
7078 pw.print("small");
7079 }
7080 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007081 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007082 if (!first) pw.print(", ");
7083 first = false;
7084 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007085 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007086 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007087 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007088 if (!first) pw.print(", ");
7089 first = false;
7090 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007092 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007093 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007094 if (!first) pw.print(", ");
7095 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007096 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007098 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007099 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007100 if (!first) pw.print(", ");
7101 first = false;
7102 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007103 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007104 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007105 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7106 if (!first) pw.print(", ");
7107 first = false;
7108 pw.print("anyDensity");
7109 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007111 pw.println("]");
Kenny Root7d794fb2010-09-13 16:29:49 -07007112 pw.print(" timeStamp="); pw.println(String.valueOf(ps.timeStamp));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007113 pw.print(" signatures="); pw.println(ps.signatures);
7114 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007115 pw.print(" haveGids="); pw.println(ps.haveGids);
7116 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007117 pw.print(" installStatus="); pw.print(ps.installStatus);
7118 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 if (ps.disabledComponents.size() > 0) {
7120 pw.println(" disabledComponents:");
7121 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007122 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007123 }
7124 }
7125 if (ps.enabledComponents.size() > 0) {
7126 pw.println(" enabledComponents:");
7127 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007128 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 }
7130 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007131 if (ps.grantedPermissions.size() > 0) {
7132 pw.println(" grantedPermissions:");
7133 for (String s : ps.grantedPermissions) {
7134 pw.print(" "); pw.println(s);
7135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007136 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007137 }
7138 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007139 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007140 if (dumpStar || dumpPackages) {
7141 if (mSettings.mRenamedPackages.size() > 0) {
7142 for (HashMap.Entry<String, String> e
7143 : mSettings.mRenamedPackages.entrySet()) {
7144 if (packageName != null && !packageName.equals(e.getKey())
7145 && !packageName.equals(e.getValue())) {
7146 continue;
7147 }
7148 if (!printedSomething) {
7149 if (printedTitle) pw.println(" ");
7150 pw.println("Renamed packages:");
7151 printedSomething = true;
7152 printedTitle = true;
7153 }
7154 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7155 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007156 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007157 }
7158 printedSomething = false;
7159 if (mSettings.mDisabledSysPackages.size() > 0) {
7160 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7161 if (packageName != null && !packageName.equals(ps.realName)
7162 && !packageName.equals(ps.name)) {
7163 continue;
7164 }
7165 if (!printedSomething) {
7166 if (printedTitle) pw.println(" ");
7167 pw.println("Hidden system packages:");
7168 printedSomething = true;
7169 printedTitle = true;
7170 }
7171 pw.print(" Package [");
7172 pw.print(ps.realName != null ? ps.realName : ps.name);
7173 pw.print("] (");
7174 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7175 pw.println("):");
7176 if (ps.realName != null) {
7177 pw.print(" compat name="); pw.println(ps.name);
7178 }
7179 pw.print(" userId="); pw.println(ps.userId);
7180 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7181 pw.print(" codePath="); pw.println(ps.codePathString);
7182 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007183 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007184 }
7185 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007186 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007187 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007188 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007189 if (packageName != null && su != packageSharedUser) {
7190 continue;
7191 }
7192 if (!printedSomething) {
7193 if (printedTitle) pw.println(" ");
7194 pw.println("Shared users:");
7195 printedSomething = true;
7196 printedTitle = true;
7197 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007198 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7199 pw.print(Integer.toHexString(System.identityHashCode(su)));
7200 pw.println("):");
7201 pw.print(" userId="); pw.print(su.userId);
7202 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007203 pw.println(" grantedPermissions:");
7204 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007205 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007207 }
7208 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007209
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007210 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007211 if (printedTitle) pw.println(" ");
7212 printedTitle = true;
7213 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007214 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007215
7216 pw.println(" ");
7217 pw.println("Package warning messages:");
7218 File fname = getSettingsProblemFile();
7219 FileInputStream in;
7220 try {
7221 in = new FileInputStream(fname);
7222 int avail = in.available();
7223 byte[] data = new byte[avail];
7224 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007225 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007226 } catch (FileNotFoundException e) {
7227 } catch (IOException e) {
7228 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007230 }
7231 }
7232
7233 static final class BasePermission {
7234 final static int TYPE_NORMAL = 0;
7235 final static int TYPE_BUILTIN = 1;
7236 final static int TYPE_DYNAMIC = 2;
7237
7238 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007239 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007240 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007241 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007242 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007243 PackageParser.Permission perm;
7244 PermissionInfo pendingInfo;
7245 int uid;
7246 int[] gids;
7247
7248 BasePermission(String _name, String _sourcePackage, int _type) {
7249 name = _name;
7250 sourcePackage = _sourcePackage;
7251 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007252 // Default to most conservative protection level.
7253 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7254 }
7255
7256 public String toString() {
7257 return "BasePermission{"
7258 + Integer.toHexString(System.identityHashCode(this))
7259 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007260 }
7261 }
7262
7263 static class PackageSignatures {
7264 private Signature[] mSignatures;
7265
7266 PackageSignatures(Signature[] sigs) {
7267 assignSignatures(sigs);
7268 }
7269
7270 PackageSignatures() {
7271 }
7272
7273 void writeXml(XmlSerializer serializer, String tagName,
7274 ArrayList<Signature> pastSignatures) throws IOException {
7275 if (mSignatures == null) {
7276 return;
7277 }
7278 serializer.startTag(null, tagName);
7279 serializer.attribute(null, "count",
7280 Integer.toString(mSignatures.length));
7281 for (int i=0; i<mSignatures.length; i++) {
7282 serializer.startTag(null, "cert");
7283 final Signature sig = mSignatures[i];
7284 final int sigHash = sig.hashCode();
7285 final int numPast = pastSignatures.size();
7286 int j;
7287 for (j=0; j<numPast; j++) {
7288 Signature pastSig = pastSignatures.get(j);
7289 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7290 serializer.attribute(null, "index", Integer.toString(j));
7291 break;
7292 }
7293 }
7294 if (j >= numPast) {
7295 pastSignatures.add(sig);
7296 serializer.attribute(null, "index", Integer.toString(numPast));
7297 serializer.attribute(null, "key", sig.toCharsString());
7298 }
7299 serializer.endTag(null, "cert");
7300 }
7301 serializer.endTag(null, tagName);
7302 }
7303
7304 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7305 throws IOException, XmlPullParserException {
7306 String countStr = parser.getAttributeValue(null, "count");
7307 if (countStr == null) {
7308 reportSettingsProblem(Log.WARN,
7309 "Error in package manager settings: <signatures> has"
7310 + " no count at " + parser.getPositionDescription());
7311 XmlUtils.skipCurrentTag(parser);
7312 }
7313 final int count = Integer.parseInt(countStr);
7314 mSignatures = new Signature[count];
7315 int pos = 0;
7316
7317 int outerDepth = parser.getDepth();
7318 int type;
7319 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7320 && (type != XmlPullParser.END_TAG
7321 || parser.getDepth() > outerDepth)) {
7322 if (type == XmlPullParser.END_TAG
7323 || type == XmlPullParser.TEXT) {
7324 continue;
7325 }
7326
7327 String tagName = parser.getName();
7328 if (tagName.equals("cert")) {
7329 if (pos < count) {
7330 String index = parser.getAttributeValue(null, "index");
7331 if (index != null) {
7332 try {
7333 int idx = Integer.parseInt(index);
7334 String key = parser.getAttributeValue(null, "key");
7335 if (key == null) {
7336 if (idx >= 0 && idx < pastSignatures.size()) {
7337 Signature sig = pastSignatures.get(idx);
7338 if (sig != null) {
7339 mSignatures[pos] = pastSignatures.get(idx);
7340 pos++;
7341 } else {
7342 reportSettingsProblem(Log.WARN,
7343 "Error in package manager settings: <cert> "
7344 + "index " + index + " is not defined at "
7345 + parser.getPositionDescription());
7346 }
7347 } else {
7348 reportSettingsProblem(Log.WARN,
7349 "Error in package manager settings: <cert> "
7350 + "index " + index + " is out of bounds at "
7351 + parser.getPositionDescription());
7352 }
7353 } else {
7354 while (pastSignatures.size() <= idx) {
7355 pastSignatures.add(null);
7356 }
7357 Signature sig = new Signature(key);
7358 pastSignatures.set(idx, sig);
7359 mSignatures[pos] = sig;
7360 pos++;
7361 }
7362 } catch (NumberFormatException e) {
7363 reportSettingsProblem(Log.WARN,
7364 "Error in package manager settings: <cert> "
7365 + "index " + index + " is not a number at "
7366 + parser.getPositionDescription());
7367 }
7368 } else {
7369 reportSettingsProblem(Log.WARN,
7370 "Error in package manager settings: <cert> has"
7371 + " no index at " + parser.getPositionDescription());
7372 }
7373 } else {
7374 reportSettingsProblem(Log.WARN,
7375 "Error in package manager settings: too "
7376 + "many <cert> tags, expected " + count
7377 + " at " + parser.getPositionDescription());
7378 }
7379 } else {
7380 reportSettingsProblem(Log.WARN,
7381 "Unknown element under <cert>: "
7382 + parser.getName());
7383 }
7384 XmlUtils.skipCurrentTag(parser);
7385 }
7386
7387 if (pos < count) {
7388 // Should never happen -- there is an error in the written
7389 // settings -- but if it does we don't want to generate
7390 // a bad array.
7391 Signature[] newSigs = new Signature[pos];
7392 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7393 mSignatures = newSigs;
7394 }
7395 }
7396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007397 private void assignSignatures(Signature[] sigs) {
7398 if (sigs == null) {
7399 mSignatures = null;
7400 return;
7401 }
7402 mSignatures = new Signature[sigs.length];
7403 for (int i=0; i<sigs.length; i++) {
7404 mSignatures[i] = sigs[i];
7405 }
7406 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007408 @Override
7409 public String toString() {
7410 StringBuffer buf = new StringBuffer(128);
7411 buf.append("PackageSignatures{");
7412 buf.append(Integer.toHexString(System.identityHashCode(this)));
7413 buf.append(" [");
7414 if (mSignatures != null) {
7415 for (int i=0; i<mSignatures.length; i++) {
7416 if (i > 0) buf.append(", ");
7417 buf.append(Integer.toHexString(
7418 System.identityHashCode(mSignatures[i])));
7419 }
7420 }
7421 buf.append("]}");
7422 return buf.toString();
7423 }
7424 }
7425
7426 static class PreferredActivity extends IntentFilter {
7427 final int mMatch;
7428 final String[] mSetPackages;
7429 final String[] mSetClasses;
7430 final String[] mSetComponents;
7431 final ComponentName mActivity;
7432 final String mShortActivity;
7433 String mParseError;
7434
7435 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7436 ComponentName activity) {
7437 super(filter);
7438 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7439 mActivity = activity;
7440 mShortActivity = activity.flattenToShortString();
7441 mParseError = null;
7442 if (set != null) {
7443 final int N = set.length;
7444 String[] myPackages = new String[N];
7445 String[] myClasses = new String[N];
7446 String[] myComponents = new String[N];
7447 for (int i=0; i<N; i++) {
7448 ComponentName cn = set[i];
7449 if (cn == null) {
7450 mSetPackages = null;
7451 mSetClasses = null;
7452 mSetComponents = null;
7453 return;
7454 }
7455 myPackages[i] = cn.getPackageName().intern();
7456 myClasses[i] = cn.getClassName().intern();
7457 myComponents[i] = cn.flattenToShortString().intern();
7458 }
7459 mSetPackages = myPackages;
7460 mSetClasses = myClasses;
7461 mSetComponents = myComponents;
7462 } else {
7463 mSetPackages = null;
7464 mSetClasses = null;
7465 mSetComponents = null;
7466 }
7467 }
7468
7469 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7470 IOException {
7471 mShortActivity = parser.getAttributeValue(null, "name");
7472 mActivity = ComponentName.unflattenFromString(mShortActivity);
7473 if (mActivity == null) {
7474 mParseError = "Bad activity name " + mShortActivity;
7475 }
7476 String matchStr = parser.getAttributeValue(null, "match");
7477 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7478 String setCountStr = parser.getAttributeValue(null, "set");
7479 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7480
7481 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7482 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7483 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7484
7485 int setPos = 0;
7486
7487 int outerDepth = parser.getDepth();
7488 int type;
7489 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7490 && (type != XmlPullParser.END_TAG
7491 || parser.getDepth() > outerDepth)) {
7492 if (type == XmlPullParser.END_TAG
7493 || type == XmlPullParser.TEXT) {
7494 continue;
7495 }
7496
7497 String tagName = parser.getName();
7498 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7499 // + parser.getDepth() + " tag=" + tagName);
7500 if (tagName.equals("set")) {
7501 String name = parser.getAttributeValue(null, "name");
7502 if (name == null) {
7503 if (mParseError == null) {
7504 mParseError = "No name in set tag in preferred activity "
7505 + mShortActivity;
7506 }
7507 } else if (setPos >= setCount) {
7508 if (mParseError == null) {
7509 mParseError = "Too many set tags in preferred activity "
7510 + mShortActivity;
7511 }
7512 } else {
7513 ComponentName cn = ComponentName.unflattenFromString(name);
7514 if (cn == null) {
7515 if (mParseError == null) {
7516 mParseError = "Bad set name " + name + " in preferred activity "
7517 + mShortActivity;
7518 }
7519 } else {
7520 myPackages[setPos] = cn.getPackageName();
7521 myClasses[setPos] = cn.getClassName();
7522 myComponents[setPos] = name;
7523 setPos++;
7524 }
7525 }
7526 XmlUtils.skipCurrentTag(parser);
7527 } else if (tagName.equals("filter")) {
7528 //Log.i(TAG, "Starting to parse filter...");
7529 readFromXml(parser);
7530 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7531 // + parser.getDepth() + " tag=" + parser.getName());
7532 } else {
7533 reportSettingsProblem(Log.WARN,
7534 "Unknown element under <preferred-activities>: "
7535 + parser.getName());
7536 XmlUtils.skipCurrentTag(parser);
7537 }
7538 }
7539
7540 if (setPos != setCount) {
7541 if (mParseError == null) {
7542 mParseError = "Not enough set tags (expected " + setCount
7543 + " but found " + setPos + ") in " + mShortActivity;
7544 }
7545 }
7546
7547 mSetPackages = myPackages;
7548 mSetClasses = myClasses;
7549 mSetComponents = myComponents;
7550 }
7551
7552 public void writeToXml(XmlSerializer serializer) throws IOException {
7553 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7554 serializer.attribute(null, "name", mShortActivity);
7555 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7556 serializer.attribute(null, "set", Integer.toString(NS));
7557 for (int s=0; s<NS; s++) {
7558 serializer.startTag(null, "set");
7559 serializer.attribute(null, "name", mSetComponents[s]);
7560 serializer.endTag(null, "set");
7561 }
7562 serializer.startTag(null, "filter");
7563 super.writeToXml(serializer);
7564 serializer.endTag(null, "filter");
7565 }
7566
7567 boolean sameSet(List<ResolveInfo> query, int priority) {
7568 if (mSetPackages == null) return false;
7569 final int NQ = query.size();
7570 final int NS = mSetPackages.length;
7571 int numMatch = 0;
7572 for (int i=0; i<NQ; i++) {
7573 ResolveInfo ri = query.get(i);
7574 if (ri.priority != priority) continue;
7575 ActivityInfo ai = ri.activityInfo;
7576 boolean good = false;
7577 for (int j=0; j<NS; j++) {
7578 if (mSetPackages[j].equals(ai.packageName)
7579 && mSetClasses[j].equals(ai.name)) {
7580 numMatch++;
7581 good = true;
7582 break;
7583 }
7584 }
7585 if (!good) return false;
7586 }
7587 return numMatch == NS;
7588 }
7589 }
7590
7591 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007592 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 HashSet<String> grantedPermissions = new HashSet<String>();
7595 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007597 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007598 setFlags(pkgFlags);
7599 }
7600
7601 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007602 this.pkgFlags = pkgFlags & (
7603 ApplicationInfo.FLAG_SYSTEM |
7604 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007605 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007606 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607 }
7608 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007609
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007610 /**
7611 * Settings base class for pending and resolved classes.
7612 */
7613 static class PackageSettingBase extends GrantedPermissions {
7614 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007615 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007616 File codePath;
7617 String codePathString;
7618 File resourcePath;
7619 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007620 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007621 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007622 long timeStamp;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007623 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007624
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007625 boolean uidError;
7626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007627 PackageSignatures signatures = new PackageSignatures();
7628
7629 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007630 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 /* Explicitly disabled components */
7633 HashSet<String> disabledComponents = new HashSet<String>(0);
7634 /* Explicitly enabled components */
7635 HashSet<String> enabledComponents = new HashSet<String>(0);
7636 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7637 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007638
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007639 PackageSettingBase origPackage;
7640
Jacek Surazski65e13172009-04-28 15:26:38 +02007641 /* package name of the app that installed this package */
7642 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007644 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007645 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646 super(pkgFlags);
7647 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007648 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007649 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007650 }
7651
Kenny Root806cc132010-09-12 08:34:19 -07007652 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7653 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007654 this.codePath = codePath;
7655 this.codePathString = codePath.toString();
7656 this.resourcePath = resourcePath;
7657 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007658 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007659 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007660 }
Kenny Root85387d72010-08-26 10:13:11 -07007661
Jacek Surazski65e13172009-04-28 15:26:38 +02007662 public void setInstallerPackageName(String packageName) {
7663 installerPackageName = packageName;
7664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007665
Jacek Surazski65e13172009-04-28 15:26:38 +02007666 String getInstallerPackageName() {
7667 return installerPackageName;
7668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 public void setInstallStatus(int newStatus) {
7671 installStatus = newStatus;
7672 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007674 public int getInstallStatus() {
7675 return installStatus;
7676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007678 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007680 }
7681
7682 public void copyFrom(PackageSettingBase base) {
7683 grantedPermissions = base.grantedPermissions;
7684 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007686 timeStamp = base.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007687 signatures = base.signatures;
7688 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007689 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 disabledComponents = base.disabledComponents;
7691 enabledComponents = base.enabledComponents;
7692 enabled = base.enabled;
7693 installStatus = base.installStatus;
7694 }
7695
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007696 boolean enableComponentLP(String componentClassName) {
7697 boolean changed = disabledComponents.remove(componentClassName);
7698 changed |= enabledComponents.add(componentClassName);
7699 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007700 }
7701
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007702 boolean disableComponentLP(String componentClassName) {
7703 boolean changed = enabledComponents.remove(componentClassName);
7704 changed |= disabledComponents.add(componentClassName);
7705 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007706 }
7707
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007708 boolean restoreComponentLP(String componentClassName) {
7709 boolean changed = enabledComponents.remove(componentClassName);
7710 changed |= disabledComponents.remove(componentClassName);
7711 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 }
7713
7714 int currentEnabledStateLP(String componentName) {
7715 if (enabledComponents.contains(componentName)) {
7716 return COMPONENT_ENABLED_STATE_ENABLED;
7717 } else if (disabledComponents.contains(componentName)) {
7718 return COMPONENT_ENABLED_STATE_DISABLED;
7719 } else {
7720 return COMPONENT_ENABLED_STATE_DEFAULT;
7721 }
7722 }
7723 }
7724
7725 /**
7726 * Settings data for a particular package we know about.
7727 */
7728 static final class PackageSetting extends PackageSettingBase {
7729 int userId;
7730 PackageParser.Package pkg;
7731 SharedUserSetting sharedUser;
7732
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007733 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007734 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7735 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7736 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 @Override
7740 public String toString() {
7741 return "PackageSetting{"
7742 + Integer.toHexString(System.identityHashCode(this))
7743 + " " + name + "/" + userId + "}";
7744 }
7745 }
7746
7747 /**
7748 * Settings data for a particular shared user ID we know about.
7749 */
7750 static final class SharedUserSetting extends GrantedPermissions {
7751 final String name;
7752 int userId;
7753 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7754 final PackageSignatures signatures = new PackageSignatures();
7755
7756 SharedUserSetting(String _name, int _pkgFlags) {
7757 super(_pkgFlags);
7758 name = _name;
7759 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 @Override
7762 public String toString() {
7763 return "SharedUserSetting{"
7764 + Integer.toHexString(System.identityHashCode(this))
7765 + " " + name + "/" + userId + "}";
7766 }
7767 }
7768
7769 /**
7770 * Holds information about dynamic settings.
7771 */
7772 private static final class Settings {
7773 private final File mSettingsFilename;
7774 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007775 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007776 private final HashMap<String, PackageSetting> mPackages =
7777 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007778 // List of replaced system applications
7779 final HashMap<String, PackageSetting> mDisabledSysPackages =
7780 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007781
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007782 // These are the last platform API version we were using for
7783 // the apps installed on internal and external storage. It is
7784 // used to grant newer permissions one time during a system upgrade.
7785 int mInternalSdkPlatform;
7786 int mExternalSdkPlatform;
7787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007788 // The user's preferred activities associated with particular intent
7789 // filters.
7790 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7791 new IntentResolver<PreferredActivity, PreferredActivity>() {
7792 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007793 protected String packageForFilter(PreferredActivity filter) {
7794 return filter.mActivity.getPackageName();
7795 }
7796 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007797 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007798 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007799 out.print(prefix); out.print(
7800 Integer.toHexString(System.identityHashCode(filter)));
7801 out.print(' ');
7802 out.print(filter.mActivity.flattenToShortString());
7803 out.print(" match=0x");
7804 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007806 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007808 out.print(prefix); out.print(" ");
7809 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007810 }
7811 }
7812 }
7813 };
7814 private final HashMap<String, SharedUserSetting> mSharedUsers =
7815 new HashMap<String, SharedUserSetting>();
7816 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7817 private final SparseArray<Object> mOtherUserIds =
7818 new SparseArray<Object>();
7819
7820 // For reading/writing settings file.
7821 private final ArrayList<Signature> mPastSignatures =
7822 new ArrayList<Signature>();
7823
7824 // Mapping from permission names to info about them.
7825 final HashMap<String, BasePermission> mPermissions =
7826 new HashMap<String, BasePermission>();
7827
7828 // Mapping from permission tree names to info about them.
7829 final HashMap<String, BasePermission> mPermissionTrees =
7830 new HashMap<String, BasePermission>();
7831
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007832 // Packages that have been uninstalled and still need their external
7833 // storage data deleted.
7834 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7835
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007836 // Packages that have been renamed since they were first installed.
7837 // Keys are the new names of the packages, values are the original
7838 // names. The packages appear everwhere else under their original
7839 // names.
7840 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 private final StringBuilder mReadMessages = new StringBuilder();
7843
7844 private static final class PendingPackage extends PackageSettingBase {
7845 final int sharedId;
7846
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007847 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007848 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7849 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7850 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 this.sharedId = sharedId;
7852 }
7853 }
7854 private final ArrayList<PendingPackage> mPendingPackages
7855 = new ArrayList<PendingPackage>();
7856
7857 Settings() {
7858 File dataDir = Environment.getDataDirectory();
7859 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007860 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7861 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007863 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007864 FileUtils.setPermissions(systemDir.toString(),
7865 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7866 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7867 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007868 FileUtils.setPermissions(systemSecureDir.toString(),
7869 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7870 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7871 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 mSettingsFilename = new File(systemDir, "packages.xml");
7873 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007874 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007875 }
7876
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007877 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007878 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007879 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007880 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007881 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007882 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 return p;
7884 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007885
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007886 PackageSetting peekPackageLP(String name) {
7887 return mPackages.get(name);
7888 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 PackageSetting p = mPackages.get(name);
7890 if (p != null && p.codePath.getPath().equals(codePath)) {
7891 return p;
7892 }
7893 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007894 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 void setInstallStatus(String pkgName, int status) {
7898 PackageSetting p = mPackages.get(pkgName);
7899 if(p != null) {
7900 if(p.getInstallStatus() != status) {
7901 p.setInstallStatus(status);
7902 }
7903 }
7904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007905
Jacek Surazski65e13172009-04-28 15:26:38 +02007906 void setInstallerPackageName(String pkgName,
7907 String installerPkgName) {
7908 PackageSetting p = mPackages.get(pkgName);
7909 if(p != null) {
7910 p.setInstallerPackageName(installerPkgName);
7911 }
7912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007913
Jacek Surazski65e13172009-04-28 15:26:38 +02007914 String getInstallerPackageName(String pkgName) {
7915 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007916 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007917 }
7918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007919 int getInstallStatus(String pkgName) {
7920 PackageSetting p = mPackages.get(pkgName);
7921 if(p != null) {
7922 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007924 return -1;
7925 }
7926
7927 SharedUserSetting getSharedUserLP(String name,
7928 int pkgFlags, boolean create) {
7929 SharedUserSetting s = mSharedUsers.get(name);
7930 if (s == null) {
7931 if (!create) {
7932 return null;
7933 }
7934 s = new SharedUserSetting(name, pkgFlags);
7935 if (MULTIPLE_APPLICATION_UIDS) {
7936 s.userId = newUserIdLP(s);
7937 } else {
7938 s.userId = FIRST_APPLICATION_UID;
7939 }
7940 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7941 // < 0 means we couldn't assign a userid; fall out and return
7942 // s, which is currently null
7943 if (s.userId >= 0) {
7944 mSharedUsers.put(name, s);
7945 }
7946 }
7947
7948 return s;
7949 }
7950
7951 int disableSystemPackageLP(String name) {
7952 PackageSetting p = mPackages.get(name);
7953 if(p == null) {
7954 Log.w(TAG, "Package:"+name+" is not an installed package");
7955 return -1;
7956 }
7957 PackageSetting dp = mDisabledSysPackages.get(name);
7958 // always make sure the system package code and resource paths dont change
7959 if(dp == null) {
7960 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7961 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7962 }
7963 mDisabledSysPackages.put(name, p);
7964 }
7965 return removePackageLP(name);
7966 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 PackageSetting enableSystemPackageLP(String name) {
7969 PackageSetting p = mDisabledSysPackages.get(name);
7970 if(p == null) {
7971 Log.w(TAG, "Package:"+name+" is not disabled");
7972 return null;
7973 }
7974 // Reset flag in ApplicationInfo object
7975 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7976 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7977 }
Kenny Root806cc132010-09-12 08:34:19 -07007978 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
7979 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007980 mDisabledSysPackages.remove(name);
7981 return ret;
7982 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007983
Kenny Root806cc132010-09-12 08:34:19 -07007984 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
7985 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 PackageSetting p = mPackages.get(name);
7987 if (p != null) {
7988 if (p.userId == uid) {
7989 return p;
7990 }
7991 reportSettingsProblem(Log.ERROR,
7992 "Adding duplicate package, keeping first: " + name);
7993 return null;
7994 }
Kenny Root806cc132010-09-12 08:34:19 -07007995 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
7996 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007997 p.userId = uid;
7998 if (addUserIdLP(uid, p, name)) {
7999 mPackages.put(name, p);
8000 return p;
8001 }
8002 return null;
8003 }
8004
8005 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8006 SharedUserSetting s = mSharedUsers.get(name);
8007 if (s != null) {
8008 if (s.userId == uid) {
8009 return s;
8010 }
8011 reportSettingsProblem(Log.ERROR,
8012 "Adding duplicate shared user, keeping first: " + name);
8013 return null;
8014 }
8015 s = new SharedUserSetting(name, pkgFlags);
8016 s.userId = uid;
8017 if (addUserIdLP(uid, s, name)) {
8018 mSharedUsers.put(name, s);
8019 return s;
8020 }
8021 return null;
8022 }
8023
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008024 // Transfer ownership of permissions from one package to another.
8025 private void transferPermissions(String origPkg, String newPkg) {
8026 // Transfer ownership of permissions to the new package.
8027 for (int i=0; i<2; i++) {
8028 HashMap<String, BasePermission> permissions =
8029 i == 0 ? mPermissionTrees : mPermissions;
8030 for (BasePermission bp : permissions.values()) {
8031 if (origPkg.equals(bp.sourcePackage)) {
8032 if (DEBUG_UPGRADE) Log.v(TAG,
8033 "Moving permission " + bp.name
8034 + " from pkg " + bp.sourcePackage
8035 + " to " + newPkg);
8036 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008037 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008038 bp.perm = null;
8039 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008040 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008041 }
8042 bp.uid = 0;
8043 bp.gids = null;
8044 }
8045 }
8046 }
8047 }
8048
8049 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008050 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008051 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008052 PackageSetting p = mPackages.get(name);
8053 if (p != null) {
8054 if (!p.codePath.equals(codePath)) {
8055 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008056 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008057 // This is an updated system app with versions in both system
8058 // and data partition. Just let the most recent version
8059 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008060 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008061 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008062 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008063 // Just a change in the code path is not an issue, but
8064 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008065 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008066 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008067 /*
8068 * Since we've changed paths, we need to prefer the new
8069 * native library path over the one stored in the
8070 * package settings since we might have moved from
8071 * internal to external storage or vice versa.
8072 */
8073 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008075 }
8076 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008077 reportSettingsProblem(Log.WARN,
8078 "Package " + name + " shared user changed from "
8079 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8080 + " to "
8081 + (sharedUser != null ? sharedUser.name : "<nothing>")
8082 + "; replacing with new");
8083 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008084 } else {
8085 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8086 // If what we are scanning is a system package, then
8087 // make it so, regardless of whether it was previously
8088 // installed only in the data partition.
8089 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008091 }
8092 }
8093 if (p == null) {
8094 // Create a new PackageSettings entry. this can end up here because
8095 // of code path mismatch or user id mismatch of an updated system partition
8096 if (!create) {
8097 return null;
8098 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008099 if (origPackage != null) {
8100 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008101 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8102 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008103 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8104 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008105 // Note that we will retain the new package's signature so
8106 // that we can keep its data.
8107 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008108 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008109 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008110 p.sharedUser = origPackage.sharedUser;
8111 p.userId = origPackage.userId;
8112 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008113 mRenamedPackages.put(name, origPackage.name);
8114 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008115 // Update new package state.
8116 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008118 p = new PackageSetting(name, realName, codePath, resourcePath,
8119 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008120 p.setTimeStamp(codePath.lastModified());
8121 p.sharedUser = sharedUser;
8122 if (sharedUser != null) {
8123 p.userId = sharedUser.userId;
8124 } else if (MULTIPLE_APPLICATION_UIDS) {
8125 // Clone the setting here for disabled system packages
8126 PackageSetting dis = mDisabledSysPackages.get(name);
8127 if (dis != null) {
8128 // For disabled packages a new setting is created
8129 // from the existing user id. This still has to be
8130 // added to list of user id's
8131 // Copy signatures from previous setting
8132 if (dis.signatures.mSignatures != null) {
8133 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8134 }
8135 p.userId = dis.userId;
8136 // Clone permissions
8137 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008138 // Clone component info
8139 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8140 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8141 // Add new setting to list of user ids
8142 addUserIdLP(p.userId, p, name);
8143 } else {
8144 // Assign new user id
8145 p.userId = newUserIdLP(p);
8146 }
8147 } else {
8148 p.userId = FIRST_APPLICATION_UID;
8149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 }
8151 if (p.userId < 0) {
8152 reportSettingsProblem(Log.WARN,
8153 "Package " + name + " could not be assigned a valid uid");
8154 return null;
8155 }
8156 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008157 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008159 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008160 }
8161 }
8162 return p;
8163 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008164
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008165 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008166 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008167 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008168 final String codePath = pkg.applicationInfo.sourceDir;
8169 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008170 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008171 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008172 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008173 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008174 p.codePath = new File(codePath);
8175 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008176 }
8177 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008178 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008179 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008180 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008181 p.resourcePath = new File(resourcePath);
8182 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008183 }
Kenny Root85387d72010-08-26 10:13:11 -07008184 // Update the native library path if needed
8185 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8186 if (nativeLibraryPath != null
8187 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8188 p.nativeLibraryPathString = nativeLibraryPath;
8189 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008190 // Update version code if needed
8191 if (pkg.mVersionCode != p.versionCode) {
8192 p.versionCode = pkg.mVersionCode;
8193 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008194 // Update signatures if needed.
8195 if (p.signatures.mSignatures == null) {
8196 p.signatures.assignSignatures(pkg.mSignatures);
8197 }
8198 // If this app defines a shared user id initialize
8199 // the shared user signatures as well.
8200 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8201 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8202 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008203 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8204 }
8205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008206 // Utility method that adds a PackageSetting to mPackages and
8207 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008208 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008209 SharedUserSetting sharedUser) {
8210 mPackages.put(name, p);
8211 if (sharedUser != null) {
8212 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8213 reportSettingsProblem(Log.ERROR,
8214 "Package " + p.name + " was user "
8215 + p.sharedUser + " but is now " + sharedUser
8216 + "; I am not changing its files so it will probably fail!");
8217 p.sharedUser.packages.remove(p);
8218 } else if (p.userId != sharedUser.userId) {
8219 reportSettingsProblem(Log.ERROR,
8220 "Package " + p.name + " was user id " + p.userId
8221 + " but is now user " + sharedUser
8222 + " with id " + sharedUser.userId
8223 + "; I am not changing its files so it will probably fail!");
8224 }
8225
8226 sharedUser.packages.add(p);
8227 p.sharedUser = sharedUser;
8228 p.userId = sharedUser.userId;
8229 }
8230 }
8231
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008232 /*
8233 * Update the shared user setting when a package using
8234 * specifying the shared user id is removed. The gids
8235 * associated with each permission of the deleted package
8236 * are removed from the shared user's gid list only if its
8237 * not in use by other permissions of packages in the
8238 * shared user setting.
8239 */
8240 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008241 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008242 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008243 return;
8244 }
8245 // No sharedUserId
8246 if (deletedPs.sharedUser == null) {
8247 return;
8248 }
8249 SharedUserSetting sus = deletedPs.sharedUser;
8250 // Update permissions
8251 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8252 boolean used = false;
8253 if (!sus.grantedPermissions.contains (eachPerm)) {
8254 continue;
8255 }
8256 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008257 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008258 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008259 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008260 used = true;
8261 break;
8262 }
8263 }
8264 if (!used) {
8265 // can safely delete this permission from list
8266 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 }
8268 }
8269 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008270 int newGids[] = globalGids;
8271 for (String eachPerm : sus.grantedPermissions) {
8272 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008273 if (bp != null) {
8274 newGids = appendInts(newGids, bp.gids);
8275 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008276 }
8277 sus.gids = newGids;
8278 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 private int removePackageLP(String name) {
8281 PackageSetting p = mPackages.get(name);
8282 if (p != null) {
8283 mPackages.remove(name);
8284 if (p.sharedUser != null) {
8285 p.sharedUser.packages.remove(p);
8286 if (p.sharedUser.packages.size() == 0) {
8287 mSharedUsers.remove(p.sharedUser.name);
8288 removeUserIdLP(p.sharedUser.userId);
8289 return p.sharedUser.userId;
8290 }
8291 } else {
8292 removeUserIdLP(p.userId);
8293 return p.userId;
8294 }
8295 }
8296 return -1;
8297 }
8298
8299 private boolean addUserIdLP(int uid, Object obj, Object name) {
8300 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8301 return false;
8302 }
8303
8304 if (uid >= FIRST_APPLICATION_UID) {
8305 int N = mUserIds.size();
8306 final int index = uid - FIRST_APPLICATION_UID;
8307 while (index >= N) {
8308 mUserIds.add(null);
8309 N++;
8310 }
8311 if (mUserIds.get(index) != null) {
8312 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008313 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008314 + " name=" + name);
8315 return false;
8316 }
8317 mUserIds.set(index, obj);
8318 } else {
8319 if (mOtherUserIds.get(uid) != null) {
8320 reportSettingsProblem(Log.ERROR,
8321 "Adding duplicate shared id: " + uid
8322 + " name=" + name);
8323 return false;
8324 }
8325 mOtherUserIds.put(uid, obj);
8326 }
8327 return true;
8328 }
8329
8330 public Object getUserIdLP(int uid) {
8331 if (uid >= FIRST_APPLICATION_UID) {
8332 int N = mUserIds.size();
8333 final int index = uid - FIRST_APPLICATION_UID;
8334 return index < N ? mUserIds.get(index) : null;
8335 } else {
8336 return mOtherUserIds.get(uid);
8337 }
8338 }
8339
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008340 private Set<String> findPackagesWithFlag(int flag) {
8341 Set<String> ret = new HashSet<String>();
8342 for (PackageSetting ps : mPackages.values()) {
8343 // Has to match atleast all the flag bits set on flag
8344 if ((ps.pkgFlags & flag) == flag) {
8345 ret.add(ps.name);
8346 }
8347 }
8348 return ret;
8349 }
8350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008351 private void removeUserIdLP(int uid) {
8352 if (uid >= FIRST_APPLICATION_UID) {
8353 int N = mUserIds.size();
8354 final int index = uid - FIRST_APPLICATION_UID;
8355 if (index < N) mUserIds.set(index, null);
8356 } else {
8357 mOtherUserIds.remove(uid);
8358 }
8359 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361 void writeLP() {
8362 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8363
8364 // Keep the old settings around until we know the new ones have
8365 // been successfully written.
8366 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008367 // Presence of backup settings file indicates that we failed
8368 // to persist settings earlier. So preserve the older
8369 // backup for future reference since the current settings
8370 // might have been corrupted.
8371 if (!mBackupSettingsFilename.exists()) {
8372 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008373 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008374 return;
8375 }
8376 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008377 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008378 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008380 }
8381
8382 mPastSignatures.clear();
8383
8384 try {
Kenny Root9f306d72010-09-26 11:19:47 -07008385 BufferedOutputStream str = new BufferedOutputStream(new FileOutputStream(
8386 mSettingsFilename));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008387
8388 //XmlSerializer serializer = XmlUtils.serializerInstance();
8389 XmlSerializer serializer = new FastXmlSerializer();
8390 serializer.setOutput(str, "utf-8");
8391 serializer.startDocument(null, true);
8392 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8393
8394 serializer.startTag(null, "packages");
8395
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008396 serializer.startTag(null, "last-platform-version");
8397 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8398 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8399 serializer.endTag(null, "last-platform-version");
8400
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008401 serializer.startTag(null, "permission-trees");
8402 for (BasePermission bp : mPermissionTrees.values()) {
8403 writePermission(serializer, bp);
8404 }
8405 serializer.endTag(null, "permission-trees");
8406
8407 serializer.startTag(null, "permissions");
8408 for (BasePermission bp : mPermissions.values()) {
8409 writePermission(serializer, bp);
8410 }
8411 serializer.endTag(null, "permissions");
8412
8413 for (PackageSetting pkg : mPackages.values()) {
8414 writePackage(serializer, pkg);
8415 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008417 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8418 writeDisabledSysPackage(serializer, pkg);
8419 }
8420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008421 serializer.startTag(null, "preferred-activities");
8422 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8423 serializer.startTag(null, "item");
8424 pa.writeToXml(serializer);
8425 serializer.endTag(null, "item");
8426 }
8427 serializer.endTag(null, "preferred-activities");
8428
8429 for (SharedUserSetting usr : mSharedUsers.values()) {
8430 serializer.startTag(null, "shared-user");
8431 serializer.attribute(null, "name", usr.name);
8432 serializer.attribute(null, "userId",
8433 Integer.toString(usr.userId));
8434 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8435 serializer.startTag(null, "perms");
8436 for (String name : usr.grantedPermissions) {
8437 serializer.startTag(null, "item");
8438 serializer.attribute(null, "name", name);
8439 serializer.endTag(null, "item");
8440 }
8441 serializer.endTag(null, "perms");
8442 serializer.endTag(null, "shared-user");
8443 }
8444
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008445 if (mPackagesToBeCleaned.size() > 0) {
8446 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8447 serializer.startTag(null, "cleaning-package");
8448 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8449 serializer.endTag(null, "cleaning-package");
8450 }
8451 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008452
8453 if (mRenamedPackages.size() > 0) {
8454 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8455 serializer.startTag(null, "renamed-package");
8456 serializer.attribute(null, "new", e.getKey());
8457 serializer.attribute(null, "old", e.getValue());
8458 serializer.endTag(null, "renamed-package");
8459 }
8460 }
8461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008462 serializer.endTag(null, "packages");
8463
8464 serializer.endDocument();
8465
8466 str.flush();
8467 str.close();
8468
8469 // New settings successfully written, old ones are no longer
8470 // needed.
8471 mBackupSettingsFilename.delete();
8472 FileUtils.setPermissions(mSettingsFilename.toString(),
8473 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8474 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8475 |FileUtils.S_IROTH,
8476 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008477
8478 // Write package list file now, use a JournaledFile.
8479 //
8480 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8481 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8482
Kenny Root9f306d72010-09-26 11:19:47 -07008483 str = new BufferedOutputStream(new FileOutputStream(journal.chooseForWrite()));
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008484 try {
8485 StringBuilder sb = new StringBuilder();
8486 for (PackageSetting pkg : mPackages.values()) {
8487 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008488 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008489 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8490
8491 // Avoid any application that has a space in its path
8492 // or that is handled by the system.
8493 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8494 continue;
8495
8496 // we store on each line the following information for now:
8497 //
8498 // pkgName - package name
8499 // userId - application-specific user id
8500 // debugFlag - 0 or 1 if the package is debuggable.
8501 // dataPath - path to package's data path
8502 //
8503 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8504 //
8505 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8506 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8507 // system/core/run-as/run-as.c
8508 //
8509 sb.setLength(0);
8510 sb.append(ai.packageName);
8511 sb.append(" ");
8512 sb.append((int)ai.uid);
8513 sb.append(isDebug ? " 1 " : " 0 ");
8514 sb.append(dataPath);
8515 sb.append("\n");
8516 str.write(sb.toString().getBytes());
8517 }
8518 str.flush();
8519 str.close();
8520 journal.commit();
8521 }
8522 catch (Exception e) {
8523 journal.rollback();
8524 }
8525
8526 FileUtils.setPermissions(mPackageListFilename.toString(),
8527 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8528 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8529 |FileUtils.S_IROTH,
8530 -1, -1);
8531
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008532 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533
8534 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008535 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 -08008536 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008537 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 -08008538 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008539 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008540 if (mSettingsFilename.exists()) {
8541 if (!mSettingsFilename.delete()) {
8542 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8543 }
8544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008545 //Debug.stopMethodTracing();
8546 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008547
8548 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008549 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550 serializer.startTag(null, "updated-package");
8551 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008552 if (pkg.realName != null) {
8553 serializer.attribute(null, "realName", pkg.realName);
8554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008555 serializer.attribute(null, "codePath", pkg.codePathString);
Kenny Root7d794fb2010-09-13 16:29:49 -07008556 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008557 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008558 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8559 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8560 }
Kenny Root85387d72010-08-26 10:13:11 -07008561 if (pkg.nativeLibraryPathString != null) {
8562 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 if (pkg.sharedUser == null) {
8565 serializer.attribute(null, "userId",
8566 Integer.toString(pkg.userId));
8567 } else {
8568 serializer.attribute(null, "sharedUserId",
8569 Integer.toString(pkg.userId));
8570 }
8571 serializer.startTag(null, "perms");
8572 if (pkg.sharedUser == null) {
8573 // If this is a shared user, the permissions will
8574 // be written there. We still need to write an
8575 // empty permissions list so permissionsFixed will
8576 // be set.
8577 for (final String name : pkg.grantedPermissions) {
8578 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008579 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008580 // We only need to write signature or system permissions but this wont
8581 // match the semantics of grantedPermissions. So write all permissions.
8582 serializer.startTag(null, "item");
8583 serializer.attribute(null, "name", name);
8584 serializer.endTag(null, "item");
8585 }
8586 }
8587 }
8588 serializer.endTag(null, "perms");
8589 serializer.endTag(null, "updated-package");
8590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008591
8592 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008593 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008594 serializer.startTag(null, "package");
8595 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008596 if (pkg.realName != null) {
8597 serializer.attribute(null, "realName", pkg.realName);
8598 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008599 serializer.attribute(null, "codePath", pkg.codePathString);
8600 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8601 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8602 }
Kenny Root85387d72010-08-26 10:13:11 -07008603 if (pkg.nativeLibraryPathString != null) {
8604 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8605 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008606 serializer.attribute(null, "flags",
8607 Integer.toString(pkg.pkgFlags));
Kenny Root7d794fb2010-09-13 16:29:49 -07008608 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008609 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008610 if (pkg.sharedUser == null) {
8611 serializer.attribute(null, "userId",
8612 Integer.toString(pkg.userId));
8613 } else {
8614 serializer.attribute(null, "sharedUserId",
8615 Integer.toString(pkg.userId));
8616 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008617 if (pkg.uidError) {
8618 serializer.attribute(null, "uidError", "true");
8619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008620 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8621 serializer.attribute(null, "enabled",
8622 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8623 ? "true" : "false");
8624 }
8625 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8626 serializer.attribute(null, "installStatus", "false");
8627 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008628 if (pkg.installerPackageName != null) {
8629 serializer.attribute(null, "installer", pkg.installerPackageName);
8630 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008631 if (pkg.obbPathString != null) {
8632 serializer.attribute(null, "obbPath", pkg.obbPathString);
8633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8635 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
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 serializer.startTag(null, "item");
8644 serializer.attribute(null, "name", name);
8645 serializer.endTag(null, "item");
8646 }
8647 }
8648 serializer.endTag(null, "perms");
8649 }
8650 if (pkg.disabledComponents.size() > 0) {
8651 serializer.startTag(null, "disabled-components");
8652 for (final String name : pkg.disabledComponents) {
8653 serializer.startTag(null, "item");
8654 serializer.attribute(null, "name", name);
8655 serializer.endTag(null, "item");
8656 }
8657 serializer.endTag(null, "disabled-components");
8658 }
8659 if (pkg.enabledComponents.size() > 0) {
8660 serializer.startTag(null, "enabled-components");
8661 for (final String name : pkg.enabledComponents) {
8662 serializer.startTag(null, "item");
8663 serializer.attribute(null, "name", name);
8664 serializer.endTag(null, "item");
8665 }
8666 serializer.endTag(null, "enabled-components");
8667 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008669 serializer.endTag(null, "package");
8670 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008671
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008672 void writePermission(XmlSerializer serializer, BasePermission bp)
8673 throws XmlPullParserException, java.io.IOException {
8674 if (bp.type != BasePermission.TYPE_BUILTIN
8675 && bp.sourcePackage != null) {
8676 serializer.startTag(null, "item");
8677 serializer.attribute(null, "name", bp.name);
8678 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008679 if (bp.protectionLevel !=
8680 PermissionInfo.PROTECTION_NORMAL) {
8681 serializer.attribute(null, "protection",
8682 Integer.toString(bp.protectionLevel));
8683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008684 if (DEBUG_SETTINGS) Log.v(TAG,
8685 "Writing perm: name=" + bp.name + " type=" + bp.type);
8686 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8687 PermissionInfo pi = bp.perm != null ? bp.perm.info
8688 : bp.pendingInfo;
8689 if (pi != null) {
8690 serializer.attribute(null, "type", "dynamic");
8691 if (pi.icon != 0) {
8692 serializer.attribute(null, "icon",
8693 Integer.toString(pi.icon));
8694 }
8695 if (pi.nonLocalizedLabel != null) {
8696 serializer.attribute(null, "label",
8697 pi.nonLocalizedLabel.toString());
8698 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008699 }
8700 }
8701 serializer.endTag(null, "item");
8702 }
8703 }
8704
8705 String getReadMessagesLP() {
8706 return mReadMessages.toString();
8707 }
8708
Oscar Montemayora8529f62009-11-18 10:14:20 -08008709 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8711 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008712 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008713 while(its.hasNext()) {
8714 String key = its.next();
8715 PackageSetting ps = mPackages.get(key);
8716 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008717 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008718 }
8719 }
8720 return ret;
8721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008723 boolean readLP() {
8724 FileInputStream str = null;
8725 if (mBackupSettingsFilename.exists()) {
8726 try {
8727 str = new FileInputStream(mBackupSettingsFilename);
8728 mReadMessages.append("Reading from backup settings file\n");
8729 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008730 if (mSettingsFilename.exists()) {
8731 // If both the backup and settings file exist, we
8732 // ignore the settings since it might have been
8733 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008734 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008735 mSettingsFilename.delete();
8736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 } catch (java.io.IOException e) {
8738 // We'll try for the normal settings file.
8739 }
8740 }
8741
8742 mPastSignatures.clear();
8743
8744 try {
8745 if (str == null) {
8746 if (!mSettingsFilename.exists()) {
8747 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008748 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749 return false;
8750 }
8751 str = new FileInputStream(mSettingsFilename);
8752 }
8753 XmlPullParser parser = Xml.newPullParser();
8754 parser.setInput(str, null);
8755
8756 int type;
8757 while ((type=parser.next()) != XmlPullParser.START_TAG
8758 && type != XmlPullParser.END_DOCUMENT) {
8759 ;
8760 }
8761
8762 if (type != XmlPullParser.START_TAG) {
8763 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008764 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008765 return false;
8766 }
8767
8768 int outerDepth = parser.getDepth();
8769 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8770 && (type != XmlPullParser.END_TAG
8771 || parser.getDepth() > outerDepth)) {
8772 if (type == XmlPullParser.END_TAG
8773 || type == XmlPullParser.TEXT) {
8774 continue;
8775 }
8776
8777 String tagName = parser.getName();
8778 if (tagName.equals("package")) {
8779 readPackageLP(parser);
8780 } else if (tagName.equals("permissions")) {
8781 readPermissionsLP(mPermissions, parser);
8782 } else if (tagName.equals("permission-trees")) {
8783 readPermissionsLP(mPermissionTrees, parser);
8784 } else if (tagName.equals("shared-user")) {
8785 readSharedUserLP(parser);
8786 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008787 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 } else if (tagName.equals("preferred-activities")) {
8789 readPreferredActivitiesLP(parser);
8790 } else if(tagName.equals("updated-package")) {
8791 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008792 } else if (tagName.equals("cleaning-package")) {
8793 String name = parser.getAttributeValue(null, "name");
8794 if (name != null) {
8795 mPackagesToBeCleaned.add(name);
8796 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008797 } else if (tagName.equals("renamed-package")) {
8798 String nname = parser.getAttributeValue(null, "new");
8799 String oname = parser.getAttributeValue(null, "old");
8800 if (nname != null && oname != null) {
8801 mRenamedPackages.put(nname, oname);
8802 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008803 } else if (tagName.equals("last-platform-version")) {
8804 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8805 try {
8806 String internal = parser.getAttributeValue(null, "internal");
8807 if (internal != null) {
8808 mInternalSdkPlatform = Integer.parseInt(internal);
8809 }
8810 String external = parser.getAttributeValue(null, "external");
8811 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008812 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008813 }
8814 } catch (NumberFormatException e) {
8815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008816 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008817 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008818 + parser.getName());
8819 XmlUtils.skipCurrentTag(parser);
8820 }
8821 }
8822
8823 str.close();
8824
8825 } catch(XmlPullParserException e) {
8826 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008827 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008828
8829 } catch(java.io.IOException e) {
8830 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008831 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008832
8833 }
8834
8835 int N = mPendingPackages.size();
8836 for (int i=0; i<N; i++) {
8837 final PendingPackage pp = mPendingPackages.get(i);
8838 Object idObj = getUserIdLP(pp.sharedId);
8839 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008840 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008841 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8842 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008843 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008844 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008845 + pp.name);
8846 continue;
8847 }
8848 p.copyFrom(pp);
8849 } else if (idObj != null) {
8850 String msg = "Bad package setting: package " + pp.name
8851 + " has shared uid " + pp.sharedId
8852 + " that is not a shared uid\n";
8853 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008854 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008855 } else {
8856 String msg = "Bad package setting: package " + pp.name
8857 + " has shared uid " + pp.sharedId
8858 + " that is not defined\n";
8859 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008860 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008861 }
8862 }
8863 mPendingPackages.clear();
8864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 mReadMessages.append("Read completed successfully: "
8866 + mPackages.size() + " packages, "
8867 + mSharedUsers.size() + " shared uids\n");
8868
8869 return true;
8870 }
8871
8872 private int readInt(XmlPullParser parser, String ns, String name,
8873 int defValue) {
8874 String v = parser.getAttributeValue(ns, name);
8875 try {
8876 if (v == null) {
8877 return defValue;
8878 }
8879 return Integer.parseInt(v);
8880 } catch (NumberFormatException e) {
8881 reportSettingsProblem(Log.WARN,
8882 "Error in package manager settings: attribute " +
8883 name + " has bad integer value " + v + " at "
8884 + parser.getPositionDescription());
8885 }
8886 return defValue;
8887 }
8888
8889 private void readPermissionsLP(HashMap<String, BasePermission> out,
8890 XmlPullParser parser)
8891 throws IOException, XmlPullParserException {
8892 int outerDepth = parser.getDepth();
8893 int type;
8894 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8895 && (type != XmlPullParser.END_TAG
8896 || parser.getDepth() > outerDepth)) {
8897 if (type == XmlPullParser.END_TAG
8898 || type == XmlPullParser.TEXT) {
8899 continue;
8900 }
8901
8902 String tagName = parser.getName();
8903 if (tagName.equals("item")) {
8904 String name = parser.getAttributeValue(null, "name");
8905 String sourcePackage = parser.getAttributeValue(null, "package");
8906 String ptype = parser.getAttributeValue(null, "type");
8907 if (name != null && sourcePackage != null) {
8908 boolean dynamic = "dynamic".equals(ptype);
8909 BasePermission bp = new BasePermission(name, sourcePackage,
8910 dynamic
8911 ? BasePermission.TYPE_DYNAMIC
8912 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008913 bp.protectionLevel = readInt(parser, null, "protection",
8914 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 if (dynamic) {
8916 PermissionInfo pi = new PermissionInfo();
8917 pi.packageName = sourcePackage.intern();
8918 pi.name = name.intern();
8919 pi.icon = readInt(parser, null, "icon", 0);
8920 pi.nonLocalizedLabel = parser.getAttributeValue(
8921 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008922 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923 bp.pendingInfo = pi;
8924 }
8925 out.put(bp.name, bp);
8926 } else {
8927 reportSettingsProblem(Log.WARN,
8928 "Error in package manager settings: permissions has"
8929 + " no name at " + parser.getPositionDescription());
8930 }
8931 } else {
8932 reportSettingsProblem(Log.WARN,
8933 "Unknown element reading permissions: "
8934 + parser.getName() + " at "
8935 + parser.getPositionDescription());
8936 }
8937 XmlUtils.skipCurrentTag(parser);
8938 }
8939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008942 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008944 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 String codePathStr = parser.getAttributeValue(null, "codePath");
8946 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07008947 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008948 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 resourcePathStr = codePathStr;
8950 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008951 String version = parser.getAttributeValue(null, "version");
8952 int versionCode = 0;
8953 if (version != null) {
8954 try {
8955 versionCode = Integer.parseInt(version);
8956 } catch (NumberFormatException e) {
8957 }
8958 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008960 int pkgFlags = 0;
8961 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07008962 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
8963 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 String timeStampStr = parser.getAttributeValue(null, "ts");
8965 if (timeStampStr != null) {
8966 try {
8967 long timeStamp = Long.parseLong(timeStampStr);
Kenny Root7d794fb2010-09-13 16:29:49 -07008968 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008969 } catch (NumberFormatException e) {
8970 }
8971 }
8972 String idStr = parser.getAttributeValue(null, "userId");
8973 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8974 if(ps.userId <= 0) {
8975 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8976 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8977 }
8978 int outerDepth = parser.getDepth();
8979 int type;
8980 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8981 && (type != XmlPullParser.END_TAG
8982 || parser.getDepth() > outerDepth)) {
8983 if (type == XmlPullParser.END_TAG
8984 || type == XmlPullParser.TEXT) {
8985 continue;
8986 }
8987
8988 String tagName = parser.getName();
8989 if (tagName.equals("perms")) {
8990 readGrantedPermissionsLP(parser,
8991 ps.grantedPermissions);
8992 } else {
8993 reportSettingsProblem(Log.WARN,
8994 "Unknown element under <updated-package>: "
8995 + parser.getName());
8996 XmlUtils.skipCurrentTag(parser);
8997 }
8998 }
8999 mDisabledSysPackages.put(name, ps);
9000 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009002 private void readPackageLP(XmlPullParser parser)
9003 throws XmlPullParserException, IOException {
9004 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009005 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009006 String idStr = null;
9007 String sharedIdStr = null;
9008 String codePathStr = null;
9009 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009010 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009011 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009012 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009013 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009014 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 long timeStamp = 0;
9017 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009018 String version = null;
9019 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009020 try {
9021 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009022 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009024 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9026 codePathStr = parser.getAttributeValue(null, "codePath");
9027 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009028 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009029 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009030 version = parser.getAttributeValue(null, "version");
9031 if (version != null) {
9032 try {
9033 versionCode = Integer.parseInt(version);
9034 } catch (NumberFormatException e) {
9035 }
9036 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009037 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009038
9039 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009040 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009041 try {
9042 pkgFlags = Integer.parseInt(systemStr);
9043 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 }
9045 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009046 // For backward compatibility
9047 systemStr = parser.getAttributeValue(null, "system");
9048 if (systemStr != null) {
9049 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9050 } else {
9051 // Old settings that don't specify system... just treat
9052 // them as system, good enough.
9053 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009055 }
Kenny Root7d794fb2010-09-13 16:29:49 -07009056 final String timeStampStr = parser.getAttributeValue(null, "ts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009057 if (timeStampStr != null) {
9058 try {
9059 timeStamp = Long.parseLong(timeStampStr);
9060 } catch (NumberFormatException e) {
9061 }
9062 }
9063 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9064 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9065 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9066 if (resourcePathStr == null) {
9067 resourcePathStr = codePathStr;
9068 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009069 if (realName != null) {
9070 realName = realName.intern();
9071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009072 if (name == null) {
9073 reportSettingsProblem(Log.WARN,
9074 "Error in package manager settings: <package> has no name at "
9075 + parser.getPositionDescription());
9076 } else if (codePathStr == null) {
9077 reportSettingsProblem(Log.WARN,
9078 "Error in package manager settings: <package> has no codePath at "
9079 + parser.getPositionDescription());
9080 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009081 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9082 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9083 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009084 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9085 + ": userId=" + userId + " pkg=" + packageSetting);
9086 if (packageSetting == null) {
9087 reportSettingsProblem(Log.ERROR,
9088 "Failure adding uid " + userId
9089 + " while parsing settings at "
9090 + parser.getPositionDescription());
9091 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009092 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009093 }
9094 } else if (sharedIdStr != null) {
9095 userId = sharedIdStr != null
9096 ? Integer.parseInt(sharedIdStr) : 0;
9097 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009098 packageSetting = new PendingPackage(name.intern(), realName,
9099 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009100 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009101 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009102 mPendingPackages.add((PendingPackage) packageSetting);
9103 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9104 + ": sharedUserId=" + userId + " pkg="
9105 + packageSetting);
9106 } else {
9107 reportSettingsProblem(Log.WARN,
9108 "Error in package manager settings: package "
9109 + name + " has bad sharedId " + sharedIdStr
9110 + " at " + parser.getPositionDescription());
9111 }
9112 } else {
9113 reportSettingsProblem(Log.WARN,
9114 "Error in package manager settings: package "
9115 + name + " has bad userId " + idStr + " at "
9116 + parser.getPositionDescription());
9117 }
9118 } catch (NumberFormatException e) {
9119 reportSettingsProblem(Log.WARN,
9120 "Error in package manager settings: package "
9121 + name + " has bad userId " + idStr + " at "
9122 + parser.getPositionDescription());
9123 }
9124 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009125 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009126 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009127 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009128 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 final String enabledStr = parser.getAttributeValue(null, "enabled");
9130 if (enabledStr != null) {
9131 if (enabledStr.equalsIgnoreCase("true")) {
9132 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9133 } else if (enabledStr.equalsIgnoreCase("false")) {
9134 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9135 } else if (enabledStr.equalsIgnoreCase("default")) {
9136 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9137 } else {
9138 reportSettingsProblem(Log.WARN,
9139 "Error in package manager settings: package "
9140 + name + " has bad enabled value: " + idStr
9141 + " at " + parser.getPositionDescription());
9142 }
9143 } else {
9144 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9145 }
9146 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9147 if (installStatusStr != null) {
9148 if (installStatusStr.equalsIgnoreCase("false")) {
9149 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9150 } else {
9151 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9152 }
9153 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009155 int outerDepth = parser.getDepth();
9156 int type;
9157 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9158 && (type != XmlPullParser.END_TAG
9159 || parser.getDepth() > outerDepth)) {
9160 if (type == XmlPullParser.END_TAG
9161 || type == XmlPullParser.TEXT) {
9162 continue;
9163 }
9164
9165 String tagName = parser.getName();
9166 if (tagName.equals("disabled-components")) {
9167 readDisabledComponentsLP(packageSetting, parser);
9168 } else if (tagName.equals("enabled-components")) {
9169 readEnabledComponentsLP(packageSetting, parser);
9170 } else if (tagName.equals("sigs")) {
9171 packageSetting.signatures.readXml(parser, mPastSignatures);
9172 } else if (tagName.equals("perms")) {
9173 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009174 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009175 packageSetting.permissionsFixed = true;
9176 } else {
9177 reportSettingsProblem(Log.WARN,
9178 "Unknown element under <package>: "
9179 + parser.getName());
9180 XmlUtils.skipCurrentTag(parser);
9181 }
9182 }
9183 } else {
9184 XmlUtils.skipCurrentTag(parser);
9185 }
9186 }
9187
9188 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9189 XmlPullParser parser)
9190 throws IOException, XmlPullParserException {
9191 int outerDepth = parser.getDepth();
9192 int type;
9193 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9194 && (type != XmlPullParser.END_TAG
9195 || parser.getDepth() > outerDepth)) {
9196 if (type == XmlPullParser.END_TAG
9197 || type == XmlPullParser.TEXT) {
9198 continue;
9199 }
9200
9201 String tagName = parser.getName();
9202 if (tagName.equals("item")) {
9203 String name = parser.getAttributeValue(null, "name");
9204 if (name != null) {
9205 packageSetting.disabledComponents.add(name.intern());
9206 } else {
9207 reportSettingsProblem(Log.WARN,
9208 "Error in package manager settings: <disabled-components> has"
9209 + " no name at " + parser.getPositionDescription());
9210 }
9211 } else {
9212 reportSettingsProblem(Log.WARN,
9213 "Unknown element under <disabled-components>: "
9214 + parser.getName());
9215 }
9216 XmlUtils.skipCurrentTag(parser);
9217 }
9218 }
9219
9220 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9221 XmlPullParser parser)
9222 throws IOException, XmlPullParserException {
9223 int outerDepth = parser.getDepth();
9224 int type;
9225 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9226 && (type != XmlPullParser.END_TAG
9227 || parser.getDepth() > outerDepth)) {
9228 if (type == XmlPullParser.END_TAG
9229 || type == XmlPullParser.TEXT) {
9230 continue;
9231 }
9232
9233 String tagName = parser.getName();
9234 if (tagName.equals("item")) {
9235 String name = parser.getAttributeValue(null, "name");
9236 if (name != null) {
9237 packageSetting.enabledComponents.add(name.intern());
9238 } else {
9239 reportSettingsProblem(Log.WARN,
9240 "Error in package manager settings: <enabled-components> has"
9241 + " no name at " + parser.getPositionDescription());
9242 }
9243 } else {
9244 reportSettingsProblem(Log.WARN,
9245 "Unknown element under <enabled-components>: "
9246 + parser.getName());
9247 }
9248 XmlUtils.skipCurrentTag(parser);
9249 }
9250 }
9251
9252 private void readSharedUserLP(XmlPullParser parser)
9253 throws XmlPullParserException, IOException {
9254 String name = null;
9255 String idStr = null;
9256 int pkgFlags = 0;
9257 SharedUserSetting su = null;
9258 try {
9259 name = parser.getAttributeValue(null, "name");
9260 idStr = parser.getAttributeValue(null, "userId");
9261 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9262 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9263 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9264 }
9265 if (name == null) {
9266 reportSettingsProblem(Log.WARN,
9267 "Error in package manager settings: <shared-user> has no name at "
9268 + parser.getPositionDescription());
9269 } else if (userId == 0) {
9270 reportSettingsProblem(Log.WARN,
9271 "Error in package manager settings: shared-user "
9272 + name + " has bad userId " + idStr + " at "
9273 + parser.getPositionDescription());
9274 } else {
9275 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9276 reportSettingsProblem(Log.ERROR,
9277 "Occurred while parsing settings at "
9278 + parser.getPositionDescription());
9279 }
9280 }
9281 } catch (NumberFormatException e) {
9282 reportSettingsProblem(Log.WARN,
9283 "Error in package manager settings: package "
9284 + name + " has bad userId " + idStr + " at "
9285 + parser.getPositionDescription());
9286 };
9287
9288 if (su != null) {
9289 int outerDepth = parser.getDepth();
9290 int type;
9291 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9292 && (type != XmlPullParser.END_TAG
9293 || parser.getDepth() > outerDepth)) {
9294 if (type == XmlPullParser.END_TAG
9295 || type == XmlPullParser.TEXT) {
9296 continue;
9297 }
9298
9299 String tagName = parser.getName();
9300 if (tagName.equals("sigs")) {
9301 su.signatures.readXml(parser, mPastSignatures);
9302 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009303 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009304 } else {
9305 reportSettingsProblem(Log.WARN,
9306 "Unknown element under <shared-user>: "
9307 + parser.getName());
9308 XmlUtils.skipCurrentTag(parser);
9309 }
9310 }
9311
9312 } else {
9313 XmlUtils.skipCurrentTag(parser);
9314 }
9315 }
9316
9317 private void readGrantedPermissionsLP(XmlPullParser parser,
9318 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9319 int outerDepth = parser.getDepth();
9320 int type;
9321 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9322 && (type != XmlPullParser.END_TAG
9323 || parser.getDepth() > outerDepth)) {
9324 if (type == XmlPullParser.END_TAG
9325 || type == XmlPullParser.TEXT) {
9326 continue;
9327 }
9328
9329 String tagName = parser.getName();
9330 if (tagName.equals("item")) {
9331 String name = parser.getAttributeValue(null, "name");
9332 if (name != null) {
9333 outPerms.add(name.intern());
9334 } else {
9335 reportSettingsProblem(Log.WARN,
9336 "Error in package manager settings: <perms> has"
9337 + " no name at " + parser.getPositionDescription());
9338 }
9339 } else {
9340 reportSettingsProblem(Log.WARN,
9341 "Unknown element under <perms>: "
9342 + parser.getName());
9343 }
9344 XmlUtils.skipCurrentTag(parser);
9345 }
9346 }
9347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009348 private void readPreferredActivitiesLP(XmlPullParser parser)
9349 throws XmlPullParserException, IOException {
9350 int outerDepth = parser.getDepth();
9351 int type;
9352 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9353 && (type != XmlPullParser.END_TAG
9354 || parser.getDepth() > outerDepth)) {
9355 if (type == XmlPullParser.END_TAG
9356 || type == XmlPullParser.TEXT) {
9357 continue;
9358 }
9359
9360 String tagName = parser.getName();
9361 if (tagName.equals("item")) {
9362 PreferredActivity pa = new PreferredActivity(parser);
9363 if (pa.mParseError == null) {
9364 mPreferredActivities.addFilter(pa);
9365 } else {
9366 reportSettingsProblem(Log.WARN,
9367 "Error in package manager settings: <preferred-activity> "
9368 + pa.mParseError + " at "
9369 + parser.getPositionDescription());
9370 }
9371 } else {
9372 reportSettingsProblem(Log.WARN,
9373 "Unknown element under <preferred-activities>: "
9374 + parser.getName());
9375 XmlUtils.skipCurrentTag(parser);
9376 }
9377 }
9378 }
9379
9380 // Returns -1 if we could not find an available UserId to assign
9381 private int newUserIdLP(Object obj) {
9382 // Let's be stupidly inefficient for now...
9383 final int N = mUserIds.size();
9384 for (int i=0; i<N; i++) {
9385 if (mUserIds.get(i) == null) {
9386 mUserIds.set(i, obj);
9387 return FIRST_APPLICATION_UID + i;
9388 }
9389 }
9390
9391 // None left?
9392 if (N >= MAX_APPLICATION_UIDS) {
9393 return -1;
9394 }
9395
9396 mUserIds.add(obj);
9397 return FIRST_APPLICATION_UID + N;
9398 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009400 public PackageSetting getDisabledSystemPkg(String name) {
9401 synchronized(mPackages) {
9402 PackageSetting ps = mDisabledSysPackages.get(name);
9403 return ps;
9404 }
9405 }
9406
9407 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009408 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9409 return true;
9410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009411 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9412 if (Config.LOGV) {
9413 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9414 + " componentName = " + componentInfo.name);
9415 Log.v(TAG, "enabledComponents: "
9416 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9417 Log.v(TAG, "disabledComponents: "
9418 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9419 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009420 if (packageSettings == null) {
9421 if (false) {
9422 Log.w(TAG, "WAITING FOR DEBUGGER");
9423 Debug.waitForDebugger();
9424 Log.i(TAG, "We will crash!");
9425 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009426 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009427 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009428 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9429 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9430 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9431 return false;
9432 }
9433 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9434 return true;
9435 }
9436 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9437 return false;
9438 }
9439 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009440 }
9441 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009442
9443 // ------- apps on sdcard specific code -------
9444 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009445 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9446 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9447 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009448 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009449
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009450 private String getEncryptKey() {
9451 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009452 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9453 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009454 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009455 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9456 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009457 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009458 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009459 return null;
9460 }
9461 }
9462 return sdEncKey;
9463 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009464 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009465 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009466 } catch (IOException ioe) {
9467 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9468 + ioe);
9469 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009470 }
Rich Cannings8d578832010-09-09 15:12:40 -07009471
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009472 }
9473
Kenny Rootc78a8072010-07-27 15:18:38 -07009474 /* package */ static String getTempContainerId() {
9475 int tmpIdx = 1;
9476 String list[] = PackageHelper.getSecureContainerList();
9477 if (list != null) {
9478 for (final String name : list) {
9479 // Ignore null and non-temporary container entries
9480 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9481 continue;
9482 }
9483
9484 String subStr = name.substring(mTempContainerPrefix.length());
9485 try {
9486 int cid = Integer.parseInt(subStr);
9487 if (cid >= tmpIdx) {
9488 tmpIdx = cid + 1;
9489 }
9490 } catch (NumberFormatException e) {
9491 }
9492 }
9493 }
9494 return mTempContainerPrefix + tmpIdx;
9495 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009496
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009497 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009498 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009499 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009500 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9501 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9502 throw new SecurityException("Media status can only be updated by the system");
9503 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009504 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009505 Log.i(TAG, "Updating external media status from " +
9506 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9507 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009508 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9509 mediaStatus+", mMediaMounted=" + mMediaMounted);
9510 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009511 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9512 reportStatus ? 1 : 0, -1);
9513 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009514 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009515 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009516 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009517 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009518 // Queue up an async operation since the package installation may take a little while.
9519 mHandler.post(new Runnable() {
9520 public void run() {
9521 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009522 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009523 }
9524 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009525 }
9526
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009527 /*
9528 * Collect information of applications on external media, map them
9529 * against existing containers and update information based on current
9530 * mount status. Please note that we always have to report status
9531 * if reportStatus has been set to true especially when unloading packages.
9532 */
9533 private void updateExternalMediaStatusInner(boolean mediaStatus,
9534 boolean reportStatus) {
9535 // Collection of uids
9536 int uidArr[] = null;
9537 // Collection of stale containers
9538 HashSet<String> removeCids = new HashSet<String>();
9539 // Collection of packages on external media with valid containers.
9540 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9541 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009542 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009543 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009544 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009545 } else {
9546 // Process list of secure containers and categorize them
9547 // as active or stale based on their package internal state.
9548 int uidList[] = new int[list.length];
9549 int num = 0;
9550 synchronized (mPackages) {
9551 for (String cid : list) {
9552 SdInstallArgs args = new SdInstallArgs(cid);
9553 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009554 String pkgName = args.getPackageName();
9555 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009556 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9557 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009558 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009559 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009560 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9561 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009562 // The package status is changed only if the code path
9563 // matches between settings and the container id.
9564 if (ps != null && ps.codePathString != null &&
9565 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009566 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9567 " corresponds to pkg : " + pkgName +
9568 " at code path: " + ps.codePathString);
9569 // We do have a valid package installed on sdcard
9570 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009571 int uid = ps.userId;
9572 if (uid != -1) {
9573 uidList[num++] = uid;
9574 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009575 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009576 // Stale container on sdcard. Just delete
9577 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9578 removeCids.add(cid);
9579 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009580 }
9581 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009582
9583 if (num > 0) {
9584 // Sort uid list
9585 Arrays.sort(uidList, 0, num);
9586 // Throw away duplicates
9587 uidArr = new int[num];
9588 uidArr[0] = uidList[0];
9589 int di = 0;
9590 for (int i = 1; i < num; i++) {
9591 if (uidList[i-1] != uidList[i]) {
9592 uidArr[di++] = uidList[i];
9593 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009594 }
9595 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009596 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009597 // Process packages with valid entries.
9598 if (mediaStatus) {
9599 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009600 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009601 startCleaningPackages();
9602 } else {
9603 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009604 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009605 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009606 }
9607
9608 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009609 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009610 int size = pkgList.size();
9611 if (size > 0) {
9612 // Send broadcasts here
9613 Bundle extras = new Bundle();
9614 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9615 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009616 if (uidArr != null) {
9617 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9618 }
9619 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9620 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009621 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009622 }
9623 }
9624
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009625 /*
9626 * Look at potentially valid container ids from processCids
9627 * If package information doesn't match the one on record
9628 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009629 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009630 */
9631 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009632 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009633 ArrayList<String> pkgList = new ArrayList<String>();
9634 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009635 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009636 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009637 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009638 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9639 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009640 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009641 try {
9642 // Make sure there are no container errors first.
9643 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9644 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009645 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009646 " when installing from sdcard");
9647 continue;
9648 }
9649 // Check code path here.
9650 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009651 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009652 " does not match one in settings " + codePath);
9653 continue;
9654 }
9655 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009656 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009657 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009658 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009659 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9660 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009661 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009662 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009663 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009664 retCode = PackageManager.INSTALL_SUCCEEDED;
9665 pkgList.add(pkg.packageName);
9666 // Post process args
9667 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9668 }
9669 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009670 Slog.i(TAG, "Failed to install pkg from " +
9671 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009672 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009673 }
9674
9675 } finally {
9676 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9677 // Don't destroy container here. Wait till gc clears things up.
9678 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009679 }
9680 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009681 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009682 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009683 // If the platform SDK has changed since the last time we booted,
9684 // we need to re-grant app permission to catch any new ones that
9685 // appear. This is really a hack, and means that apps can in some
9686 // cases get permissions that the user didn't initially explicitly
9687 // allow... it would be nice to have some better way to handle
9688 // this situation.
9689 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9690 != mSdkVersion;
9691 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9692 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9693 + "; regranting permissions for external storage");
9694 mSettings.mExternalSdkPlatform = mSdkVersion;
9695
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009696 // Make sure group IDs have been assigned, and any permission
9697 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009698 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009699 // Persist settings
9700 mSettings.writeLP();
9701 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009702 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009703 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009704 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009705 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009706 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009707 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009708 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009709 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009710 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009711 if (removeCids != null) {
9712 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009713 if (cid.startsWith(mTempContainerPrefix)) {
9714 Log.i(TAG, "Destroying stale temporary container " + cid);
9715 PackageHelper.destroySdDir(cid);
9716 } else {
9717 Log.w(TAG, "Container " + cid + " is stale");
9718 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009719 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009720 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009721 }
9722
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009723 /*
9724 * Utility method to unload a list of specified containers
9725 */
9726 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9727 // Just unmount all valid containers.
9728 for (SdInstallArgs arg : cidArgs) {
9729 synchronized (mInstallLock) {
9730 arg.doPostDeleteLI(false);
9731 }
9732 }
9733 }
9734
9735 /*
9736 * Unload packages mounted on external media. This involves deleting
9737 * package data from internal structures, sending broadcasts about
9738 * diabled packages, gc'ing to free up references, unmounting all
9739 * secure containers corresponding to packages on external media, and
9740 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9741 * Please note that we always have to post this message if status has
9742 * been requested no matter what.
9743 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009744 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009745 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009746 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009747 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009748 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009749 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009750 for (SdInstallArgs args : keys) {
9751 String cid = args.cid;
9752 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009753 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009754 // Delete package internally
9755 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9756 synchronized (mInstallLock) {
9757 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009758 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009759 if (res) {
9760 pkgList.add(pkgName);
9761 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009762 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009763 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009764 }
9765 }
9766 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009767
9768 synchronized (mPackages) {
9769 // We didn't update the settings after removing each package;
9770 // write them now for all packages.
9771 mSettings.writeLP();
9772 }
9773
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009774 // We have to absolutely send UPDATED_MEDIA_STATUS only
9775 // after confirming that all the receivers processed the ordered
9776 // broadcast when packages get disabled, force a gc to clean things up.
9777 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009778 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009779 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9780 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9781 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009782 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9783 reportStatus ? 1 : 0, 1, keys);
9784 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009785 }
9786 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009787 } else {
9788 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9789 reportStatus ? 1 : 0, -1, keys);
9790 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009791 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009792 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009793
9794 public void movePackage(final String packageName,
9795 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009796 mContext.enforceCallingOrSelfPermission(
9797 android.Manifest.permission.MOVE_PACKAGE, null);
9798 int returnCode = PackageManager.MOVE_SUCCEEDED;
9799 int currFlags = 0;
9800 int newFlags = 0;
9801 synchronized (mPackages) {
9802 PackageParser.Package pkg = mPackages.get(packageName);
9803 if (pkg == null) {
9804 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009805 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009806 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009807 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009808 Slog.w(TAG, "Cannot move system application");
9809 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009810 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009811 Slog.w(TAG, "Cannot move forward locked app.");
9812 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009813 } else if (pkg.mOperationPending) {
9814 Slog.w(TAG, "Attempt to move package which has pending operations");
9815 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009816 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009817 // Find install location first
9818 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9819 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9820 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009821 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009822 } else {
9823 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9824 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009825 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9826 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009827 if (newFlags == currFlags) {
9828 Slog.w(TAG, "No move required. Trying to move to same location");
9829 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9830 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009831 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009832 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9833 pkg.mOperationPending = true;
9834 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009835 }
9836 }
9837 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009838 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009839 } else {
9840 Message msg = mHandler.obtainMessage(INIT_COPY);
9841 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009842 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9843 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9844 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009845 msg.obj = mp;
9846 mHandler.sendMessage(msg);
9847 }
9848 }
9849 }
9850
9851 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9852 // Queue up an async operation since the package deletion may take a little while.
9853 mHandler.post(new Runnable() {
9854 public void run() {
9855 mHandler.removeCallbacks(this);
9856 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009857 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9858 int uidArr[] = null;
9859 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009860 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009861 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009862 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009863 Slog.w(TAG, " Package " + mp.packageName +
9864 " doesn't exist. Aborting move");
9865 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9866 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9867 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9868 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9869 " Aborting move and returning error");
9870 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9871 } else {
9872 uidArr = new int[] { pkg.applicationInfo.uid };
9873 pkgList = new ArrayList<String>();
9874 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009875 }
9876 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009877 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9878 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009879 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009880 // Update package code and resource paths
9881 synchronized (mInstallLock) {
9882 synchronized (mPackages) {
9883 PackageParser.Package pkg = mPackages.get(mp.packageName);
9884 // Recheck for package again.
9885 if (pkg == null ) {
9886 Slog.w(TAG, " Package " + mp.packageName +
9887 " doesn't exist. Aborting move");
9888 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9889 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9890 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9891 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9892 " Aborting move and returning error");
9893 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9894 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009895 final String oldCodePath = pkg.mPath;
9896 final String newCodePath = mp.targetArgs.getCodePath();
9897 final String newResPath = mp.targetArgs.getResourcePath();
9898 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009899 pkg.mPath = newCodePath;
9900 // Move dex files around
9901 if (moveDexFilesLI(pkg)
9902 != PackageManager.INSTALL_SUCCEEDED) {
9903 // Moving of dex files failed. Set
9904 // error code and abort move.
9905 pkg.mPath = pkg.mScanPath;
9906 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9907 } else {
9908 pkg.mScanPath = newCodePath;
9909 pkg.applicationInfo.sourceDir = newCodePath;
9910 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009911 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009912 PackageSetting ps = (PackageSetting) pkg.mExtras;
9913 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9914 ps.codePathString = ps.codePath.getPath();
9915 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9916 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009917 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009918 // Set the application info flag correctly.
9919 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9920 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9921 } else {
9922 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9923 }
9924 ps.setFlags(pkg.applicationInfo.flags);
9925 mAppDirs.remove(oldCodePath);
9926 mAppDirs.put(newCodePath, pkg);
9927 // Persist settings
9928 mSettings.writeLP();
9929 }
9930 }
9931 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009932 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009933 // Send resources available broadcast
9934 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009935 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009936 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009937 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009938 // Clean up failed installation
9939 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009940 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009941 }
9942 } else {
9943 // Force a gc to clear things up.
9944 Runtime.getRuntime().gc();
9945 // Delete older code
9946 synchronized (mInstallLock) {
9947 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009948 }
9949 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009950
9951 // Allow more operations on this file if we didn't fail because
9952 // an operation was already pending for this package.
9953 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9954 synchronized (mPackages) {
9955 PackageParser.Package pkg = mPackages.get(mp.packageName);
9956 if (pkg != null) {
9957 pkg.mOperationPending = false;
9958 }
9959 }
9960 }
9961
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009962 IPackageMoveObserver observer = mp.observer;
9963 if (observer != null) {
9964 try {
9965 observer.packageMoved(mp.packageName, returnCode);
9966 } catch (RemoteException e) {
9967 Log.i(TAG, "Observer no longer exists.");
9968 }
9969 }
9970 }
9971 });
9972 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009973
9974 public boolean setInstallLocation(int loc) {
9975 mContext.enforceCallingOrSelfPermission(
9976 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9977 if (getInstallLocation() == loc) {
9978 return true;
9979 }
9980 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9981 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9982 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9983 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9984 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9985 return true;
9986 }
9987 return false;
9988 }
9989
9990 public int getInstallLocation() {
9991 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9992 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009994}