blob: ce0e79f891921d684dc8120ac128bf15bf74abf0 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
57import android.content.pm.PackageStats;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
Kenny Root9f306d72010-09-26 11:19:47 -070094import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.FileReader;
101import java.io.FilenameFilter;
102import java.io.IOException;
103import java.io.InputStream;
104import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800105import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
108import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700109import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Collections;
111import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800112import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.Enumeration;
114import java.util.HashMap;
115import java.util.HashSet;
116import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700117import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.List;
119import java.util.Map;
120import java.util.Set;
121import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800122import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import java.util.zip.ZipFile;
124import java.util.zip.ZipOutputStream;
125
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700126/**
127 * Keep track of all those .apks everywhere.
128 *
129 * This is very central to the platform's security; please run the unit
130 * tests whenever making modifications here:
131 *
132mmm frameworks/base/tests/AndroidTests
133adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
134adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
135 *
136 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137class PackageManagerService extends IPackageManager.Stub {
138 private static final String TAG = "PackageManager";
139 private static final boolean DEBUG_SETTINGS = false;
140 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800141 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800142 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
145 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400146 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 private static final int FIRST_APPLICATION_UID =
148 Process.FIRST_APPLICATION_UID;
149 private static final int MAX_APPLICATION_UIDS = 1000;
150
151 private static final boolean SHOW_INFO = false;
152
153 private static final boolean GET_CERTIFICATES = true;
154
Oscar Montemayora8529f62009-11-18 10:14:20 -0800155 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private static final int REMOVE_EVENTS =
158 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
159 private static final int ADD_EVENTS =
160 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
161
162 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800163 // Suffix used during package installation when copying/moving
164 // package apks to install directory.
165 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800167 /**
168 * Indicates the state of installation. Used by PackageManager to
169 * figure out incomplete installations. Say a package is being installed
170 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
171 * the package installation is successful or unsuccesful lin which case
172 * the PackageManager will no longer maintain state information associated
173 * with the package. If some exception(like device freeze or battery being
174 * pulled out) occurs during installation of a package, the PackageManager
175 * needs this information to clean up the previously failed installation.
176 */
177 private static final int PKG_INSTALL_INCOMPLETE = 0;
178 private static final int PKG_INSTALL_COMPLETE = 1;
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final int SCAN_MONITOR = 1<<0;
181 static final int SCAN_NO_DEX = 1<<1;
182 static final int SCAN_FORCE_DEX = 1<<2;
183 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800184 static final int SCAN_NEW_INSTALL = 1<<4;
185 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700186 static final int SCAN_UPDATE_TIME = 1<<6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700188 static final int REMOVE_CHATTY = 1<<16;
189
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800190 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
191 "com.android.defcontainer",
192 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700193
Kenny Root85387d72010-08-26 10:13:11 -0700194 private static final String LIB_DIR_NAME = "lib";
195
Kenny Rootc78a8072010-07-27 15:18:38 -0700196 static final String mTempContainerPrefix = "smdl2tmp";
197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
199 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700200 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Dianne Hackborn851a5412009-05-08 12:06:44 -0700202 final int mSdkVersion = Build.VERSION.SDK_INT;
203 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
204 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 final Context mContext;
207 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700208 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 final DisplayMetrics mMetrics;
210 final int mDefParseFlags;
211 final String[] mSeparateProcesses;
212
213 // This is where all application persistent data goes.
214 final File mAppDataDir;
215
Oscar Montemayora8529f62009-11-18 10:14:20 -0800216 // If Encrypted File System feature is enabled, all application persistent data
217 // should go here instead.
218 final File mSecureAppDataDir;
219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 // This is the object monitoring the framework dir.
221 final FileObserver mFrameworkInstallObserver;
222
223 // This is the object monitoring the system app dir.
224 final FileObserver mSystemInstallObserver;
225
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700226 // This is the object monitoring the system app dir.
227 final FileObserver mVendorInstallObserver;
228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 // This is the object monitoring mAppInstallDir.
230 final FileObserver mAppInstallObserver;
231
232 // This is the object monitoring mDrmAppPrivateInstallDir.
233 final FileObserver mDrmAppInstallObserver;
234
235 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
236 // LOCK HELD. Can be called with mInstallLock held.
237 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 final File mFrameworkDir;
240 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700241 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700243 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
245 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
246 // apps.
247 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // Lock for state used when installing and doing other long running
252 // operations. Methods that must be called with this lock held have
253 // the prefix "LI".
254 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800256 // These are the directories in the 3rd party applications installed dir
257 // that we have currently loaded packages from. Keys are the application's
258 // installed zip file (absolute codePath), and values are Package.
259 final HashMap<String, PackageParser.Package> mAppDirs =
260 new HashMap<String, PackageParser.Package>();
261
262 // Information for the parser to write more useful error messages.
263 File mScanningPath;
264 int mLastScanError;
265
266 final int[] mOutPermissions = new int[3];
267
268 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 // Keys are String (package name), values are Package. This also serves
271 // as the lock for the global state. Methods that must be called with
272 // this lock held have the prefix "LP".
273 final HashMap<String, PackageParser.Package> mPackages =
274 new HashMap<String, PackageParser.Package>();
275
276 final Settings mSettings;
277 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278
279 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
280 int[] mGlobalGids;
281
282 // These are the built-in uid -> permission mappings that were read from the
283 // etc/permissions.xml file.
284 final SparseArray<HashSet<String>> mSystemPermissions =
285 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800287 // These are the built-in shared libraries that were read from the
288 // etc/permissions.xml file.
289 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800290
Dianne Hackborn49237342009-08-27 20:08:01 -0700291 // Temporary for building the final shared libraries for an .apk.
292 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
Dianne Hackborn49237342009-08-27 20:08:01 -0700294 // These are the features this devices supports that were read from the
295 // etc/permissions.xml file.
296 final HashMap<String, FeatureInfo> mAvailableFeatures =
297 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 // All available activities, for your resolving pleasure.
300 final ActivityIntentResolver mActivities =
301 new ActivityIntentResolver();
302
303 // All available receivers, for your resolving pleasure.
304 final ActivityIntentResolver mReceivers =
305 new ActivityIntentResolver();
306
307 // All available services, for your resolving pleasure.
308 final ServiceIntentResolver mServices = new ServiceIntentResolver();
309
310 // Keys are String (provider class name), values are Provider.
311 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
312 new HashMap<ComponentName, PackageParser.Provider>();
313
314 // Mapping from provider base names (first directory in content URI codePath)
315 // to the provider information.
316 final HashMap<String, PackageParser.Provider> mProviders =
317 new HashMap<String, PackageParser.Provider>();
318
319 // Mapping from instrumentation class names to info about them.
320 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
321 new HashMap<ComponentName, PackageParser.Instrumentation>();
322
323 // Mapping from permission names to info about them.
324 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
325 new HashMap<String, PackageParser.PermissionGroup>();
326
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800327 // Packages whose data we have transfered into another package, thus
328 // should no longer exist.
329 final HashSet<String> mTransferedPackages = new HashSet<String>();
330
Dianne Hackborn854060af2009-07-09 18:14:31 -0700331 // Broadcast actions that are only available to the system.
332 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 boolean mSystemReady;
335 boolean mSafeMode;
336 boolean mHasSystemUidErrors;
337
338 ApplicationInfo mAndroidApplication;
339 final ActivityInfo mResolveActivity = new ActivityInfo();
340 final ResolveInfo mResolveInfo = new ResolveInfo();
341 ComponentName mResolveComponentName;
342 PackageParser.Package mPlatformPackage;
343
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700344 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800345 final HashMap<String, ArrayList<String>> mPendingBroadcasts
346 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800347 // Service Connection to remote media container service to copy
348 // package uri's from external media onto secure containers
349 // or internal storage.
350 private IMediaContainerService mContainerService = null;
351
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700352 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800353 static final int MCS_BOUND = 3;
354 static final int END_COPY = 4;
355 static final int INIT_COPY = 5;
356 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800357 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800358 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800359 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800360 static final int MCS_RECONNECT = 10;
361 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700362 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700363 static final int WRITE_SETTINGS = 13;
364
365 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800366
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700367 // Delay time in millisecs
368 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369 final private DefaultContainerConnection mDefContainerConn =
370 new DefaultContainerConnection();
371 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800372 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800373 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800374 IMediaContainerService imcs =
375 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800376 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800377 }
378
379 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800380 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800381 }
382 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700383
Christopher Tate1bb69062010-02-19 17:02:12 -0800384 // Recordkeeping of restore-after-install operations that are currently in flight
385 // between the Package Manager and the Backup Manager
386 class PostInstallData {
387 public InstallArgs args;
388 public PackageInstalledInfo res;
389
390 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
391 args = _a;
392 res = _r;
393 }
394 };
395 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
396 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
397
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700398 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800399 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800400 final ArrayList<HandlerParams> mPendingInstalls =
401 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402
403 private boolean connectToService() {
404 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
405 " DefaultContainerService");
406 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700407 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800408 if (mContext.bindService(service, mDefContainerConn,
409 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800411 mBound = true;
412 return true;
413 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800415 return false;
416 }
417
418 private void disconnectService() {
419 mContainerService = null;
420 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700421 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800422 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700423 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800424 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800425
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700426 PackageHandler(Looper looper) {
427 super(looper);
428 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700429
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700430 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700431 try {
432 doHandleMessage(msg);
433 } finally {
434 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
435 }
436 }
437
438 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700439 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800440 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800441 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800442 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800443 int idx = mPendingInstalls.size();
444 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
445 // If a bind was already initiated we dont really
446 // need to do anything. The pending install
447 // will be processed later on.
448 if (!mBound) {
449 // If this is the only one pending we might
450 // have to bind to the service again.
451 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800452 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800453 params.serviceError();
454 return;
455 } else {
456 // Once we bind to the service, the first
457 // pending request will be processed.
458 mPendingInstalls.add(idx, params);
459 }
460 } else {
461 mPendingInstalls.add(idx, params);
462 // Already bound to the service. Just make
463 // sure we trigger off processing the first request.
464 if (idx == 0) {
465 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800466 }
467 }
468 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800469 }
470 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800471 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800472 if (msg.obj != null) {
473 mContainerService = (IMediaContainerService) msg.obj;
474 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800475 if (mContainerService == null) {
476 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800477 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 for (HandlerParams params : mPendingInstalls) {
479 mPendingInstalls.remove(0);
480 // Indicate service bind error
481 params.serviceError();
482 }
483 mPendingInstalls.clear();
484 } else if (mPendingInstalls.size() > 0) {
485 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800486 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 params.startCopy();
488 }
489 } else {
490 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800491 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800492 }
493 break;
494 }
495 case MCS_RECONNECT : {
496 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
497 if (mPendingInstalls.size() > 0) {
498 if (mBound) {
499 disconnectService();
500 }
501 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800502 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800503 for (HandlerParams params : mPendingInstalls) {
504 mPendingInstalls.remove(0);
505 // Indicate service bind error
506 params.serviceError();
507 }
508 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800509 }
510 }
511 break;
512 }
513 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800514 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
515 // Delete pending install
516 if (mPendingInstalls.size() > 0) {
517 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800518 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800519 if (mPendingInstalls.size() == 0) {
520 if (mBound) {
521 disconnectService();
522 }
523 } else {
524 // There are more pending requests in queue.
525 // Just post MCS_BOUND message to trigger processing
526 // of next pending install.
527 mHandler.sendEmptyMessage(MCS_BOUND);
528 }
529 break;
530 }
531 case MCS_GIVE_UP: {
532 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
533 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800534 break;
535 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700536 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800537 String packages[];
538 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700540 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700541 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800543 if (mPendingBroadcasts == null) {
544 return;
545 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700546 size = mPendingBroadcasts.size();
547 if (size <= 0) {
548 // Nothing to be done. Just return
549 return;
550 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800551 packages = new String[size];
552 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700553 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 Iterator<HashMap.Entry<String, ArrayList<String>>>
555 it = mPendingBroadcasts.entrySet().iterator();
556 int i = 0;
557 while (it.hasNext() && i < size) {
558 HashMap.Entry<String, ArrayList<String>> ent = it.next();
559 packages[i] = ent.getKey();
560 components[i] = ent.getValue();
561 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700562 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800563 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700564 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800565 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700566 mPendingBroadcasts.clear();
567 }
568 // Send broadcasts
569 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800570 sendPackageChangedBroadcast(packages[i], true,
571 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700572 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700573 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700574 break;
575 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800576 case START_CLEANING_PACKAGE: {
577 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700578 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800579 synchronized (mPackages) {
580 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
581 mSettings.mPackagesToBeCleaned.add(packageName);
582 }
583 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700584 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800585 startCleaningPackages();
586 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800587 case POST_INSTALL: {
588 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
589 PostInstallData data = mRunningInstalls.get(msg.arg1);
590 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700591 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800592
593 if (data != null) {
594 InstallArgs args = data.args;
595 PackageInstalledInfo res = data.res;
596
597 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700598 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800599 Bundle extras = new Bundle(1);
600 extras.putInt(Intent.EXTRA_UID, res.uid);
601 final boolean update = res.removedInfo.removedPackage != null;
602 if (update) {
603 extras.putBoolean(Intent.EXTRA_REPLACING, true);
604 }
605 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
606 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700607 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800608 if (update) {
609 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
610 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700611 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800612 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700613 if (res.removedInfo.args != null) {
614 // Remove the replaced package's older resources safely now
615 deleteOld = true;
616 }
617 }
618 // Force a gc to clear up things
619 Runtime.getRuntime().gc();
620 // We delete after a gc for applications on sdcard.
621 if (deleteOld) {
622 synchronized (mInstallLock) {
623 res.removedInfo.args.doPostDeleteLI(true);
624 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800625 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800626 if (args.observer != null) {
627 try {
628 args.observer.packageInstalled(res.name, res.returnCode);
629 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800630 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800631 }
632 }
633 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800634 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800635 }
636 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700637 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700638 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
639 boolean reportStatus = msg.arg1 == 1;
640 boolean doGc = msg.arg2 == 1;
641 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
642 if (doGc) {
643 // Force a gc to clear up stale containers.
644 Runtime.getRuntime().gc();
645 }
646 if (msg.obj != null) {
647 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
648 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
649 // Unload containers
650 unloadAllContainers(args);
651 }
652 if (reportStatus) {
653 try {
654 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
655 PackageHelper.getMountService().finishMediaUpdate();
656 } catch (RemoteException e) {
657 Log.e(TAG, "MountService not running?");
658 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700659 }
660 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700661 case WRITE_SETTINGS: {
662 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
663 synchronized (mPackages) {
664 removeMessages(WRITE_SETTINGS);
665 mSettings.writeLP();
666 }
667 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
668 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700669 }
670 }
671 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800672
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700673 void scheduleWriteSettingsLocked() {
674 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
675 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
676 }
677 }
678
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800679 static boolean installOnSd(int flags) {
680 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700681 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800682 return false;
683 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700684 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
685 return true;
686 }
687 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800688 }
689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800690 public static final IPackageManager main(Context context, boolean factoryTest) {
691 PackageManagerService m = new PackageManagerService(context, factoryTest);
692 ServiceManager.addService("package", m);
693 return m;
694 }
695
696 static String[] splitString(String str, char sep) {
697 int count = 1;
698 int i = 0;
699 while ((i=str.indexOf(sep, i)) >= 0) {
700 count++;
701 i++;
702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800704 String[] res = new String[count];
705 i=0;
706 count = 0;
707 int lastI=0;
708 while ((i=str.indexOf(sep, i)) >= 0) {
709 res[count] = str.substring(lastI, i);
710 count++;
711 i++;
712 lastI = i;
713 }
714 res[count] = str.substring(lastI, str.length());
715 return res;
716 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800723 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 mContext = context;
727 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700728 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 mMetrics = new DisplayMetrics();
730 mSettings = new Settings();
731 mSettings.addSharedUserLP("android.uid.system",
732 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
733 mSettings.addSharedUserLP("android.uid.phone",
734 MULTIPLE_APPLICATION_UIDS
735 ? RADIO_UID : FIRST_APPLICATION_UID,
736 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400737 mSettings.addSharedUserLP("android.uid.log",
738 MULTIPLE_APPLICATION_UIDS
739 ? LOG_UID : FIRST_APPLICATION_UID,
740 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741
742 String separateProcesses = SystemProperties.get("debug.separate_processes");
743 if (separateProcesses != null && separateProcesses.length() > 0) {
744 if ("*".equals(separateProcesses)) {
745 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
746 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800747 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 } else {
749 mDefParseFlags = 0;
750 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800751 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 + separateProcesses);
753 }
754 } else {
755 mDefParseFlags = 0;
756 mSeparateProcesses = null;
757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 Installer installer = new Installer();
760 // Little hacky thing to check if installd is here, to determine
761 // whether we are running on the simulator and thus need to take
762 // care of building the /data file structure ourself.
763 // (apparently the sim now has a working installer)
764 if (installer.ping() && Process.supportsProcesses()) {
765 mInstaller = installer;
766 } else {
767 mInstaller = null;
768 }
769
770 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
771 Display d = wm.getDefaultDisplay();
772 d.getMetrics(mMetrics);
773
774 synchronized (mInstallLock) {
775 synchronized (mPackages) {
776 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700777 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800779 File dataDir = Environment.getDataDirectory();
780 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800781 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
783
784 if (mInstaller == null) {
785 // Make sure these dirs exist, when we are running in
786 // the simulator.
787 // Make a wide-open directory for random misc stuff.
788 File miscDir = new File(dataDir, "misc");
789 miscDir.mkdirs();
790 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800791 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 mDrmAppPrivateInstallDir.mkdirs();
793 }
794
795 readPermissions();
796
797 mRestoredSettings = mSettings.readLP();
798 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800799
800 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800802
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800803 // Set flag to monitor and not change apk file paths when
804 // scanning install directories.
805 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700806 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800807 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800808 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700814 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700817 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 /**
820 * Out of paranoia, ensure that everything in the boot class
821 * path has been dexed.
822 */
823 String bootClassPath = System.getProperty("java.boot.class.path");
824 if (bootClassPath != null) {
825 String[] paths = splitString(bootClassPath, ':');
826 for (int i=0; i<paths.length; i++) {
827 try {
828 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
829 libFiles.add(paths[i]);
830 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700831 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800834 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800836 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 }
838 }
839 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800840 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 /**
844 * Also ensure all external libraries have had dexopt run on them.
845 */
846 if (mSharedLibraries.size() > 0) {
847 Iterator<String> libs = mSharedLibraries.values().iterator();
848 while (libs.hasNext()) {
849 String lib = libs.next();
850 try {
851 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
852 libFiles.add(lib);
853 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700854 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800857 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800859 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 }
861 }
862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 // Gross hack for now: we know this file doesn't contain any
865 // code, so don't dexopt it to avoid the resulting log spew.
866 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 /**
869 * And there are a number of commands implemented in Java, which
870 * we currently need to do the dexopt on so that they can be
871 * run from a non-root shell.
872 */
873 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700874 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 for (int i=0; i<frameworkFiles.length; i++) {
876 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
877 String path = libPath.getPath();
878 // Skip the file if we alrady did it.
879 if (libFiles.contains(path)) {
880 continue;
881 }
882 // Skip the file if it is not a type we want to dexopt.
883 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
884 continue;
885 }
886 try {
887 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
888 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700889 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
891 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800892 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800894 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 }
896 }
897 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800898
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700899 if (didDexOpt) {
900 // If we had to do a dexopt of one of the previous
901 // things, then something on the system has changed.
902 // Consider this significant, and wipe away all other
903 // existing dexopt files to ensure we don't leave any
904 // dangling around.
905 String[] files = mDalvikCacheDir.list();
906 if (files != null) {
907 for (int i=0; i<files.length; i++) {
908 String fn = files[i];
909 if (fn.startsWith("data@app@")
910 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800911 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700912 (new File(mDalvikCacheDir, fn)).delete();
913 }
914 }
915 }
916 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800918
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800919 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 mFrameworkInstallObserver = new AppDirObserver(
921 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
922 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700923 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
924 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700925 scanMode | SCAN_NO_DEX, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800926
927 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800928 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
929 mSystemInstallObserver = new AppDirObserver(
930 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
931 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700932 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700933 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800934
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700935 // Collect all vendor packages.
936 mVendorAppDir = new File("/vendor/app");
937 mVendorInstallObserver = new AppDirObserver(
938 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
939 mVendorInstallObserver.startWatching();
940 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700941 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700942
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800943 if (mInstaller != null) {
944 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
945 mInstaller.moveFiles();
946 }
947
948 // Prune any system packages that no longer exist.
949 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
950 while (psit.hasNext()) {
951 PackageSetting ps = psit.next();
952 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800953 && !mPackages.containsKey(ps.name)
954 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800955 psit.remove();
956 String msg = "System package " + ps.name
957 + " no longer exists; wiping its data";
958 reportSettingsProblem(Log.WARN, msg);
959 if (mInstaller != null) {
960 // XXX how to set useEncryptedFSDir for packages that
961 // are not encrypted?
962 mInstaller.remove(ps.name, true);
963 }
964 }
965 }
966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 mAppInstallDir = new File(dataDir, "app");
968 if (mInstaller == null) {
969 // Make sure these dirs exist, when we are running in
970 // the simulator.
971 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
972 }
973 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800974 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800975 //clean up list
976 for(int i = 0; i < deletePkgsList.size(); i++) {
977 //clean up here
978 cleanupInstallFailedPackage(deletePkgsList.get(i));
979 }
980 //delete tmp files
981 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982
983 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 SystemClock.uptimeMillis());
985 mAppInstallObserver = new AppDirObserver(
986 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
987 mAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700988 scanDirLI(mAppInstallDir, 0, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989
990 mDrmAppInstallObserver = new AppDirObserver(
991 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
992 mDrmAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700993 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
994 scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800996 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800998 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1000 + " seconds");
1001
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001002 // If the platform SDK has changed since the last time we booted,
1003 // we need to re-grant app permission to catch any new ones that
1004 // appear. This is really a hack, and means that apps can in some
1005 // cases get permissions that the user didn't initially explicitly
1006 // allow... it would be nice to have some better way to handle
1007 // this situation.
1008 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1009 != mSdkVersion;
1010 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1011 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1012 + "; regranting permissions for internal storage");
1013 mSettings.mInternalSdkPlatform = mSdkVersion;
1014
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001015 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016
1017 mSettings.writeLP();
1018
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001019 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 // Now after opening every single application zip, make sure they
1023 // are all flushed. Not really needed, but keeps things nice and
1024 // tidy.
1025 Runtime.getRuntime().gc();
1026 } // synchronized (mPackages)
1027 } // synchronized (mInstallLock)
1028 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 @Override
1031 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1032 throws RemoteException {
1033 try {
1034 return super.onTransact(code, data, reply, flags);
1035 } catch (RuntimeException e) {
1036 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001037 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 }
1039 throw e;
1040 }
1041 }
1042
Dianne Hackborne6620b22010-01-22 14:46:21 -08001043 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001044 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001046 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1047 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001049 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001050 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
1052 } else {
1053 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001054 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 File dataDir = new File(pkg.applicationInfo.dataDir);
1056 dataDir.delete();
1057 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001058 if (ps.codePath != null) {
1059 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001060 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001061 }
1062 }
1063 if (ps.resourcePath != null) {
1064 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001065 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001066 }
1067 }
1068 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 }
1070
1071 void readPermissions() {
1072 // Read permissions from .../etc/permission directory.
1073 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1074 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001075 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 return;
1077 }
1078 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001079 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 return;
1081 }
1082
1083 // Iterate over the files in the directory and scan .xml files
1084 for (File f : libraryDir.listFiles()) {
1085 // We'll read platform.xml last
1086 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1087 continue;
1088 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001091 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 continue;
1093 }
1094 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001095 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001096 continue;
1097 }
1098
1099 readPermissionsFromXml(f);
1100 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1103 final File permFile = new File(Environment.getRootDirectory(),
1104 "etc/permissions/platform.xml");
1105 readPermissionsFromXml(permFile);
1106 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001107
1108 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 FileReader permReader = null;
1110 try {
1111 permReader = new FileReader(permFile);
1112 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001113 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 return;
1115 }
1116
1117 try {
1118 XmlPullParser parser = Xml.newPullParser();
1119 parser.setInput(permReader);
1120
1121 XmlUtils.beginDocument(parser, "permissions");
1122
1123 while (true) {
1124 XmlUtils.nextElement(parser);
1125 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1126 break;
1127 }
1128
1129 String name = parser.getName();
1130 if ("group".equals(name)) {
1131 String gidStr = parser.getAttributeValue(null, "gid");
1132 if (gidStr != null) {
1133 int gid = Integer.parseInt(gidStr);
1134 mGlobalGids = appendInt(mGlobalGids, gid);
1135 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001136 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001137 + parser.getPositionDescription());
1138 }
1139
1140 XmlUtils.skipCurrentTag(parser);
1141 continue;
1142 } else if ("permission".equals(name)) {
1143 String perm = parser.getAttributeValue(null, "name");
1144 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001145 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 + parser.getPositionDescription());
1147 XmlUtils.skipCurrentTag(parser);
1148 continue;
1149 }
1150 perm = perm.intern();
1151 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 } else if ("assign-permission".equals(name)) {
1154 String perm = parser.getAttributeValue(null, "name");
1155 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001156 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 + parser.getPositionDescription());
1158 XmlUtils.skipCurrentTag(parser);
1159 continue;
1160 }
1161 String uidStr = parser.getAttributeValue(null, "uid");
1162 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001163 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 + parser.getPositionDescription());
1165 XmlUtils.skipCurrentTag(parser);
1166 continue;
1167 }
1168 int uid = Process.getUidForName(uidStr);
1169 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001170 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 + uidStr + "\" at "
1172 + parser.getPositionDescription());
1173 XmlUtils.skipCurrentTag(parser);
1174 continue;
1175 }
1176 perm = perm.intern();
1177 HashSet<String> perms = mSystemPermissions.get(uid);
1178 if (perms == null) {
1179 perms = new HashSet<String>();
1180 mSystemPermissions.put(uid, perms);
1181 }
1182 perms.add(perm);
1183 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001184
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 } else if ("library".equals(name)) {
1186 String lname = parser.getAttributeValue(null, "name");
1187 String lfile = parser.getAttributeValue(null, "file");
1188 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001189 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 + parser.getPositionDescription());
1191 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001192 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 + parser.getPositionDescription());
1194 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001195 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001196 mSharedLibraries.put(lname, lfile);
1197 }
1198 XmlUtils.skipCurrentTag(parser);
1199 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001200
Dianne Hackborn49237342009-08-27 20:08:01 -07001201 } else if ("feature".equals(name)) {
1202 String fname = parser.getAttributeValue(null, "name");
1203 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001204 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001205 + parser.getPositionDescription());
1206 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001207 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001208 FeatureInfo fi = new FeatureInfo();
1209 fi.name = fname;
1210 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
1212 XmlUtils.skipCurrentTag(parser);
1213 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 } else {
1216 XmlUtils.skipCurrentTag(parser);
1217 continue;
1218 }
1219
1220 }
1221 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001222 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001224 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
1226 }
1227
1228 void readPermission(XmlPullParser parser, String name)
1229 throws IOException, XmlPullParserException {
1230
1231 name = name.intern();
1232
1233 BasePermission bp = mSettings.mPermissions.get(name);
1234 if (bp == null) {
1235 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1236 mSettings.mPermissions.put(name, bp);
1237 }
1238 int outerDepth = parser.getDepth();
1239 int type;
1240 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1241 && (type != XmlPullParser.END_TAG
1242 || parser.getDepth() > outerDepth)) {
1243 if (type == XmlPullParser.END_TAG
1244 || type == XmlPullParser.TEXT) {
1245 continue;
1246 }
1247
1248 String tagName = parser.getName();
1249 if ("group".equals(tagName)) {
1250 String gidStr = parser.getAttributeValue(null, "gid");
1251 if (gidStr != null) {
1252 int gid = Process.getGidForName(gidStr);
1253 bp.gids = appendInt(bp.gids, gid);
1254 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001255 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 + parser.getPositionDescription());
1257 }
1258 }
1259 XmlUtils.skipCurrentTag(parser);
1260 }
1261 }
1262
1263 static int[] appendInt(int[] cur, int val) {
1264 if (cur == null) {
1265 return new int[] { val };
1266 }
1267 final int N = cur.length;
1268 for (int i=0; i<N; i++) {
1269 if (cur[i] == val) {
1270 return cur;
1271 }
1272 }
1273 int[] ret = new int[N+1];
1274 System.arraycopy(cur, 0, ret, 0, N);
1275 ret[N] = val;
1276 return ret;
1277 }
1278
1279 static int[] appendInts(int[] cur, int[] add) {
1280 if (add == null) return cur;
1281 if (cur == null) return add;
1282 final int N = add.length;
1283 for (int i=0; i<N; i++) {
1284 cur = appendInt(cur, add[i]);
1285 }
1286 return cur;
1287 }
1288
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001289 static int[] removeInt(int[] cur, int val) {
1290 if (cur == null) {
1291 return null;
1292 }
1293 final int N = cur.length;
1294 for (int i=0; i<N; i++) {
1295 if (cur[i] == val) {
1296 int[] ret = new int[N-1];
1297 if (i > 0) {
1298 System.arraycopy(cur, 0, ret, 0, i);
1299 }
1300 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001301 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001302 }
1303 return ret;
1304 }
1305 }
1306 return cur;
1307 }
1308
1309 static int[] removeInts(int[] cur, int[] rem) {
1310 if (rem == null) return cur;
1311 if (cur == null) return cur;
1312 final int N = rem.length;
1313 for (int i=0; i<N; i++) {
1314 cur = removeInt(cur, rem[i]);
1315 }
1316 return cur;
1317 }
1318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001320 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1321 // The package has been uninstalled but has retained data and resources.
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001322 return PackageParser.generatePackageInfo(p, null, flags, 0, 0);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 final PackageSetting ps = (PackageSetting)p.mExtras;
1325 if (ps == null) {
1326 return null;
1327 }
1328 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001329 return PackageParser.generatePackageInfo(p, gp.gids, flags,
1330 ps.firstInstallTime, ps.lastUpdateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 }
1332
1333 public PackageInfo getPackageInfo(String packageName, int flags) {
1334 synchronized (mPackages) {
1335 PackageParser.Package p = mPackages.get(packageName);
1336 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001337 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 + ": " + p);
1339 if (p != null) {
1340 return generatePackageInfo(p, flags);
1341 }
1342 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1343 return generatePackageInfoFromSettingsLP(packageName, flags);
1344 }
1345 }
1346 return null;
1347 }
1348
Dianne Hackborn47096932010-02-11 15:57:09 -08001349 public String[] currentToCanonicalPackageNames(String[] names) {
1350 String[] out = new String[names.length];
1351 synchronized (mPackages) {
1352 for (int i=names.length-1; i>=0; i--) {
1353 PackageSetting ps = mSettings.mPackages.get(names[i]);
1354 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1355 }
1356 }
1357 return out;
1358 }
1359
1360 public String[] canonicalToCurrentPackageNames(String[] names) {
1361 String[] out = new String[names.length];
1362 synchronized (mPackages) {
1363 for (int i=names.length-1; i>=0; i--) {
1364 String cur = mSettings.mRenamedPackages.get(names[i]);
1365 out[i] = cur != null ? cur : names[i];
1366 }
1367 }
1368 return out;
1369 }
1370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 public int getPackageUid(String packageName) {
1372 synchronized (mPackages) {
1373 PackageParser.Package p = mPackages.get(packageName);
1374 if(p != null) {
1375 return p.applicationInfo.uid;
1376 }
1377 PackageSetting ps = mSettings.mPackages.get(packageName);
1378 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1379 return -1;
1380 }
1381 p = ps.pkg;
1382 return p != null ? p.applicationInfo.uid : -1;
1383 }
1384 }
1385
1386 public int[] getPackageGids(String packageName) {
1387 synchronized (mPackages) {
1388 PackageParser.Package p = mPackages.get(packageName);
1389 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001390 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 + ": " + p);
1392 if (p != null) {
1393 final PackageSetting ps = (PackageSetting)p.mExtras;
1394 final SharedUserSetting suid = ps.sharedUser;
1395 return suid != null ? suid.gids : ps.gids;
1396 }
1397 }
1398 // stupid thing to indicate an error.
1399 return new int[0];
1400 }
1401
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001402 static final PermissionInfo generatePermissionInfo(
1403 BasePermission bp, int flags) {
1404 if (bp.perm != null) {
1405 return PackageParser.generatePermissionInfo(bp.perm, flags);
1406 }
1407 PermissionInfo pi = new PermissionInfo();
1408 pi.name = bp.name;
1409 pi.packageName = bp.sourcePackage;
1410 pi.nonLocalizedLabel = bp.name;
1411 pi.protectionLevel = bp.protectionLevel;
1412 return pi;
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 public PermissionInfo getPermissionInfo(String name, int flags) {
1416 synchronized (mPackages) {
1417 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001418 if (p != null) {
1419 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 }
1421 return null;
1422 }
1423 }
1424
1425 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1426 synchronized (mPackages) {
1427 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1428 for (BasePermission p : mSettings.mPermissions.values()) {
1429 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001430 if (p.perm == null || p.perm.info.group == null) {
1431 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 }
1433 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001434 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1436 }
1437 }
1438 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 if (out.size() > 0) {
1441 return out;
1442 }
1443 return mPermissionGroups.containsKey(group) ? out : null;
1444 }
1445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1448 synchronized (mPackages) {
1449 return PackageParser.generatePermissionGroupInfo(
1450 mPermissionGroups.get(name), flags);
1451 }
1452 }
1453
1454 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1455 synchronized (mPackages) {
1456 final int N = mPermissionGroups.size();
1457 ArrayList<PermissionGroupInfo> out
1458 = new ArrayList<PermissionGroupInfo>(N);
1459 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1460 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1461 }
1462 return out;
1463 }
1464 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1467 PackageSetting ps = mSettings.mPackages.get(packageName);
1468 if(ps != null) {
1469 if(ps.pkg == null) {
1470 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1471 if(pInfo != null) {
1472 return pInfo.applicationInfo;
1473 }
1474 return null;
1475 }
1476 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1477 }
1478 return null;
1479 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1482 PackageSetting ps = mSettings.mPackages.get(packageName);
1483 if(ps != null) {
1484 if(ps.pkg == null) {
1485 ps.pkg = new PackageParser.Package(packageName);
1486 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001487 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1488 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1489 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1490 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001491 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001492 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
1494 return generatePackageInfo(ps.pkg, flags);
1495 }
1496 return null;
1497 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1500 synchronized (mPackages) {
1501 PackageParser.Package p = mPackages.get(packageName);
1502 if (Config.LOGV) Log.v(
1503 TAG, "getApplicationInfo " + packageName
1504 + ": " + p);
1505 if (p != null) {
1506 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001507 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
1509 if ("android".equals(packageName)||"system".equals(packageName)) {
1510 return mAndroidApplication;
1511 }
1512 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1513 return generateApplicationInfoFromSettingsLP(packageName, flags);
1514 }
1515 }
1516 return null;
1517 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001518
1519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1521 mContext.enforceCallingOrSelfPermission(
1522 android.Manifest.permission.CLEAR_APP_CACHE, null);
1523 // Queue up an async operation since clearing cache may take a little while.
1524 mHandler.post(new Runnable() {
1525 public void run() {
1526 mHandler.removeCallbacks(this);
1527 int retCode = -1;
1528 if (mInstaller != null) {
1529 retCode = mInstaller.freeCache(freeStorageSize);
1530 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001531 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 }
1533 } //end if mInstaller
1534 if (observer != null) {
1535 try {
1536 observer.onRemoveCompleted(null, (retCode >= 0));
1537 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001538 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 }
1540 }
1541 }
1542 });
1543 }
1544
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001545 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001546 mContext.enforceCallingOrSelfPermission(
1547 android.Manifest.permission.CLEAR_APP_CACHE, null);
1548 // Queue up an async operation since clearing cache may take a little while.
1549 mHandler.post(new Runnable() {
1550 public void run() {
1551 mHandler.removeCallbacks(this);
1552 int retCode = -1;
1553 if (mInstaller != null) {
1554 retCode = mInstaller.freeCache(freeStorageSize);
1555 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001556 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001557 }
1558 }
1559 if(pi != null) {
1560 try {
1561 // Callback via pending intent
1562 int code = (retCode >= 0) ? 1 : 0;
1563 pi.sendIntent(null, code, null,
1564 null, null);
1565 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001566 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001567 }
1568 }
1569 }
1570 });
1571 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1574 synchronized (mPackages) {
1575 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001576
1577 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001579 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 }
1581 if (mResolveComponentName.equals(component)) {
1582 return mResolveActivity;
1583 }
1584 }
1585 return null;
1586 }
1587
1588 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1589 synchronized (mPackages) {
1590 PackageParser.Activity a = mReceivers.mActivities.get(component);
1591 if (Config.LOGV) Log.v(
1592 TAG, "getReceiverInfo " + component + ": " + a);
1593 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1594 return PackageParser.generateActivityInfo(a, flags);
1595 }
1596 }
1597 return null;
1598 }
1599
1600 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1601 synchronized (mPackages) {
1602 PackageParser.Service s = mServices.mServices.get(component);
1603 if (Config.LOGV) Log.v(
1604 TAG, "getServiceInfo " + component + ": " + s);
1605 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1606 return PackageParser.generateServiceInfo(s, flags);
1607 }
1608 }
1609 return null;
1610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001611
Dianne Hackborn361199b2010-08-30 17:42:07 -07001612 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1613 synchronized (mPackages) {
1614 PackageParser.Provider p = mProvidersByComponent.get(component);
1615 if (Config.LOGV) Log.v(
1616 TAG, "getProviderInfo " + component + ": " + p);
1617 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1618 return PackageParser.generateProviderInfo(p, flags);
1619 }
1620 }
1621 return null;
1622 }
1623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001624 public String[] getSystemSharedLibraryNames() {
1625 Set<String> libSet;
1626 synchronized (mPackages) {
1627 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001628 int size = libSet.size();
1629 if (size > 0) {
1630 String[] libs = new String[size];
1631 libSet.toArray(libs);
1632 return libs;
1633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001635 return null;
1636 }
1637
1638 public FeatureInfo[] getSystemAvailableFeatures() {
1639 Collection<FeatureInfo> featSet;
1640 synchronized (mPackages) {
1641 featSet = mAvailableFeatures.values();
1642 int size = featSet.size();
1643 if (size > 0) {
1644 FeatureInfo[] features = new FeatureInfo[size+1];
1645 featSet.toArray(features);
1646 FeatureInfo fi = new FeatureInfo();
1647 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1648 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1649 features[size] = fi;
1650 return features;
1651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 }
1653 return null;
1654 }
1655
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001656 public boolean hasSystemFeature(String name) {
1657 synchronized (mPackages) {
1658 return mAvailableFeatures.containsKey(name);
1659 }
1660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001662 public int checkPermission(String permName, String pkgName) {
1663 synchronized (mPackages) {
1664 PackageParser.Package p = mPackages.get(pkgName);
1665 if (p != null && p.mExtras != null) {
1666 PackageSetting ps = (PackageSetting)p.mExtras;
1667 if (ps.sharedUser != null) {
1668 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1669 return PackageManager.PERMISSION_GRANTED;
1670 }
1671 } else if (ps.grantedPermissions.contains(permName)) {
1672 return PackageManager.PERMISSION_GRANTED;
1673 }
1674 }
1675 }
1676 return PackageManager.PERMISSION_DENIED;
1677 }
1678
1679 public int checkUidPermission(String permName, int uid) {
1680 synchronized (mPackages) {
1681 Object obj = mSettings.getUserIdLP(uid);
1682 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001683 GrantedPermissions gp = (GrantedPermissions)obj;
1684 if (gp.grantedPermissions.contains(permName)) {
1685 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
1687 } else {
1688 HashSet<String> perms = mSystemPermissions.get(uid);
1689 if (perms != null && perms.contains(permName)) {
1690 return PackageManager.PERMISSION_GRANTED;
1691 }
1692 }
1693 }
1694 return PackageManager.PERMISSION_DENIED;
1695 }
1696
1697 private BasePermission findPermissionTreeLP(String permName) {
1698 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1699 if (permName.startsWith(bp.name) &&
1700 permName.length() > bp.name.length() &&
1701 permName.charAt(bp.name.length()) == '.') {
1702 return bp;
1703 }
1704 }
1705 return null;
1706 }
1707
1708 private BasePermission checkPermissionTreeLP(String permName) {
1709 if (permName != null) {
1710 BasePermission bp = findPermissionTreeLP(permName);
1711 if (bp != null) {
1712 if (bp.uid == Binder.getCallingUid()) {
1713 return bp;
1714 }
1715 throw new SecurityException("Calling uid "
1716 + Binder.getCallingUid()
1717 + " is not allowed to add to permission tree "
1718 + bp.name + " owned by uid " + bp.uid);
1719 }
1720 }
1721 throw new SecurityException("No permission tree found for " + permName);
1722 }
1723
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001724 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1725 if (s1 == null) {
1726 return s2 == null;
1727 }
1728 if (s2 == null) {
1729 return false;
1730 }
1731 if (s1.getClass() != s2.getClass()) {
1732 return false;
1733 }
1734 return s1.equals(s2);
1735 }
1736
1737 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1738 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001739 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001740 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1741 if (!compareStrings(pi1.name, pi2.name)) return false;
1742 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1743 // We'll take care of setting this one.
1744 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1745 // These are not currently stored in settings.
1746 //if (!compareStrings(pi1.group, pi2.group)) return false;
1747 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1748 //if (pi1.labelRes != pi2.labelRes) return false;
1749 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1750 return true;
1751 }
1752
1753 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1754 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1755 throw new SecurityException("Label must be specified in permission");
1756 }
1757 BasePermission tree = checkPermissionTreeLP(info.name);
1758 BasePermission bp = mSettings.mPermissions.get(info.name);
1759 boolean added = bp == null;
1760 boolean changed = true;
1761 if (added) {
1762 bp = new BasePermission(info.name, tree.sourcePackage,
1763 BasePermission.TYPE_DYNAMIC);
1764 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1765 throw new SecurityException(
1766 "Not allowed to modify non-dynamic permission "
1767 + info.name);
1768 } else {
1769 if (bp.protectionLevel == info.protectionLevel
1770 && bp.perm.owner.equals(tree.perm.owner)
1771 && bp.uid == tree.uid
1772 && comparePermissionInfos(bp.perm.info, info)) {
1773 changed = false;
1774 }
1775 }
1776 bp.protectionLevel = info.protectionLevel;
1777 bp.perm = new PackageParser.Permission(tree.perm.owner,
1778 new PermissionInfo(info));
1779 bp.perm.info.packageName = tree.perm.info.packageName;
1780 bp.uid = tree.uid;
1781 if (added) {
1782 mSettings.mPermissions.put(info.name, bp);
1783 }
1784 if (changed) {
1785 if (!async) {
1786 mSettings.writeLP();
1787 } else {
1788 scheduleWriteSettingsLocked();
1789 }
1790 }
1791 return added;
1792 }
1793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 public boolean addPermission(PermissionInfo info) {
1795 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001796 return addPermissionLocked(info, false);
1797 }
1798 }
1799
1800 public boolean addPermissionAsync(PermissionInfo info) {
1801 synchronized (mPackages) {
1802 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804 }
1805
1806 public void removePermission(String name) {
1807 synchronized (mPackages) {
1808 checkPermissionTreeLP(name);
1809 BasePermission bp = mSettings.mPermissions.get(name);
1810 if (bp != null) {
1811 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1812 throw new SecurityException(
1813 "Not allowed to modify non-dynamic permission "
1814 + name);
1815 }
1816 mSettings.mPermissions.remove(name);
1817 mSettings.writeLP();
1818 }
1819 }
1820 }
1821
Dianne Hackborn854060af2009-07-09 18:14:31 -07001822 public boolean isProtectedBroadcast(String actionName) {
1823 synchronized (mPackages) {
1824 return mProtectedBroadcasts.contains(actionName);
1825 }
1826 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001828 public int checkSignatures(String pkg1, String pkg2) {
1829 synchronized (mPackages) {
1830 PackageParser.Package p1 = mPackages.get(pkg1);
1831 PackageParser.Package p2 = mPackages.get(pkg2);
1832 if (p1 == null || p1.mExtras == null
1833 || p2 == null || p2.mExtras == null) {
1834 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1835 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001836 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001837 }
1838 }
1839
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001840 public int checkUidSignatures(int uid1, int uid2) {
1841 synchronized (mPackages) {
1842 Signature[] s1;
1843 Signature[] s2;
1844 Object obj = mSettings.getUserIdLP(uid1);
1845 if (obj != null) {
1846 if (obj instanceof SharedUserSetting) {
1847 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1848 } else if (obj instanceof PackageSetting) {
1849 s1 = ((PackageSetting)obj).signatures.mSignatures;
1850 } else {
1851 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1852 }
1853 } else {
1854 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1855 }
1856 obj = mSettings.getUserIdLP(uid2);
1857 if (obj != null) {
1858 if (obj instanceof SharedUserSetting) {
1859 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1860 } else if (obj instanceof PackageSetting) {
1861 s2 = ((PackageSetting)obj).signatures.mSignatures;
1862 } else {
1863 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1864 }
1865 } else {
1866 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1867 }
1868 return checkSignaturesLP(s1, s2);
1869 }
1870 }
1871
1872 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1873 if (s1 == null) {
1874 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1876 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1877 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001878 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1880 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001881 HashSet<Signature> set1 = new HashSet<Signature>();
1882 for (Signature sig : s1) {
1883 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001885 HashSet<Signature> set2 = new HashSet<Signature>();
1886 for (Signature sig : s2) {
1887 set2.add(sig);
1888 }
1889 // Make sure s2 contains all signatures in s1.
1890 if (set1.equals(set2)) {
1891 return PackageManager.SIGNATURE_MATCH;
1892 }
1893 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895
1896 public String[] getPackagesForUid(int uid) {
1897 synchronized (mPackages) {
1898 Object obj = mSettings.getUserIdLP(uid);
1899 if (obj instanceof SharedUserSetting) {
1900 SharedUserSetting sus = (SharedUserSetting)obj;
1901 final int N = sus.packages.size();
1902 String[] res = new String[N];
1903 Iterator<PackageSetting> it = sus.packages.iterator();
1904 int i=0;
1905 while (it.hasNext()) {
1906 res[i++] = it.next().name;
1907 }
1908 return res;
1909 } else if (obj instanceof PackageSetting) {
1910 PackageSetting ps = (PackageSetting)obj;
1911 return new String[] { ps.name };
1912 }
1913 }
1914 return null;
1915 }
1916
1917 public String getNameForUid(int uid) {
1918 synchronized (mPackages) {
1919 Object obj = mSettings.getUserIdLP(uid);
1920 if (obj instanceof SharedUserSetting) {
1921 SharedUserSetting sus = (SharedUserSetting)obj;
1922 return sus.name + ":" + sus.userId;
1923 } else if (obj instanceof PackageSetting) {
1924 PackageSetting ps = (PackageSetting)obj;
1925 return ps.name;
1926 }
1927 }
1928 return null;
1929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 public int getUidForSharedUser(String sharedUserName) {
1932 if(sharedUserName == null) {
1933 return -1;
1934 }
1935 synchronized (mPackages) {
1936 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1937 if(suid == null) {
1938 return -1;
1939 }
1940 return suid.userId;
1941 }
1942 }
1943
1944 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1945 int flags) {
1946 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001947 return chooseBestActivity(intent, resolvedType, flags, query);
1948 }
1949
Mihai Predaeae850c2009-05-13 10:13:48 +02001950 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1951 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 if (query != null) {
1953 final int N = query.size();
1954 if (N == 1) {
1955 return query.get(0);
1956 } else if (N > 1) {
1957 // If there is more than one activity with the same priority,
1958 // then let the user decide between them.
1959 ResolveInfo r0 = query.get(0);
1960 ResolveInfo r1 = query.get(1);
1961 if (false) {
1962 System.out.println(r0.activityInfo.name +
1963 "=" + r0.priority + " vs " +
1964 r1.activityInfo.name +
1965 "=" + r1.priority);
1966 }
1967 // If the first activity has a higher priority, or a different
1968 // default, then it is always desireable to pick it.
1969 if (r0.priority != r1.priority
1970 || r0.preferredOrder != r1.preferredOrder
1971 || r0.isDefault != r1.isDefault) {
1972 return query.get(0);
1973 }
1974 // If we have saved a preference for a preferred activity for
1975 // this Intent, use that.
1976 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1977 flags, query, r0.priority);
1978 if (ri != null) {
1979 return ri;
1980 }
1981 return mResolveInfo;
1982 }
1983 }
1984 return null;
1985 }
1986
1987 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1988 int flags, List<ResolveInfo> query, int priority) {
1989 synchronized (mPackages) {
1990 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1991 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001992 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1994 if (prefs != null && prefs.size() > 0) {
1995 // First figure out how good the original match set is.
1996 // We will only allow preferred activities that came
1997 // from the same match quality.
1998 int match = 0;
1999 final int N = query.size();
2000 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2001 for (int j=0; j<N; j++) {
2002 ResolveInfo ri = query.get(j);
2003 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2004 + ": 0x" + Integer.toHexString(match));
2005 if (ri.match > match) match = ri.match;
2006 }
2007 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2008 + Integer.toHexString(match));
2009 match &= IntentFilter.MATCH_CATEGORY_MASK;
2010 final int M = prefs.size();
2011 for (int i=0; i<M; i++) {
2012 PreferredActivity pa = prefs.get(i);
2013 if (pa.mMatch != match) {
2014 continue;
2015 }
2016 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2017 if (DEBUG_PREFERRED) {
2018 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002019 if (ai != null) {
2020 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2021 } else {
2022 Log.v(TAG, " null");
2023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 }
2025 if (ai != null) {
2026 for (int j=0; j<N; j++) {
2027 ResolveInfo ri = query.get(j);
2028 if (!ri.activityInfo.applicationInfo.packageName
2029 .equals(ai.applicationInfo.packageName)) {
2030 continue;
2031 }
2032 if (!ri.activityInfo.name.equals(ai.name)) {
2033 continue;
2034 }
2035
2036 // Okay we found a previously set preferred app.
2037 // If the result set is different from when this
2038 // was created, we need to clear it and re-ask the
2039 // user their preference.
2040 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002041 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 + intent + " type " + resolvedType);
2043 mSettings.mPreferredActivities.removeFilter(pa);
2044 return null;
2045 }
2046
2047 // Yay!
2048 return ri;
2049 }
2050 }
2051 }
2052 }
2053 }
2054 return null;
2055 }
2056
2057 public List<ResolveInfo> queryIntentActivities(Intent intent,
2058 String resolvedType, int flags) {
2059 ComponentName comp = intent.getComponent();
2060 if (comp != null) {
2061 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2062 ActivityInfo ai = getActivityInfo(comp, flags);
2063 if (ai != null) {
2064 ResolveInfo ri = new ResolveInfo();
2065 ri.activityInfo = ai;
2066 list.add(ri);
2067 }
2068 return list;
2069 }
2070
2071 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002072 String pkgName = intent.getPackage();
2073 if (pkgName == null) {
2074 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2075 resolvedType, flags);
2076 }
2077 PackageParser.Package pkg = mPackages.get(pkgName);
2078 if (pkg != null) {
2079 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2080 resolvedType, flags, pkg.activities);
2081 }
2082 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 }
2084 }
2085
2086 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2087 Intent[] specifics, String[] specificTypes, Intent intent,
2088 String resolvedType, int flags) {
2089 final String resultsAction = intent.getAction();
2090
2091 List<ResolveInfo> results = queryIntentActivities(
2092 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2093 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2094
2095 int specificsPos = 0;
2096 int N;
2097
2098 // todo: note that the algorithm used here is O(N^2). This
2099 // isn't a problem in our current environment, but if we start running
2100 // into situations where we have more than 5 or 10 matches then this
2101 // should probably be changed to something smarter...
2102
2103 // First we go through and resolve each of the specific items
2104 // that were supplied, taking care of removing any corresponding
2105 // duplicate items in the generic resolve list.
2106 if (specifics != null) {
2107 for (int i=0; i<specifics.length; i++) {
2108 final Intent sintent = specifics[i];
2109 if (sintent == null) {
2110 continue;
2111 }
2112
2113 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2114 String action = sintent.getAction();
2115 if (resultsAction != null && resultsAction.equals(action)) {
2116 // If this action was explicitly requested, then don't
2117 // remove things that have it.
2118 action = null;
2119 }
2120 ComponentName comp = sintent.getComponent();
2121 ResolveInfo ri = null;
2122 ActivityInfo ai = null;
2123 if (comp == null) {
2124 ri = resolveIntent(
2125 sintent,
2126 specificTypes != null ? specificTypes[i] : null,
2127 flags);
2128 if (ri == null) {
2129 continue;
2130 }
2131 if (ri == mResolveInfo) {
2132 // ACK! Must do something better with this.
2133 }
2134 ai = ri.activityInfo;
2135 comp = new ComponentName(ai.applicationInfo.packageName,
2136 ai.name);
2137 } else {
2138 ai = getActivityInfo(comp, flags);
2139 if (ai == null) {
2140 continue;
2141 }
2142 }
2143
2144 // Look for any generic query activities that are duplicates
2145 // of this specific one, and remove them from the results.
2146 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2147 N = results.size();
2148 int j;
2149 for (j=specificsPos; j<N; j++) {
2150 ResolveInfo sri = results.get(j);
2151 if ((sri.activityInfo.name.equals(comp.getClassName())
2152 && sri.activityInfo.applicationInfo.packageName.equals(
2153 comp.getPackageName()))
2154 || (action != null && sri.filter.matchAction(action))) {
2155 results.remove(j);
2156 if (Config.LOGV) Log.v(
2157 TAG, "Removing duplicate item from " + j
2158 + " due to specific " + specificsPos);
2159 if (ri == null) {
2160 ri = sri;
2161 }
2162 j--;
2163 N--;
2164 }
2165 }
2166
2167 // Add this specific item to its proper place.
2168 if (ri == null) {
2169 ri = new ResolveInfo();
2170 ri.activityInfo = ai;
2171 }
2172 results.add(specificsPos, ri);
2173 ri.specificIndex = i;
2174 specificsPos++;
2175 }
2176 }
2177
2178 // Now we go through the remaining generic results and remove any
2179 // duplicate actions that are found here.
2180 N = results.size();
2181 for (int i=specificsPos; i<N-1; i++) {
2182 final ResolveInfo rii = results.get(i);
2183 if (rii.filter == null) {
2184 continue;
2185 }
2186
2187 // Iterate over all of the actions of this result's intent
2188 // filter... typically this should be just one.
2189 final Iterator<String> it = rii.filter.actionsIterator();
2190 if (it == null) {
2191 continue;
2192 }
2193 while (it.hasNext()) {
2194 final String action = it.next();
2195 if (resultsAction != null && resultsAction.equals(action)) {
2196 // If this action was explicitly requested, then don't
2197 // remove things that have it.
2198 continue;
2199 }
2200 for (int j=i+1; j<N; j++) {
2201 final ResolveInfo rij = results.get(j);
2202 if (rij.filter != null && rij.filter.hasAction(action)) {
2203 results.remove(j);
2204 if (Config.LOGV) Log.v(
2205 TAG, "Removing duplicate item from " + j
2206 + " due to action " + action + " at " + i);
2207 j--;
2208 N--;
2209 }
2210 }
2211 }
2212
2213 // If the caller didn't request filter information, drop it now
2214 // so we don't have to marshall/unmarshall it.
2215 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2216 rii.filter = null;
2217 }
2218 }
2219
2220 // Filter out the caller activity if so requested.
2221 if (caller != null) {
2222 N = results.size();
2223 for (int i=0; i<N; i++) {
2224 ActivityInfo ainfo = results.get(i).activityInfo;
2225 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2226 && caller.getClassName().equals(ainfo.name)) {
2227 results.remove(i);
2228 break;
2229 }
2230 }
2231 }
2232
2233 // If the caller didn't request filter information,
2234 // drop them now so we don't have to
2235 // marshall/unmarshall it.
2236 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2237 N = results.size();
2238 for (int i=0; i<N; i++) {
2239 results.get(i).filter = null;
2240 }
2241 }
2242
2243 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2244 return results;
2245 }
2246
2247 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2248 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002249 ComponentName comp = intent.getComponent();
2250 if (comp != null) {
2251 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2252 ActivityInfo ai = getReceiverInfo(comp, flags);
2253 if (ai != null) {
2254 ResolveInfo ri = new ResolveInfo();
2255 ri.activityInfo = ai;
2256 list.add(ri);
2257 }
2258 return list;
2259 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002262 String pkgName = intent.getPackage();
2263 if (pkgName == null) {
2264 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2265 resolvedType, flags);
2266 }
2267 PackageParser.Package pkg = mPackages.get(pkgName);
2268 if (pkg != null) {
2269 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2270 resolvedType, flags, pkg.receivers);
2271 }
2272 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 }
2274 }
2275
2276 public ResolveInfo resolveService(Intent intent, String resolvedType,
2277 int flags) {
2278 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2279 flags);
2280 if (query != null) {
2281 if (query.size() >= 1) {
2282 // If there is more than one service with the same priority,
2283 // just arbitrarily pick the first one.
2284 return query.get(0);
2285 }
2286 }
2287 return null;
2288 }
2289
2290 public List<ResolveInfo> queryIntentServices(Intent intent,
2291 String resolvedType, int flags) {
2292 ComponentName comp = intent.getComponent();
2293 if (comp != null) {
2294 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2295 ServiceInfo si = getServiceInfo(comp, flags);
2296 if (si != null) {
2297 ResolveInfo ri = new ResolveInfo();
2298 ri.serviceInfo = si;
2299 list.add(ri);
2300 }
2301 return list;
2302 }
2303
2304 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002305 String pkgName = intent.getPackage();
2306 if (pkgName == null) {
2307 return (List<ResolveInfo>)mServices.queryIntent(intent,
2308 resolvedType, flags);
2309 }
2310 PackageParser.Package pkg = mPackages.get(pkgName);
2311 if (pkg != null) {
2312 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2313 resolvedType, flags, pkg.services);
2314 }
2315 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 }
2317 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002318
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002319 public List<PackageInfo> getInstalledPackages(int flags) {
2320 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2321
2322 synchronized (mPackages) {
2323 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2324 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2325 while (i.hasNext()) {
2326 final PackageSetting ps = i.next();
2327 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2328 if(psPkg != null) {
2329 finalList.add(psPkg);
2330 }
2331 }
2332 }
2333 else {
2334 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2335 while (i.hasNext()) {
2336 final PackageParser.Package p = i.next();
2337 if (p.applicationInfo != null) {
2338 PackageInfo pi = generatePackageInfo(p, flags);
2339 if(pi != null) {
2340 finalList.add(pi);
2341 }
2342 }
2343 }
2344 }
2345 }
2346 return finalList;
2347 }
2348
2349 public List<ApplicationInfo> getInstalledApplications(int flags) {
2350 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2351 synchronized(mPackages) {
2352 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2353 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2354 while (i.hasNext()) {
2355 final PackageSetting ps = i.next();
2356 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2357 if(ai != null) {
2358 finalList.add(ai);
2359 }
2360 }
2361 }
2362 else {
2363 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2364 while (i.hasNext()) {
2365 final PackageParser.Package p = i.next();
2366 if (p.applicationInfo != null) {
2367 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2368 if(ai != null) {
2369 finalList.add(ai);
2370 }
2371 }
2372 }
2373 }
2374 }
2375 return finalList;
2376 }
2377
2378 public List<ApplicationInfo> getPersistentApplications(int flags) {
2379 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2380
2381 synchronized (mPackages) {
2382 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2383 while (i.hasNext()) {
2384 PackageParser.Package p = i.next();
2385 if (p.applicationInfo != null
2386 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002387 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002388 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 }
2390 }
2391 }
2392
2393 return finalList;
2394 }
2395
2396 public ProviderInfo resolveContentProvider(String name, int flags) {
2397 synchronized (mPackages) {
2398 final PackageParser.Provider provider = mProviders.get(name);
2399 return provider != null
2400 && mSettings.isEnabledLP(provider.info, flags)
2401 && (!mSafeMode || (provider.info.applicationInfo.flags
2402 &ApplicationInfo.FLAG_SYSTEM) != 0)
2403 ? PackageParser.generateProviderInfo(provider, flags)
2404 : null;
2405 }
2406 }
2407
Fred Quintana718d8a22009-04-29 17:53:20 -07002408 /**
2409 * @deprecated
2410 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 public void querySyncProviders(List outNames, List outInfo) {
2412 synchronized (mPackages) {
2413 Iterator<Map.Entry<String, PackageParser.Provider>> i
2414 = mProviders.entrySet().iterator();
2415
2416 while (i.hasNext()) {
2417 Map.Entry<String, PackageParser.Provider> entry = i.next();
2418 PackageParser.Provider p = entry.getValue();
2419
2420 if (p.syncable
2421 && (!mSafeMode || (p.info.applicationInfo.flags
2422 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2423 outNames.add(entry.getKey());
2424 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2425 }
2426 }
2427 }
2428 }
2429
2430 public List<ProviderInfo> queryContentProviders(String processName,
2431 int uid, int flags) {
2432 ArrayList<ProviderInfo> finalList = null;
2433
2434 synchronized (mPackages) {
2435 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2436 while (i.hasNext()) {
2437 PackageParser.Provider p = i.next();
2438 if (p.info.authority != null
2439 && (processName == null ||
2440 (p.info.processName.equals(processName)
2441 && p.info.applicationInfo.uid == uid))
2442 && mSettings.isEnabledLP(p.info, flags)
2443 && (!mSafeMode || (p.info.applicationInfo.flags
2444 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2445 if (finalList == null) {
2446 finalList = new ArrayList<ProviderInfo>(3);
2447 }
2448 finalList.add(PackageParser.generateProviderInfo(p,
2449 flags));
2450 }
2451 }
2452 }
2453
2454 if (finalList != null) {
2455 Collections.sort(finalList, mProviderInitOrderSorter);
2456 }
2457
2458 return finalList;
2459 }
2460
2461 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2462 int flags) {
2463 synchronized (mPackages) {
2464 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2465 return PackageParser.generateInstrumentationInfo(i, flags);
2466 }
2467 }
2468
2469 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2470 int flags) {
2471 ArrayList<InstrumentationInfo> finalList =
2472 new ArrayList<InstrumentationInfo>();
2473
2474 synchronized (mPackages) {
2475 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2476 while (i.hasNext()) {
2477 PackageParser.Instrumentation p = i.next();
2478 if (targetPackage == null
2479 || targetPackage.equals(p.info.targetPackage)) {
2480 finalList.add(PackageParser.generateInstrumentationInfo(p,
2481 flags));
2482 }
2483 }
2484 }
2485
2486 return finalList;
2487 }
2488
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002489 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002491 if (files == null) {
2492 Log.d(TAG, "No files in app dir " + dir);
2493 return;
2494 }
2495
2496 Log.d(TAG, "Scanning app dir " + dir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497
2498 int i;
2499 for (i=0; i<files.length; i++) {
2500 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002501 if (!isPackageFilename(files[i])) {
2502 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002503 continue;
2504 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002505 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002506 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002507 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002508 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2509 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002510 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002511 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002512 file.delete();
2513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 }
2515 }
2516
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002517 private static File getSettingsProblemFile() {
2518 File dataDir = Environment.getDataDirectory();
2519 File systemDir = new File(dataDir, "system");
2520 File fname = new File(systemDir, "uiderrors.txt");
2521 return fname;
2522 }
2523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 private static void reportSettingsProblem(int priority, String msg) {
2525 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002526 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 FileOutputStream out = new FileOutputStream(fname, true);
2528 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002529 SimpleDateFormat formatter = new SimpleDateFormat();
2530 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2531 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 pw.close();
2533 FileUtils.setPermissions(
2534 fname.toString(),
2535 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2536 -1, -1);
2537 } catch (java.io.IOException e) {
2538 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002539 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 }
2541
2542 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2543 PackageParser.Package pkg, File srcFile, int parseFlags) {
2544 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002545 if (ps != null
2546 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002547 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002548 if (ps.signatures.mSignatures != null
2549 && ps.signatures.mSignatures.length != 0) {
2550 // Optimization: reuse the existing cached certificates
2551 // if the package appears to be unchanged.
2552 pkg.mSignatures = ps.signatures.mSignatures;
2553 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 }
Jeff Browne7600722010-04-07 18:28:23 -07002555
2556 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002557 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002558 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2559 }
2560
2561 if (!pp.collectCertificates(pkg, parseFlags)) {
2562 mLastScanError = pp.getParseError();
2563 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
2565 }
2566 return true;
2567 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 /*
2570 * Scan a package and return the newly parsed package.
2571 * Returns null in case of errors and the error code is stored in mLastScanError
2572 */
2573 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002574 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002576 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002578 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002581 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 if (pkg == null) {
2583 mLastScanError = pp.getParseError();
2584 return null;
2585 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002586 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 PackageSetting updatedPkg;
2588 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002589 // Look to see if we already know about this package.
2590 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002591 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002592 // This package has been renamed to its original name. Let's
2593 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002594 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002595 }
2596 // If there was no original package, see one for the real package name.
2597 if (ps == null) {
2598 ps = mSettings.peekPackageLP(pkg.packageName);
2599 }
2600 // Check to see if this package could be hiding/updating a system
2601 // package. Must look for it either under the original or real
2602 // package name depending on our state.
2603 updatedPkg = mSettings.mDisabledSysPackages.get(
2604 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002606 // First check if this is a system package that may involve an update
2607 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002608 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002609 // The path has changed from what was last scanned... check the
2610 // version of the new path against what we have stored to determine
2611 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002612 if (pkg.mVersionCode < ps.versionCode) {
2613 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002614 // Ignore entry. Skip it.
2615 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002616 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002617 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002618 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2619 return null;
2620 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002621 // The current app on the system partion is better than
2622 // what we have updated to on the data partition; switch
2623 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002624 // At this point, its safely assumed that package installation for
2625 // apps in system partition will go through. If not there won't be a working
2626 // version of the app
2627 synchronized (mPackages) {
2628 // Just remove the loaded entries from package lists.
2629 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002630 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002631 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002632 + "reverting from " + ps.codePathString
2633 + ": new version " + pkg.mVersionCode
2634 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002635 InstallArgs args = new FileInstallArgs(ps.codePathString,
2636 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002637 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002638 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 }
2641 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002642 if (updatedPkg != null) {
2643 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2644 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2645 }
2646 // Verify certificates against what was last scanned
2647 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002648 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002649 return null;
2650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002651 // The apk is forward locked (not public) if its code and resources
2652 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002653 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002654 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002655 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002656 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002657
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002658 String codePath = null;
2659 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002660 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2661 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002662 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002663 } else {
2664 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002665 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002666 }
2667 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002668 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002669 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002670 codePath = pkg.mScanPath;
2671 // Set application objects path explicitly.
2672 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002674 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 }
2676
Kenny Root85387d72010-08-26 10:13:11 -07002677 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2678 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002679 pkg.mPath = pkg.mScanPath = destCodePath;
2680 pkg.applicationInfo.sourceDir = destCodePath;
2681 pkg.applicationInfo.publicSourceDir = destResPath;
2682 }
2683
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002684 private static String fixProcessName(String defProcessName,
2685 String processName, int uid) {
2686 if (processName == null) {
2687 return defProcessName;
2688 }
2689 return processName;
2690 }
2691
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002692 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002693 PackageParser.Package pkg) {
2694 if (pkgSetting.signatures.mSignatures != null) {
2695 // Already existing package. Make sure signatures match
2696 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2697 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002698 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002699 + " signatures do not match the previously installed version; ignoring!");
2700 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002701 return false;
2702 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002703 }
2704 // Check for shared user signatures
2705 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2706 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2707 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2708 Slog.e(TAG, "Package " + pkg.packageName
2709 + " has no signatures that match those in shared user "
2710 + pkgSetting.sharedUser.name + "; ignoring!");
2711 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2712 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002714 }
2715 return true;
2716 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002717
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002718 public boolean performDexOpt(String packageName) {
2719 if (!mNoDexOpt) {
2720 return false;
2721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002722
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002723 PackageParser.Package p;
2724 synchronized (mPackages) {
2725 p = mPackages.get(packageName);
2726 if (p == null || p.mDidDexOpt) {
2727 return false;
2728 }
2729 }
2730 synchronized (mInstallLock) {
2731 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2732 }
2733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002734
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002735 static final int DEX_OPT_SKIPPED = 0;
2736 static final int DEX_OPT_PERFORMED = 1;
2737 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002738
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002739 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2740 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002741 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002742 String path = pkg.mScanPath;
2743 int ret = 0;
2744 try {
2745 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002746 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002747 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002748 pkg.mDidDexOpt = true;
2749 performed = true;
2750 }
2751 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002752 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002753 ret = -1;
2754 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002755 Slog.w(TAG, "IOException reading apk: " + path, e);
2756 ret = -1;
2757 } catch (dalvik.system.StaleDexCacheError e) {
2758 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2759 ret = -1;
2760 } catch (Exception e) {
2761 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002762 ret = -1;
2763 }
2764 if (ret < 0) {
2765 //error from installer
2766 return DEX_OPT_FAILED;
2767 }
2768 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002769
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002770 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2771 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002772
2773 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2774 return Environment.isEncryptedFilesystemEnabled() &&
2775 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2776 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002777
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002778 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2779 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002780 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002781 + " to " + newPkg.packageName
2782 + ": old package not in system partition");
2783 return false;
2784 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002785 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002786 + " to " + newPkg.packageName
2787 + ": old package still exists");
2788 return false;
2789 }
2790 return true;
2791 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002792
2793 private File getDataPathForPackage(PackageParser.Package pkg) {
2794 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2795 File dataPath;
2796 if (useEncryptedFSDir) {
2797 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2798 } else {
2799 dataPath = new File(mAppDataDir, pkg.packageName);
2800 }
2801 return dataPath;
2802 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002803
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002804 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002805 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002806 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002807 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2808 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002809 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002810 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002811 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2812 return null;
2813 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 mScanningPath = scanFile;
2815 if (pkg == null) {
2816 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2817 return null;
2818 }
2819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2821 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2822 }
2823
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002824 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 synchronized (mPackages) {
2826 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002827 Slog.w(TAG, "*************************************************");
2828 Slog.w(TAG, "Core android package being redefined. Skipping.");
2829 Slog.w(TAG, " file=" + mScanningPath);
2830 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002831 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2832 return null;
2833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 // Set up information for our fall-back user intent resolution
2836 // activity.
2837 mPlatformPackage = pkg;
2838 pkg.mVersionCode = mSdkVersion;
2839 mAndroidApplication = pkg.applicationInfo;
2840 mResolveActivity.applicationInfo = mAndroidApplication;
2841 mResolveActivity.name = ResolverActivity.class.getName();
2842 mResolveActivity.packageName = mAndroidApplication.packageName;
2843 mResolveActivity.processName = mAndroidApplication.processName;
2844 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2845 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2846 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2847 mResolveActivity.exported = true;
2848 mResolveActivity.enabled = true;
2849 mResolveInfo.activityInfo = mResolveActivity;
2850 mResolveInfo.priority = 0;
2851 mResolveInfo.preferredOrder = 0;
2852 mResolveInfo.match = 0;
2853 mResolveComponentName = new ComponentName(
2854 mAndroidApplication.packageName, mResolveActivity.name);
2855 }
2856 }
2857
2858 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002859 TAG, "Scanning package " + pkg.packageName);
2860 if (mPackages.containsKey(pkg.packageName)
2861 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002862 Slog.w(TAG, "*************************************************");
2863 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002865 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2867 return null;
2868 }
2869
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002870 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002871 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2872 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002873
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 SharedUserSetting suid = null;
2875 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002876
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002877 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2878 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002879 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002880 pkg.mRealPackage = null;
2881 pkg.mAdoptPermissions = null;
2882 }
2883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 synchronized (mPackages) {
2885 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002886 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2887 if (mTmpSharedLibraries == null ||
2888 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2889 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2890 }
2891 int num = 0;
2892 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2893 for (int i=0; i<N; i++) {
2894 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002896 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002898 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2900 return null;
2901 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002902 mTmpSharedLibraries[num] = file;
2903 num++;
2904 }
2905 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2906 for (int i=0; i<N; i++) {
2907 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2908 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002909 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002910 + " desires unavailable shared library "
2911 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2912 } else {
2913 mTmpSharedLibraries[num] = file;
2914 num++;
2915 }
2916 }
2917 if (num > 0) {
2918 pkg.usesLibraryFiles = new String[num];
2919 System.arraycopy(mTmpSharedLibraries, 0,
2920 pkg.usesLibraryFiles, 0, num);
2921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002922
Dianne Hackborn49237342009-08-27 20:08:01 -07002923 if (pkg.reqFeatures != null) {
2924 N = pkg.reqFeatures.size();
2925 for (int i=0; i<N; i++) {
2926 FeatureInfo fi = pkg.reqFeatures.get(i);
2927 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2928 // Don't care.
2929 continue;
2930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002931
Dianne Hackborn49237342009-08-27 20:08:01 -07002932 if (fi.name != null) {
2933 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002934 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002935 + " requires unavailable feature "
2936 + fi.name + "; failing!");
2937 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2938 return null;
2939 }
2940 }
2941 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002942 }
2943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 if (pkg.mSharedUserId != null) {
2946 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2947 pkg.applicationInfo.flags, true);
2948 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002949 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 + " for shared user failed");
2951 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2952 return null;
2953 }
2954 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2955 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2956 + suid.userId + "): packages=" + suid.packages);
2957 }
2958 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002959
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002961 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002962 Log.w(TAG, "WAITING FOR DEBUGGER");
2963 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002964 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2965 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002966 }
2967 }
2968
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002969 // Check if we are renaming from an original package name.
2970 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002971 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002972 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973 // This package may need to be renamed to a previously
2974 // installed name. Let's check on that...
2975 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002976 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002977 // This package had originally been installed as the
2978 // original name, and we have already taken care of
2979 // transitioning to the new one. Just update the new
2980 // one to continue using the old name.
2981 realName = pkg.mRealPackage;
2982 if (!pkg.packageName.equals(renamed)) {
2983 // Callers into this function may have already taken
2984 // care of renaming the package; only do it here if
2985 // it is not already done.
2986 pkg.setPackageName(renamed);
2987 }
2988
Dianne Hackbornc1552392010-03-03 16:19:01 -08002989 } else {
2990 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2991 if ((origPackage=mSettings.peekPackageLP(
2992 pkg.mOriginalPackages.get(i))) != null) {
2993 // We do have the package already installed under its
2994 // original name... should we use it?
2995 if (!verifyPackageUpdate(origPackage, pkg)) {
2996 // New package is not compatible with original.
2997 origPackage = null;
2998 continue;
2999 } else if (origPackage.sharedUser != null) {
3000 // Make sure uid is compatible between packages.
3001 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003002 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003003 + " to " + pkg.packageName + ": old uid "
3004 + origPackage.sharedUser.name
3005 + " differs from " + pkg.mSharedUserId);
3006 origPackage = null;
3007 continue;
3008 }
3009 } else {
3010 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3011 + pkg.packageName + " to old name " + origPackage.name);
3012 }
3013 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003014 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003015 }
3016 }
3017 }
3018
3019 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003020 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003021 + " was transferred to another, but its .apk remains");
3022 }
3023
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003024 // Just create the setting, don't add it yet. For already existing packages
3025 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003026 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003027 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3028 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003030 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3032 return null;
3033 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003034
3035 if (pkgSetting.origPackage != null) {
3036 // If we are first transitioning from an original package,
3037 // fix up the new package's name now. We need to do this after
3038 // looking up the package under its new name, so getPackageLP
3039 // can take care of fiddling things correctly.
3040 pkg.setPackageName(origPackage.name);
3041
3042 // File a report about this.
3043 String msg = "New package " + pkgSetting.realName
3044 + " renamed to replace old package " + pkgSetting.name;
3045 reportSettingsProblem(Log.WARN, msg);
3046
3047 // Make a note of it.
3048 mTransferedPackages.add(origPackage.name);
3049
3050 // No longer need to retain this.
3051 pkgSetting.origPackage = null;
3052 }
3053
3054 if (realName != null) {
3055 // Make a note of it.
3056 mTransferedPackages.add(pkg.packageName);
3057 }
3058
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003059 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3061 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063 pkg.applicationInfo.uid = pkgSetting.userId;
3064 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003065
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003066 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003067 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 return null;
3069 }
3070 // The signature has changed, but this package is in the system
3071 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003072 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 // However... if this package is part of a shared user, but it
3074 // doesn't match the signature of the shared user, let's fail.
3075 // What this means is that you can't change the signatures
3076 // associated with an overall shared user, which doesn't seem all
3077 // that unreasonable.
3078 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003079 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3080 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3081 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003082 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3083 return null;
3084 }
3085 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003086 // File a report about this.
3087 String msg = "System package " + pkg.packageName
3088 + " signature changed; retaining data.";
3089 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003091
The Android Open Source Project10592532009-03-18 17:39:46 -07003092 // Verify that this new package doesn't have any content providers
3093 // that conflict with existing packages. Only do this if the
3094 // package isn't already installed, since we don't want to break
3095 // things that are installed.
3096 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3097 int N = pkg.providers.size();
3098 int i;
3099 for (i=0; i<N; i++) {
3100 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003101 if (p.info.authority != null) {
3102 String names[] = p.info.authority.split(";");
3103 for (int j = 0; j < names.length; j++) {
3104 if (mProviders.containsKey(names[j])) {
3105 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003106 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003107 " (in package " + pkg.applicationInfo.packageName +
3108 ") is already used by "
3109 + ((other != null && other.getComponentName() != null)
3110 ? other.getComponentName().getPackageName() : "?"));
3111 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3112 return null;
3113 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003114 }
3115 }
3116 }
3117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 }
3119
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003120 final String pkgName = pkg.packageName;
3121
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003122 if (pkg.mAdoptPermissions != null) {
3123 // This package wants to adopt ownership of permissions from
3124 // another package.
3125 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3126 String origName = pkg.mAdoptPermissions.get(i);
3127 PackageSetting orig = mSettings.peekPackageLP(origName);
3128 if (orig != null) {
3129 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003130 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003131 + origName + " to " + pkg.packageName);
3132 mSettings.transferPermissions(origName, pkg.packageName);
3133 }
3134 }
3135 }
3136 }
3137
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003138 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003140 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 pkg.applicationInfo.processName = fixProcessName(
3142 pkg.applicationInfo.packageName,
3143 pkg.applicationInfo.processName,
3144 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145
3146 File dataPath;
3147 if (mPlatformPackage == pkg) {
3148 // The system package is special.
3149 dataPath = new File (Environment.getDataDirectory(), "system");
3150 pkg.applicationInfo.dataDir = dataPath.getPath();
3151 } else {
3152 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003153 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003154 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003155
3156 boolean uidError = false;
3157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 if (dataPath.exists()) {
3159 mOutPermissions[1] = 0;
3160 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003161
3162 // If we have mismatched owners for the data path, we have a
3163 // problem (unless we're running in the simulator.)
3164 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 boolean recovered = false;
3166 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3167 // If this is a system app, we can at least delete its
3168 // current data so the application will still work.
3169 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003170 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003171 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 // Old data gone!
3173 String msg = "System package " + pkg.packageName
3174 + " has changed from uid: "
3175 + mOutPermissions[1] + " to "
3176 + pkg.applicationInfo.uid + "; old data erased";
3177 reportSettingsProblem(Log.WARN, msg);
3178 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003181 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 pkg.applicationInfo.uid);
3183 if (ret == -1) {
3184 // Ack should not happen!
3185 msg = "System package " + pkg.packageName
3186 + " could not have data directory re-created after delete.";
3187 reportSettingsProblem(Log.WARN, msg);
3188 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3189 return null;
3190 }
3191 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 if (!recovered) {
3194 mHasSystemUidErrors = true;
3195 }
3196 }
3197 if (!recovered) {
3198 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3199 + pkg.applicationInfo.uid + "/fs_"
3200 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003201 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 String msg = "Package " + pkg.packageName
3203 + " has mismatched uid: "
3204 + mOutPermissions[1] + " on disk, "
3205 + pkg.applicationInfo.uid + " in settings";
3206 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003207 mSettings.mReadMessages.append(msg);
3208 mSettings.mReadMessages.append('\n');
3209 uidError = true;
3210 if (!pkgSetting.uidError) {
3211 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 }
3214 }
3215 }
3216 pkg.applicationInfo.dataDir = dataPath.getPath();
3217 } else {
3218 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3219 Log.v(TAG, "Want this data dir: " + dataPath);
3220 //invoke installer to do the actual installation
3221 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003222 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 pkg.applicationInfo.uid);
3224 if(ret < 0) {
3225 // Error from installer
3226 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3227 return null;
3228 }
3229 } else {
3230 dataPath.mkdirs();
3231 if (dataPath.exists()) {
3232 FileUtils.setPermissions(
3233 dataPath.toString(),
3234 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3235 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3236 }
3237 }
3238 if (dataPath.exists()) {
3239 pkg.applicationInfo.dataDir = dataPath.getPath();
3240 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003241 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 pkg.applicationInfo.dataDir = null;
3243 }
3244 }
Kenny Root85387d72010-08-26 10:13:11 -07003245
3246 /*
3247 * Set the data dir to the default "/data/data/<package name>/lib"
3248 * if we got here without anyone telling us different (e.g., apps
3249 * stored on SD card have their native libraries stored in the ASEC
3250 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003251 *
3252 * This happens during an upgrade from a package settings file that
3253 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003254 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003255 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3256 if (pkgSetting.nativeLibraryPathString == null) {
3257 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3258 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3259 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3260 } else {
3261 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3262 }
Kenny Root85387d72010-08-26 10:13:11 -07003263 }
3264
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003265 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 }
3267
Kenny Root85387d72010-08-26 10:13:11 -07003268 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 if (mInstaller != null) {
3270 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003271 /* Note: We don't want to unpack the native binaries for
3272 * system applications, unless they have been updated
3273 * (the binaries are already under /system/lib).
3274 * Also, don't unpack libs for apps on the external card
3275 * since they should have their libraries in the ASEC
3276 * container already.
3277 *
3278 * In other words, we're going to unpack the binaries
3279 * only for non-system apps and system app upgrades.
3280 */
Kenny Root831baa22010-10-05 12:29:25 -07003281 if (pkg.applicationInfo.nativeLibraryDir != null) {
3282 final File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3283 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3284 /*
3285 * Upgrading from a previous version of the OS sometimes
3286 * leaves native libraries in the /data/data/<app>/lib
3287 * directory for system apps even when they shouldn't be.
3288 * Recent changes in the JNI library search path
3289 * necessitates we remove those to match previous behavior.
3290 */
3291 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(sharedLibraryDir)) {
3292 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3293 }
3294 } else if (!isExternal(pkg)) {
3295 Log.i(TAG, path + " changed; unpacking");
Kenny Root6a6b0072010-10-07 16:46:10 -07003296 mInstaller.unlinkNativeLibraryDirectory(dataPath.getPath());
Kenny Root831baa22010-10-05 12:29:25 -07003297 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003298 } else {
3299 mInstaller.linkNativeLibraryDirectory(dataPath.getPath(),
3300 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003303 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003304
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003305 if ((scanMode&SCAN_NO_DEX) == 0) {
3306 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3308 return null;
3309 }
3310 }
3311 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003312
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003313 if (mFactoryTest && pkg.requestedPermissions.contains(
3314 android.Manifest.permission.FACTORY_TEST)) {
3315 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3316 }
3317
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003318 // Request the ActivityManager to kill the process(only for existing packages)
3319 // so that we do not end up in a confused state while the user is still using the older
3320 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003321 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003322 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003323 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003324 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003327 // We don't expect installation to fail beyond this point,
3328 if ((scanMode&SCAN_MONITOR) != 0) {
3329 mAppDirs.put(pkg.mPath, pkg);
3330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003332 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003334 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003335 // Make sure we don't accidentally delete its data.
3336 mSettings.mPackagesToBeCleaned.remove(pkgName);
3337
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003338 // Take care of first install / last update times.
3339 if (currentTime != 0) {
3340 if (pkgSetting.firstInstallTime == 0) {
3341 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3342 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3343 pkgSetting.lastUpdateTime = currentTime;
3344 }
3345 } else if (pkgSetting.firstInstallTime == 0) {
3346 // We need *something*. Take time time stamp of the file.
3347 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3348 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3349 if (scanFileTime != pkgSetting.timeStamp) {
3350 // A package on the system image has changed; consider this
3351 // to be an update.
3352 pkgSetting.lastUpdateTime = scanFileTime;
3353 }
3354 }
3355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 int N = pkg.providers.size();
3357 StringBuilder r = null;
3358 int i;
3359 for (i=0; i<N; i++) {
3360 PackageParser.Provider p = pkg.providers.get(i);
3361 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3362 p.info.processName, pkg.applicationInfo.uid);
3363 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3364 p.info.name), p);
3365 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003366 if (p.info.authority != null) {
3367 String names[] = p.info.authority.split(";");
3368 p.info.authority = null;
3369 for (int j = 0; j < names.length; j++) {
3370 if (j == 1 && p.syncable) {
3371 // We only want the first authority for a provider to possibly be
3372 // syncable, so if we already added this provider using a different
3373 // authority clear the syncable flag. We copy the provider before
3374 // changing it because the mProviders object contains a reference
3375 // to a provider that we don't want to change.
3376 // Only do this for the second authority since the resulting provider
3377 // object can be the same for all future authorities for this provider.
3378 p = new PackageParser.Provider(p);
3379 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003381 if (!mProviders.containsKey(names[j])) {
3382 mProviders.put(names[j], p);
3383 if (p.info.authority == null) {
3384 p.info.authority = names[j];
3385 } else {
3386 p.info.authority = p.info.authority + ";" + names[j];
3387 }
3388 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3389 Log.d(TAG, "Registered content provider: " + names[j] +
3390 ", className = " + p.info.name +
3391 ", isSyncable = " + p.info.isSyncable);
3392 } else {
3393 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003394 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003395 " (in package " + pkg.applicationInfo.packageName +
3396 "): name already used by "
3397 + ((other != null && other.getComponentName() != null)
3398 ? other.getComponentName().getPackageName() : "?"));
3399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 }
3401 }
3402 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3403 if (r == null) {
3404 r = new StringBuilder(256);
3405 } else {
3406 r.append(' ');
3407 }
3408 r.append(p.info.name);
3409 }
3410 }
3411 if (r != null) {
3412 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3413 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003415 N = pkg.services.size();
3416 r = null;
3417 for (i=0; i<N; i++) {
3418 PackageParser.Service s = pkg.services.get(i);
3419 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3420 s.info.processName, pkg.applicationInfo.uid);
3421 mServices.addService(s);
3422 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3423 if (r == null) {
3424 r = new StringBuilder(256);
3425 } else {
3426 r.append(' ');
3427 }
3428 r.append(s.info.name);
3429 }
3430 }
3431 if (r != null) {
3432 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3433 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 N = pkg.receivers.size();
3436 r = null;
3437 for (i=0; i<N; i++) {
3438 PackageParser.Activity a = pkg.receivers.get(i);
3439 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3440 a.info.processName, pkg.applicationInfo.uid);
3441 mReceivers.addActivity(a, "receiver");
3442 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3443 if (r == null) {
3444 r = new StringBuilder(256);
3445 } else {
3446 r.append(' ');
3447 }
3448 r.append(a.info.name);
3449 }
3450 }
3451 if (r != null) {
3452 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 N = pkg.activities.size();
3456 r = null;
3457 for (i=0; i<N; i++) {
3458 PackageParser.Activity a = pkg.activities.get(i);
3459 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3460 a.info.processName, pkg.applicationInfo.uid);
3461 mActivities.addActivity(a, "activity");
3462 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3463 if (r == null) {
3464 r = new StringBuilder(256);
3465 } else {
3466 r.append(' ');
3467 }
3468 r.append(a.info.name);
3469 }
3470 }
3471 if (r != null) {
3472 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3473 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 N = pkg.permissionGroups.size();
3476 r = null;
3477 for (i=0; i<N; i++) {
3478 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3479 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3480 if (cur == null) {
3481 mPermissionGroups.put(pg.info.name, pg);
3482 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3483 if (r == null) {
3484 r = new StringBuilder(256);
3485 } else {
3486 r.append(' ');
3487 }
3488 r.append(pg.info.name);
3489 }
3490 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003491 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003492 + pg.info.packageName + " ignored: original from "
3493 + cur.info.packageName);
3494 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3495 if (r == null) {
3496 r = new StringBuilder(256);
3497 } else {
3498 r.append(' ');
3499 }
3500 r.append("DUP:");
3501 r.append(pg.info.name);
3502 }
3503 }
3504 }
3505 if (r != null) {
3506 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3507 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003509 N = pkg.permissions.size();
3510 r = null;
3511 for (i=0; i<N; i++) {
3512 PackageParser.Permission p = pkg.permissions.get(i);
3513 HashMap<String, BasePermission> permissionMap =
3514 p.tree ? mSettings.mPermissionTrees
3515 : mSettings.mPermissions;
3516 p.group = mPermissionGroups.get(p.info.group);
3517 if (p.info.group == null || p.group != null) {
3518 BasePermission bp = permissionMap.get(p.info.name);
3519 if (bp == null) {
3520 bp = new BasePermission(p.info.name, p.info.packageName,
3521 BasePermission.TYPE_NORMAL);
3522 permissionMap.put(p.info.name, bp);
3523 }
3524 if (bp.perm == null) {
3525 if (bp.sourcePackage == null
3526 || bp.sourcePackage.equals(p.info.packageName)) {
3527 BasePermission tree = findPermissionTreeLP(p.info.name);
3528 if (tree == null
3529 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003530 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 bp.perm = p;
3532 bp.uid = pkg.applicationInfo.uid;
3533 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3534 if (r == null) {
3535 r = new StringBuilder(256);
3536 } else {
3537 r.append(' ');
3538 }
3539 r.append(p.info.name);
3540 }
3541 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003542 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 + p.info.packageName + " ignored: base tree "
3544 + tree.name + " is from package "
3545 + tree.sourcePackage);
3546 }
3547 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003548 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 + p.info.packageName + " ignored: original from "
3550 + bp.sourcePackage);
3551 }
3552 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3553 if (r == null) {
3554 r = new StringBuilder(256);
3555 } else {
3556 r.append(' ');
3557 }
3558 r.append("DUP:");
3559 r.append(p.info.name);
3560 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003561 if (bp.perm == p) {
3562 bp.protectionLevel = p.info.protectionLevel;
3563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003564 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003565 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 + p.info.packageName + " ignored: no group "
3567 + p.group);
3568 }
3569 }
3570 if (r != null) {
3571 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3572 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003573
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 N = pkg.instrumentation.size();
3575 r = null;
3576 for (i=0; i<N; i++) {
3577 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3578 a.info.packageName = pkg.applicationInfo.packageName;
3579 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3580 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3581 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003582 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003583 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3585 if (r == null) {
3586 r = new StringBuilder(256);
3587 } else {
3588 r.append(' ');
3589 }
3590 r.append(a.info.name);
3591 }
3592 }
3593 if (r != null) {
3594 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3595 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003596
Dianne Hackborn854060af2009-07-09 18:14:31 -07003597 if (pkg.protectedBroadcasts != null) {
3598 N = pkg.protectedBroadcasts.size();
3599 for (i=0; i<N; i++) {
3600 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3601 }
3602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003604 pkgSetting.setTimeStamp(scanFileTime);
3605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003607 return pkg;
3608 }
3609
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003610 private void killApplication(String pkgName, int uid) {
3611 // Request the ActivityManager to kill the process(only for existing packages)
3612 // so that we do not end up in a confused state while the user is still using the older
3613 // version of the application while the new one gets installed.
3614 IActivityManager am = ActivityManagerNative.getDefault();
3615 if (am != null) {
3616 try {
3617 am.killApplicationWithUid(pkgName, uid);
3618 } catch (RemoteException e) {
3619 }
3620 }
3621 }
3622
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003623 // Return the path of the directory that will contain the native binaries
3624 // of a given installed package. This is relative to the data path.
3625 //
Kenny Root85387d72010-08-26 10:13:11 -07003626 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3627 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3628 if (nativeLibraryDir != null) {
3629 return new File(nativeLibraryDir);
3630 } else {
3631 // Fall back for old packages
3632 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3633 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003634 }
3635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3637 if (chatty && Config.LOGD) Log.d(
3638 TAG, "Removing package " + pkg.applicationInfo.packageName );
3639
3640 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003642
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 mPackages.remove(pkg.applicationInfo.packageName);
3644 if (pkg.mPath != null) {
3645 mAppDirs.remove(pkg.mPath);
3646 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003648 PackageSetting ps = (PackageSetting)pkg.mExtras;
3649 if (ps != null && ps.sharedUser != null) {
3650 // XXX don't do this until the data is removed.
3651 if (false) {
3652 ps.sharedUser.packages.remove(ps);
3653 if (ps.sharedUser.packages.size() == 0) {
3654 // Remove.
3655 }
3656 }
3657 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 int N = pkg.providers.size();
3660 StringBuilder r = null;
3661 int i;
3662 for (i=0; i<N; i++) {
3663 PackageParser.Provider p = pkg.providers.get(i);
3664 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3665 p.info.name));
3666 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 /* The is another ContentProvider with this authority when
3669 * this app was installed so this authority is null,
3670 * Ignore it as we don't have to unregister the provider.
3671 */
3672 continue;
3673 }
3674 String names[] = p.info.authority.split(";");
3675 for (int j = 0; j < names.length; j++) {
3676 if (mProviders.get(names[j]) == p) {
3677 mProviders.remove(names[j]);
3678 if (chatty && Config.LOGD) Log.d(
3679 TAG, "Unregistered content provider: " + names[j] +
3680 ", className = " + p.info.name +
3681 ", isSyncable = " + p.info.isSyncable);
3682 }
3683 }
3684 if (chatty) {
3685 if (r == null) {
3686 r = new StringBuilder(256);
3687 } else {
3688 r.append(' ');
3689 }
3690 r.append(p.info.name);
3691 }
3692 }
3693 if (r != null) {
3694 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3695 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 N = pkg.services.size();
3698 r = null;
3699 for (i=0; i<N; i++) {
3700 PackageParser.Service s = pkg.services.get(i);
3701 mServices.removeService(s);
3702 if (chatty) {
3703 if (r == null) {
3704 r = new StringBuilder(256);
3705 } else {
3706 r.append(' ');
3707 }
3708 r.append(s.info.name);
3709 }
3710 }
3711 if (r != null) {
3712 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 N = pkg.receivers.size();
3716 r = null;
3717 for (i=0; i<N; i++) {
3718 PackageParser.Activity a = pkg.receivers.get(i);
3719 mReceivers.removeActivity(a, "receiver");
3720 if (chatty) {
3721 if (r == null) {
3722 r = new StringBuilder(256);
3723 } else {
3724 r.append(' ');
3725 }
3726 r.append(a.info.name);
3727 }
3728 }
3729 if (r != null) {
3730 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 N = pkg.activities.size();
3734 r = null;
3735 for (i=0; i<N; i++) {
3736 PackageParser.Activity a = pkg.activities.get(i);
3737 mActivities.removeActivity(a, "activity");
3738 if (chatty) {
3739 if (r == null) {
3740 r = new StringBuilder(256);
3741 } else {
3742 r.append(' ');
3743 }
3744 r.append(a.info.name);
3745 }
3746 }
3747 if (r != null) {
3748 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3749 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003750
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 N = pkg.permissions.size();
3752 r = null;
3753 for (i=0; i<N; i++) {
3754 PackageParser.Permission p = pkg.permissions.get(i);
3755 boolean tree = false;
3756 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3757 if (bp == null) {
3758 tree = true;
3759 bp = mSettings.mPermissionTrees.get(p.info.name);
3760 }
3761 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003762 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 if (chatty) {
3764 if (r == null) {
3765 r = new StringBuilder(256);
3766 } else {
3767 r.append(' ');
3768 }
3769 r.append(p.info.name);
3770 }
3771 }
3772 }
3773 if (r != null) {
3774 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3775 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003777 N = pkg.instrumentation.size();
3778 r = null;
3779 for (i=0; i<N; i++) {
3780 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003781 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 if (chatty) {
3783 if (r == null) {
3784 r = new StringBuilder(256);
3785 } else {
3786 r.append(' ');
3787 }
3788 r.append(a.info.name);
3789 }
3790 }
3791 if (r != null) {
3792 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3793 }
3794 }
3795 }
3796
3797 private static final boolean isPackageFilename(String name) {
3798 return name != null && name.endsWith(".apk");
3799 }
3800
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003801 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3802 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3803 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3804 return true;
3805 }
3806 }
3807 return false;
3808 }
3809
3810 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003811 PackageParser.Package pkgInfo, boolean grantPermissions,
3812 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 // Make sure there are no dangling permission trees.
3814 Iterator<BasePermission> it = mSettings.mPermissionTrees
3815 .values().iterator();
3816 while (it.hasNext()) {
3817 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003818 if (bp.packageSetting == null) {
3819 // We may not yet have parsed the package, so just see if
3820 // we still know about its settings.
3821 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3822 }
3823 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003824 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003825 + " from package " + bp.sourcePackage);
3826 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003827 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3828 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3829 Slog.i(TAG, "Removing old permission tree: " + bp.name
3830 + " from package " + bp.sourcePackage);
3831 grantPermissions = true;
3832 it.remove();
3833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
3835 }
3836
3837 // Make sure all dynamic permissions have been assigned to a package,
3838 // and make sure there are no dangling permissions.
3839 it = mSettings.mPermissions.values().iterator();
3840 while (it.hasNext()) {
3841 BasePermission bp = it.next();
3842 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3843 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3844 + bp.name + " pkg=" + bp.sourcePackage
3845 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003846 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 BasePermission tree = findPermissionTreeLP(bp.name);
3848 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003849 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 bp.perm = new PackageParser.Permission(tree.perm.owner,
3851 new PermissionInfo(bp.pendingInfo));
3852 bp.perm.info.packageName = tree.perm.info.packageName;
3853 bp.perm.info.name = bp.name;
3854 bp.uid = tree.uid;
3855 }
3856 }
3857 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003858 if (bp.packageSetting == null) {
3859 // We may not yet have parsed the package, so just see if
3860 // we still know about its settings.
3861 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3862 }
3863 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003864 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 + " from package " + bp.sourcePackage);
3866 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003867 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3868 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3869 Slog.i(TAG, "Removing old permission: " + bp.name
3870 + " from package " + bp.sourcePackage);
3871 grantPermissions = true;
3872 it.remove();
3873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003874 }
3875 }
3876
3877 // Now update the permissions for all packages, in particular
3878 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003879 if (grantPermissions) {
3880 for (PackageParser.Package pkg : mPackages.values()) {
3881 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003882 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003883 }
3884 }
3885 }
3886
3887 if (pkgInfo != null) {
3888 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 }
3890 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3893 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3894 if (ps == null) {
3895 return;
3896 }
3897 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003898 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 if (replace) {
3901 ps.permissionsFixed = false;
3902 if (gp == ps) {
3903 gp.grantedPermissions.clear();
3904 gp.gids = mGlobalGids;
3905 }
3906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 if (gp.gids == null) {
3909 gp.gids = mGlobalGids;
3910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 final int N = pkg.requestedPermissions.size();
3913 for (int i=0; i<N; i++) {
3914 String name = pkg.requestedPermissions.get(i);
3915 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 if (false) {
3917 if (gp != ps) {
3918 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003919 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 }
3921 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003922 if (bp != null && bp.packageSetting != null) {
3923 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003925 boolean allowedSig = false;
3926 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3927 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003929 } else if (bp.packageSetting == null) {
3930 // This permission is invalid; skip it.
3931 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003932 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3933 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3934 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003936 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003938 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003939 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 // For updated system applications, the signatureOrSystem permission
3941 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003942 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3944 if(sysPs.grantedPermissions.contains(perm)) {
3945 allowed = true;
3946 } else {
3947 allowed = false;
3948 }
3949 } else {
3950 allowed = true;
3951 }
3952 }
3953 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003954 if (allowed) {
3955 allowedSig = true;
3956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 } else {
3958 allowed = false;
3959 }
3960 if (false) {
3961 if (gp != ps) {
3962 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3963 }
3964 }
3965 if (allowed) {
3966 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3967 && ps.permissionsFixed) {
3968 // If this is an existing, non-system package, then
3969 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003970 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003972 // Except... if this is a permission that was added
3973 // to the platform (note: need to only do this when
3974 // updating the platform).
3975 final int NP = PackageParser.NEW_PERMISSIONS.length;
3976 for (int ip=0; ip<NP; ip++) {
3977 final PackageParser.NewPermissionInfo npi
3978 = PackageParser.NEW_PERMISSIONS[ip];
3979 if (npi.name.equals(perm)
3980 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3981 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003982 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003983 + pkg.packageName);
3984 break;
3985 }
3986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 }
3988 }
3989 if (allowed) {
3990 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003991 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003992 gp.grantedPermissions.add(perm);
3993 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003994 } else if (!ps.haveGids) {
3995 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 }
3997 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003998 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 + " to package " + pkg.packageName
4000 + " because it was previously installed without");
4001 }
4002 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004003 if (gp.grantedPermissions.remove(perm)) {
4004 changedPermission = true;
4005 gp.gids = removeInts(gp.gids, bp.gids);
4006 Slog.i(TAG, "Un-granting permission " + perm
4007 + " from package " + pkg.packageName
4008 + " (protectionLevel=" + bp.protectionLevel
4009 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4010 + ")");
4011 } else {
4012 Slog.w(TAG, "Not granting permission " + perm
4013 + " to package " + pkg.packageName
4014 + " (protectionLevel=" + bp.protectionLevel
4015 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4016 + ")");
4017 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004018 }
4019 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004020 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 + " in package " + pkg.packageName);
4022 }
4023 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004024
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004025 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004026 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4027 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 // This is the first that we have heard about this package, so the
4029 // permissions we have now selected are fixed until explicitly
4030 // changed.
4031 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004033 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 private final class ActivityIntentResolver
4037 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004038 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004040 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 }
4042
Mihai Preda074edef2009-05-18 17:13:31 +02004043 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004045 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4047 }
4048
Mihai Predaeae850c2009-05-13 10:13:48 +02004049 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4050 ArrayList<PackageParser.Activity> packageActivities) {
4051 if (packageActivities == null) {
4052 return null;
4053 }
4054 mFlags = flags;
4055 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4056 int N = packageActivities.size();
4057 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4058 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004059
4060 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004061 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004062 intentFilters = packageActivities.get(i).intents;
4063 if (intentFilters != null && intentFilters.size() > 0) {
4064 listCut.add(intentFilters);
4065 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004066 }
4067 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4068 }
4069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004071 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004072 if (SHOW_INFO || Config.LOGV) Log.v(
4073 TAG, " " + type + " " +
4074 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4075 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4076 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004077 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4079 if (SHOW_INFO || Config.LOGV) {
4080 Log.v(TAG, " IntentFilter:");
4081 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4082 }
4083 if (!intent.debugCheck()) {
4084 Log.w(TAG, "==> For Activity " + a.info.name);
4085 }
4086 addFilter(intent);
4087 }
4088 }
4089
4090 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004091 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 if (SHOW_INFO || Config.LOGV) Log.v(
4093 TAG, " " + type + " " +
4094 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4095 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4096 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004097 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004098 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4099 if (SHOW_INFO || Config.LOGV) {
4100 Log.v(TAG, " IntentFilter:");
4101 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4102 }
4103 removeFilter(intent);
4104 }
4105 }
4106
4107 @Override
4108 protected boolean allowFilterResult(
4109 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4110 ActivityInfo filterAi = filter.activity.info;
4111 for (int i=dest.size()-1; i>=0; i--) {
4112 ActivityInfo destAi = dest.get(i).activityInfo;
4113 if (destAi.name == filterAi.name
4114 && destAi.packageName == filterAi.packageName) {
4115 return false;
4116 }
4117 }
4118 return true;
4119 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004121 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004122 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4123 return info.activity.owner.packageName;
4124 }
4125
4126 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4128 int match) {
4129 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4130 return null;
4131 }
4132 final PackageParser.Activity activity = info.activity;
4133 if (mSafeMode && (activity.info.applicationInfo.flags
4134 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4135 return null;
4136 }
4137 final ResolveInfo res = new ResolveInfo();
4138 res.activityInfo = PackageParser.generateActivityInfo(activity,
4139 mFlags);
4140 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4141 res.filter = info;
4142 }
4143 res.priority = info.getPriority();
4144 res.preferredOrder = activity.owner.mPreferredOrder;
4145 //System.out.println("Result: " + res.activityInfo.className +
4146 // " = " + res.priority);
4147 res.match = match;
4148 res.isDefault = info.hasDefault;
4149 res.labelRes = info.labelRes;
4150 res.nonLocalizedLabel = info.nonLocalizedLabel;
4151 res.icon = info.icon;
4152 return res;
4153 }
4154
4155 @Override
4156 protected void sortResults(List<ResolveInfo> results) {
4157 Collections.sort(results, mResolvePrioritySorter);
4158 }
4159
4160 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004161 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004163 out.print(prefix); out.print(
4164 Integer.toHexString(System.identityHashCode(filter.activity)));
4165 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004166 out.print(filter.activity.getComponentShortName());
4167 out.print(" filter ");
4168 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 }
4170
4171// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4172// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4173// final List<ResolveInfo> retList = Lists.newArrayList();
4174// while (i.hasNext()) {
4175// final ResolveInfo resolveInfo = i.next();
4176// if (isEnabledLP(resolveInfo.activityInfo)) {
4177// retList.add(resolveInfo);
4178// }
4179// }
4180// return retList;
4181// }
4182
4183 // Keys are String (activity class name), values are Activity.
4184 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4185 = new HashMap<ComponentName, PackageParser.Activity>();
4186 private int mFlags;
4187 }
4188
4189 private final class ServiceIntentResolver
4190 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004191 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004192 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004193 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 }
4195
Mihai Preda074edef2009-05-18 17:13:31 +02004196 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004197 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004198 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4200 }
4201
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004202 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4203 ArrayList<PackageParser.Service> packageServices) {
4204 if (packageServices == null) {
4205 return null;
4206 }
4207 mFlags = flags;
4208 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4209 int N = packageServices.size();
4210 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4211 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4212
4213 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4214 for (int i = 0; i < N; ++i) {
4215 intentFilters = packageServices.get(i).intents;
4216 if (intentFilters != null && intentFilters.size() > 0) {
4217 listCut.add(intentFilters);
4218 }
4219 }
4220 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4221 }
4222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004224 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 if (SHOW_INFO || Config.LOGV) Log.v(
4226 TAG, " " + (s.info.nonLocalizedLabel != null
4227 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4228 if (SHOW_INFO || Config.LOGV) Log.v(
4229 TAG, " Class=" + s.info.name);
4230 int NI = s.intents.size();
4231 int j;
4232 for (j=0; j<NI; j++) {
4233 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4234 if (SHOW_INFO || Config.LOGV) {
4235 Log.v(TAG, " IntentFilter:");
4236 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4237 }
4238 if (!intent.debugCheck()) {
4239 Log.w(TAG, "==> For Service " + s.info.name);
4240 }
4241 addFilter(intent);
4242 }
4243 }
4244
4245 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004246 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004247 if (SHOW_INFO || Config.LOGV) Log.v(
4248 TAG, " " + (s.info.nonLocalizedLabel != null
4249 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4250 if (SHOW_INFO || Config.LOGV) Log.v(
4251 TAG, " Class=" + s.info.name);
4252 int NI = s.intents.size();
4253 int j;
4254 for (j=0; j<NI; j++) {
4255 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4256 if (SHOW_INFO || Config.LOGV) {
4257 Log.v(TAG, " IntentFilter:");
4258 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4259 }
4260 removeFilter(intent);
4261 }
4262 }
4263
4264 @Override
4265 protected boolean allowFilterResult(
4266 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4267 ServiceInfo filterSi = filter.service.info;
4268 for (int i=dest.size()-1; i>=0; i--) {
4269 ServiceInfo destAi = dest.get(i).serviceInfo;
4270 if (destAi.name == filterSi.name
4271 && destAi.packageName == filterSi.packageName) {
4272 return false;
4273 }
4274 }
4275 return true;
4276 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004279 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4280 return info.service.owner.packageName;
4281 }
4282
4283 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004284 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4285 int match) {
4286 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4287 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4288 return null;
4289 }
4290 final PackageParser.Service service = info.service;
4291 if (mSafeMode && (service.info.applicationInfo.flags
4292 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4293 return null;
4294 }
4295 final ResolveInfo res = new ResolveInfo();
4296 res.serviceInfo = PackageParser.generateServiceInfo(service,
4297 mFlags);
4298 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4299 res.filter = filter;
4300 }
4301 res.priority = info.getPriority();
4302 res.preferredOrder = service.owner.mPreferredOrder;
4303 //System.out.println("Result: " + res.activityInfo.className +
4304 // " = " + res.priority);
4305 res.match = match;
4306 res.isDefault = info.hasDefault;
4307 res.labelRes = info.labelRes;
4308 res.nonLocalizedLabel = info.nonLocalizedLabel;
4309 res.icon = info.icon;
4310 return res;
4311 }
4312
4313 @Override
4314 protected void sortResults(List<ResolveInfo> results) {
4315 Collections.sort(results, mResolvePrioritySorter);
4316 }
4317
4318 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004319 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004320 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004321 out.print(prefix); out.print(
4322 Integer.toHexString(System.identityHashCode(filter.service)));
4323 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004324 out.print(filter.service.getComponentShortName());
4325 out.print(" filter ");
4326 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 }
4328
4329// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4330// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4331// final List<ResolveInfo> retList = Lists.newArrayList();
4332// while (i.hasNext()) {
4333// final ResolveInfo resolveInfo = (ResolveInfo) i;
4334// if (isEnabledLP(resolveInfo.serviceInfo)) {
4335// retList.add(resolveInfo);
4336// }
4337// }
4338// return retList;
4339// }
4340
4341 // Keys are String (activity class name), values are Activity.
4342 private final HashMap<ComponentName, PackageParser.Service> mServices
4343 = new HashMap<ComponentName, PackageParser.Service>();
4344 private int mFlags;
4345 };
4346
4347 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4348 new Comparator<ResolveInfo>() {
4349 public int compare(ResolveInfo r1, ResolveInfo r2) {
4350 int v1 = r1.priority;
4351 int v2 = r2.priority;
4352 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4353 if (v1 != v2) {
4354 return (v1 > v2) ? -1 : 1;
4355 }
4356 v1 = r1.preferredOrder;
4357 v2 = r2.preferredOrder;
4358 if (v1 != v2) {
4359 return (v1 > v2) ? -1 : 1;
4360 }
4361 if (r1.isDefault != r2.isDefault) {
4362 return r1.isDefault ? -1 : 1;
4363 }
4364 v1 = r1.match;
4365 v2 = r2.match;
4366 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4367 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4368 }
4369 };
4370
4371 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4372 new Comparator<ProviderInfo>() {
4373 public int compare(ProviderInfo p1, ProviderInfo p2) {
4374 final int v1 = p1.initOrder;
4375 final int v2 = p2.initOrder;
4376 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4377 }
4378 };
4379
Kenny Root93565c4b2010-06-18 15:46:06 -07004380 private static final boolean DEBUG_OBB = false;
4381
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004382 private static final void sendPackageBroadcast(String action, String pkg,
4383 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004384 IActivityManager am = ActivityManagerNative.getDefault();
4385 if (am != null) {
4386 try {
4387 final Intent intent = new Intent(action,
4388 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4389 if (extras != null) {
4390 intent.putExtras(extras);
4391 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004392 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004393 am.broadcastIntent(null, intent, null, finishedReceiver,
4394 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004395 } catch (RemoteException ex) {
4396 }
4397 }
4398 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004399
4400 public String nextPackageToClean(String lastPackage) {
4401 synchronized (mPackages) {
4402 if (!mMediaMounted) {
4403 // If the external storage is no longer mounted at this point,
4404 // the caller may not have been able to delete all of this
4405 // packages files and can not delete any more. Bail.
4406 return null;
4407 }
4408 if (lastPackage != null) {
4409 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4410 }
4411 return mSettings.mPackagesToBeCleaned.size() > 0
4412 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4413 }
4414 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004415
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004416 void schedulePackageCleaning(String packageName) {
4417 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4418 }
4419
4420 void startCleaningPackages() {
4421 synchronized (mPackages) {
4422 if (!mMediaMounted) {
4423 return;
4424 }
4425 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4426 return;
4427 }
4428 }
4429 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4430 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4431 IActivityManager am = ActivityManagerNative.getDefault();
4432 if (am != null) {
4433 try {
4434 am.startService(null, intent, null);
4435 } catch (RemoteException e) {
4436 }
4437 }
4438 }
4439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004440 private final class AppDirObserver extends FileObserver {
4441 public AppDirObserver(String path, int mask, boolean isrom) {
4442 super(path, mask);
4443 mRootDir = path;
4444 mIsRom = isrom;
4445 }
4446
4447 public void onEvent(int event, String path) {
4448 String removedPackage = null;
4449 int removedUid = -1;
4450 String addedPackage = null;
4451 int addedUid = -1;
4452
4453 synchronized (mInstallLock) {
4454 String fullPathStr = null;
4455 File fullPath = null;
4456 if (path != null) {
4457 fullPath = new File(mRootDir, path);
4458 fullPathStr = fullPath.getPath();
4459 }
4460
4461 if (Config.LOGV) Log.v(
4462 TAG, "File " + fullPathStr + " changed: "
4463 + Integer.toHexString(event));
4464
4465 if (!isPackageFilename(path)) {
4466 if (Config.LOGV) Log.v(
4467 TAG, "Ignoring change of non-package file: " + fullPathStr);
4468 return;
4469 }
4470
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004471 // Ignore packages that are being installed or
4472 // have just been installed.
4473 if (ignoreCodePath(fullPathStr)) {
4474 return;
4475 }
4476 PackageParser.Package p = null;
4477 synchronized (mPackages) {
4478 p = mAppDirs.get(fullPathStr);
4479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004480 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004481 if (p != null) {
4482 removePackageLI(p, true);
4483 removedPackage = p.applicationInfo.packageName;
4484 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 }
4486 }
4487
4488 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004490 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004491 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4492 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 PackageParser.PARSE_CHATTY |
4494 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004495 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4496 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 if (p != null) {
4498 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004499 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004500 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 }
4502 addedPackage = p.applicationInfo.packageName;
4503 addedUid = p.applicationInfo.uid;
4504 }
4505 }
4506 }
4507
4508 synchronized (mPackages) {
4509 mSettings.writeLP();
4510 }
4511 }
4512
4513 if (removedPackage != null) {
4514 Bundle extras = new Bundle(1);
4515 extras.putInt(Intent.EXTRA_UID, removedUid);
4516 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004517 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4518 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 }
4520 if (addedPackage != null) {
4521 Bundle extras = new Bundle(1);
4522 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004523 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4524 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004525 }
4526 }
4527
4528 private final String mRootDir;
4529 private final boolean mIsRom;
4530 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 /* Called when a downloaded package installation has been confirmed by the user */
4533 public void installPackage(
4534 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004535 installPackage(packageURI, observer, flags, null);
4536 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004537
Jacek Surazski65e13172009-04-28 15:26:38 +02004538 /* Called when a downloaded package installation has been confirmed by the user */
4539 public void installPackage(
4540 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4541 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004542 mContext.enforceCallingOrSelfPermission(
4543 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004544
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004545 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004546 msg.obj = new InstallParams(packageURI, observer, flags,
4547 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004548 mHandler.sendMessage(msg);
4549 }
4550
Christopher Tate1bb69062010-02-19 17:02:12 -08004551 public void finishPackageInstall(int token) {
4552 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4553 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4554 mHandler.sendMessage(msg);
4555 }
4556
Kenny Root93565c4b2010-06-18 15:46:06 -07004557 public void setPackageObbPath(String packageName, String path) {
4558 if (DEBUG_OBB)
4559 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4560 PackageSetting pkgSetting;
4561 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004562 final int permission = mContext.checkCallingPermission(
4563 android.Manifest.permission.INSTALL_PACKAGES);
4564 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004565 synchronized (mPackages) {
4566 pkgSetting = mSettings.mPackages.get(packageName);
4567 if (pkgSetting == null) {
4568 throw new IllegalArgumentException("Unknown package: " + packageName);
4569 }
4570 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4571 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4572 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4573 + pkgSetting.userId);
4574 }
4575 pkgSetting.obbPathString = path;
4576 mSettings.writeLP();
4577 }
4578 }
4579
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004580 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004581 // Queue up an async operation since the package installation may take a little while.
4582 mHandler.post(new Runnable() {
4583 public void run() {
4584 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004585 // Result object to be returned
4586 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004587 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004588 res.uid = -1;
4589 res.pkg = null;
4590 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004591 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004592 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004593 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004594 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004595 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004596 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004597 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004598
4599 // A restore should be performed at this point if (a) the install
4600 // succeeded, (b) the operation is not an update, and (c) the new
4601 // package has a backupAgent defined.
4602 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004603 boolean doRestore = (!update
4604 && res.pkg != null
4605 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004606
4607 // Set up the post-install work request bookkeeping. This will be used
4608 // and cleaned up by the post-install event handling regardless of whether
4609 // there's a restore pass performed. Token values are >= 1.
4610 int token;
4611 if (mNextInstallToken < 0) mNextInstallToken = 1;
4612 token = mNextInstallToken++;
4613
4614 PostInstallData data = new PostInstallData(args, res);
4615 mRunningInstalls.put(token, data);
4616 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4617
4618 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4619 // Pass responsibility to the Backup Manager. It will perform a
4620 // restore if appropriate, then pass responsibility back to the
4621 // Package Manager to run the post-install observer callbacks
4622 // and broadcasts.
4623 IBackupManager bm = IBackupManager.Stub.asInterface(
4624 ServiceManager.getService(Context.BACKUP_SERVICE));
4625 if (bm != null) {
4626 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4627 + " to BM for possible restore");
4628 try {
4629 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4630 } catch (RemoteException e) {
4631 // can't happen; the backup manager is local
4632 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004633 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004634 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004635 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004636 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004637 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004638 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004640 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004641
4642 if (!doRestore) {
4643 // No restore possible, or the Backup Manager was mysteriously not
4644 // available -- just fire the post-install work request directly.
4645 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4646 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4647 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 }
4650 });
4651 }
4652
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004653 abstract class HandlerParams {
4654 final static int MAX_RETRIES = 4;
4655 int retry = 0;
4656 final void startCopy() {
4657 try {
4658 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4659 retry++;
4660 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004661 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004662 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4663 handleServiceError();
4664 return;
4665 } else {
4666 handleStartCopy();
4667 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4668 mHandler.sendEmptyMessage(MCS_UNBIND);
4669 }
4670 } catch (RemoteException e) {
4671 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4672 mHandler.sendEmptyMessage(MCS_RECONNECT);
4673 }
4674 handleReturnCode();
4675 }
4676
4677 final void serviceError() {
4678 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4679 handleServiceError();
4680 handleReturnCode();
4681 }
4682 abstract void handleStartCopy() throws RemoteException;
4683 abstract void handleServiceError();
4684 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004685 }
4686
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004687 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004688 final IPackageInstallObserver observer;
4689 int flags;
4690 final Uri packageURI;
4691 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004692 private InstallArgs mArgs;
4693 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004694 InstallParams(Uri packageURI,
4695 IPackageInstallObserver observer, int flags,
4696 String installerPackageName) {
4697 this.packageURI = packageURI;
4698 this.flags = flags;
4699 this.observer = observer;
4700 this.installerPackageName = installerPackageName;
4701 }
4702
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004703 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4704 String packageName = pkgLite.packageName;
4705 int installLocation = pkgLite.installLocation;
4706 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4707 synchronized (mPackages) {
4708 PackageParser.Package pkg = mPackages.get(packageName);
4709 if (pkg != null) {
4710 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4711 // Check for updated system application.
4712 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4713 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004714 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004715 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4716 }
4717 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4718 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004719 if (onSd) {
4720 // Install flag overrides everything.
4721 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4722 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004723 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004724 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4725 // Application explicitly specified internal.
4726 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4727 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4728 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004729 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004730 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004731 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004732 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4733 }
4734 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004735 }
4736 }
4737 } else {
4738 // Invalid install. Return error code
4739 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4740 }
4741 }
4742 }
4743 // All the special cases have been taken care of.
4744 // Return result based on recommended install location.
4745 if (onSd) {
4746 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4747 }
4748 return pkgLite.recommendedInstallLocation;
4749 }
4750
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004751 /*
4752 * Invoke remote method to get package information and install
4753 * location values. Override install location based on default
4754 * policy if needed and then create install arguments based
4755 * on the install location.
4756 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004757 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004758 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004759 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4760 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004761 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4762 if (onInt && onSd) {
4763 // Check if both bits are set.
4764 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4765 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4766 } else if (fwdLocked && onSd) {
4767 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004768 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004769 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004770 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004771 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004772 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004773 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004774 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4775 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4776 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4777 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4778 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004779 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4780 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4781 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004782 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4783 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004784 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004785 // Override with defaults if needed.
4786 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004787 if (!onSd && !onInt) {
4788 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004789 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4790 // Set the flag to install on external media.
4791 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004792 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004793 } else {
4794 // Make sure the flag for installing on external
4795 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004796 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004797 flags &= ~PackageManager.INSTALL_EXTERNAL;
4798 }
4799 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004800 }
4801 }
4802 // Create the file args now.
4803 mArgs = createInstallArgs(this);
4804 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4805 // Create copy only if we are not in an erroneous state.
4806 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004807 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004808 }
4809 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004810 }
4811
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004812 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004813 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004814 // If mArgs is null, then MCS couldn't be reached. When it
4815 // reconnects, it will try again to install. At that point, this
4816 // will succeed.
4817 if (mArgs != null) {
4818 processPendingInstall(mArgs, mRet);
4819 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004820 }
4821
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004822 @Override
4823 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004824 mArgs = createInstallArgs(this);
4825 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004826 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004827 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004828
4829 /*
4830 * Utility class used in movePackage api.
4831 * srcArgs and targetArgs are not set for invalid flags and make
4832 * sure to do null checks when invoking methods on them.
4833 * We probably want to return ErrorPrams for both failed installs
4834 * and moves.
4835 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004836 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004837 final IPackageMoveObserver observer;
4838 final int flags;
4839 final String packageName;
4840 final InstallArgs srcArgs;
4841 final InstallArgs targetArgs;
4842 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004843
4844 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4845 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004846 this.srcArgs = srcArgs;
4847 this.observer = observer;
4848 this.flags = flags;
4849 this.packageName = packageName;
4850 if (srcArgs != null) {
4851 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004852 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004853 } else {
4854 targetArgs = null;
4855 }
4856 }
4857
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004858 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004859 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4860 // Check for storage space on target medium
4861 if (!targetArgs.checkFreeStorage(mContainerService)) {
4862 Log.w(TAG, "Insufficient storage to install");
4863 return;
4864 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004865 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004866 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004867 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004868 if (DEBUG_SD_INSTALL) {
4869 StringBuilder builder = new StringBuilder();
4870 if (srcArgs != null) {
4871 builder.append("src: ");
4872 builder.append(srcArgs.getCodePath());
4873 }
4874 if (targetArgs != null) {
4875 builder.append(" target : ");
4876 builder.append(targetArgs.getCodePath());
4877 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004878 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004879 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004880 }
4881
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004882 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004883 void handleReturnCode() {
4884 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004885 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4886 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4887 currentStatus = PackageManager.MOVE_SUCCEEDED;
4888 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4889 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4890 }
4891 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004892 }
4893
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004894 @Override
4895 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004896 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004897 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004898 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004899
4900 private InstallArgs createInstallArgs(InstallParams params) {
4901 if (installOnSd(params.flags)) {
4902 return new SdInstallArgs(params);
4903 } else {
4904 return new FileInstallArgs(params);
4905 }
4906 }
4907
Kenny Root85387d72010-08-26 10:13:11 -07004908 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4909 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004910 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004911 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004912 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004913 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004914 }
4915 }
4916
Kenny Root85387d72010-08-26 10:13:11 -07004917 // Used by package mover
4918 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004919 if (installOnSd(flags)) {
4920 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4921 return new SdInstallArgs(packageURI, cid);
4922 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004923 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004924 }
4925 }
4926
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004927 static abstract class InstallArgs {
4928 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004929 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004930 final int flags;
4931 final Uri packageURI;
4932 final String installerPackageName;
4933
4934 InstallArgs(Uri packageURI,
4935 IPackageInstallObserver observer, int flags,
4936 String installerPackageName) {
4937 this.packageURI = packageURI;
4938 this.flags = flags;
4939 this.observer = observer;
4940 this.installerPackageName = installerPackageName;
4941 }
4942
4943 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004944 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004945 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004946 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004947 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004948 abstract String getCodePath();
4949 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004950 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004951 // Need installer lock especially for dex file removal.
4952 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004953 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004954 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004955 }
4956
4957 class FileInstallArgs extends InstallArgs {
4958 File installDir;
4959 String codeFileName;
4960 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004961 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004962 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004963
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004964 FileInstallArgs(InstallParams params) {
4965 super(params.packageURI, params.observer,
4966 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004967 }
4968
Kenny Root85387d72010-08-26 10:13:11 -07004969 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004970 super(null, null, 0, null);
4971 File codeFile = new File(fullCodePath);
4972 installDir = codeFile.getParentFile();
4973 codeFileName = fullCodePath;
4974 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004975 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004976 }
4977
Kenny Root85387d72010-08-26 10:13:11 -07004978 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004979 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004980 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004981 String apkName = getNextCodePath(null, pkgName, ".apk");
4982 codeFileName = new File(installDir, apkName + ".apk").getPath();
4983 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004984 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004985 }
4986
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004987 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4988 return imcs.checkFreeStorage(false, packageURI);
4989 }
4990
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004991 String getCodePath() {
4992 return codeFileName;
4993 }
4994
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004995 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004996 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004997 codeFileName = createTempPackageFile(installDir).getPath();
4998 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004999 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005000 }
5001
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005002 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005003 if (temp) {
5004 // Generate temp file name
5005 createCopyFile();
5006 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005007 // Get a ParcelFileDescriptor to write to the output file
5008 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005009 if (!created) {
5010 try {
5011 codeFile.createNewFile();
5012 // Set permissions
5013 if (!setPermissions()) {
5014 // Failed setting permissions.
5015 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5016 }
5017 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005018 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005019 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5020 }
5021 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005022 ParcelFileDescriptor out = null;
5023 try {
Kenny Root85387d72010-08-26 10:13:11 -07005024 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005025 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005026 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005027 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5028 }
5029 // Copy the resource now
5030 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5031 try {
5032 if (imcs.copyResource(packageURI, out)) {
5033 ret = PackageManager.INSTALL_SUCCEEDED;
5034 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005035 } finally {
5036 try { if (out != null) out.close(); } catch (IOException e) {}
5037 }
Kenny Root85387d72010-08-26 10:13:11 -07005038
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005039 return ret;
5040 }
5041
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005042 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005043 if (status != PackageManager.INSTALL_SUCCEEDED) {
5044 cleanUp();
5045 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005046 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005047 }
5048
5049 boolean doRename(int status, final String pkgName, String oldCodePath) {
5050 if (status != PackageManager.INSTALL_SUCCEEDED) {
5051 cleanUp();
5052 return false;
5053 } else {
5054 // Rename based on packageName
5055 File codeFile = new File(getCodePath());
5056 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5057 File desFile = new File(installDir, apkName + ".apk");
5058 if (!codeFile.renameTo(desFile)) {
5059 return false;
5060 }
5061 // Reset paths since the file has been renamed.
5062 codeFileName = desFile.getPath();
5063 resourceFileName = getResourcePathFromCodePath();
5064 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005065 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005066 // Failed setting permissions.
5067 return false;
5068 }
5069 return true;
5070 }
5071 }
5072
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005073 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005074 if (status != PackageManager.INSTALL_SUCCEEDED) {
5075 cleanUp();
5076 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005077 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005078 }
5079
5080 String getResourcePath() {
5081 return resourceFileName;
5082 }
5083
5084 String getResourcePathFromCodePath() {
5085 String codePath = getCodePath();
5086 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5087 String apkNameOnly = getApkName(codePath);
5088 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5089 } else {
5090 return codePath;
5091 }
5092 }
5093
Kenny Root85387d72010-08-26 10:13:11 -07005094 @Override
5095 String getNativeLibraryPath() {
5096 return libraryPath;
5097 }
5098
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005099 private boolean cleanUp() {
5100 boolean ret = true;
5101 String sourceDir = getCodePath();
5102 String publicSourceDir = getResourcePath();
5103 if (sourceDir != null) {
5104 File sourceFile = new File(sourceDir);
5105 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005106 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 ret = false;
5108 }
5109 // Delete application's code and resources
5110 sourceFile.delete();
5111 }
5112 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5113 final File publicSourceFile = new File(publicSourceDir);
5114 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005115 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005116 }
5117 if (publicSourceFile.exists()) {
5118 publicSourceFile.delete();
5119 }
5120 }
5121 return ret;
5122 }
5123
5124 void cleanUpResourcesLI() {
5125 String sourceDir = getCodePath();
5126 if (cleanUp() && mInstaller != null) {
5127 int retCode = mInstaller.rmdex(sourceDir);
5128 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005129 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005130 + " at location "
5131 + sourceDir + ", retcode=" + retCode);
5132 // we don't consider this to be a failure of the core package deletion
5133 }
5134 }
Kenny Root85387d72010-08-26 10:13:11 -07005135 if (libraryPath != null) {
Kenny Root8f7cc022010-09-12 09:04:56 -07005136 NativeLibraryHelper.removeNativeBinariesLI(libraryPath);
Kenny Root85387d72010-08-26 10:13:11 -07005137 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005138 }
5139
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005140 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005141 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005142 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005143 final int filePermissions =
5144 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5145 |FileUtils.S_IROTH;
5146 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5147 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005148 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005149 getCodePath()
5150 + ". The return code was: " + retCode);
5151 // TODO Define new internal error
5152 return false;
5153 }
5154 return true;
5155 }
5156 return true;
5157 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005158
5159 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005160 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005161 cleanUpResourcesLI();
5162 return true;
5163 }
Kenny Root85387d72010-08-26 10:13:11 -07005164
5165 private boolean isFwdLocked() {
5166 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5167 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005168 }
5169
5170 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005171 static final String RES_FILE_NAME = "pkg.apk";
5172
Kenny Root85387d72010-08-26 10:13:11 -07005173 String cid;
5174 String packagePath;
5175 String libraryPath;
5176
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005177 SdInstallArgs(InstallParams params) {
5178 super(params.packageURI, params.observer,
5179 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005180 }
5181
Kenny Root85387d72010-08-26 10:13:11 -07005182 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005183 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005184 // Extract cid from fullCodePath
5185 int eidx = fullCodePath.lastIndexOf("/");
5186 String subStr1 = fullCodePath.substring(0, eidx);
5187 int sidx = subStr1.lastIndexOf("/");
5188 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005189 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005190 }
5191
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005192 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005193 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5194 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005195 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005196 }
5197
5198 SdInstallArgs(Uri packageURI, String cid) {
5199 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005200 this.cid = cid;
5201 }
5202
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005203 void createCopyFile() {
5204 cid = getTempContainerId();
5205 }
5206
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005207 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5208 return imcs.checkFreeStorage(true, packageURI);
5209 }
5210
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005211 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005212 if (temp) {
5213 createCopyFile();
5214 }
Kenny Root85387d72010-08-26 10:13:11 -07005215 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005216 packageURI, cid,
5217 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005218 if (newCachePath != null) {
5219 setCachePath(newCachePath);
5220 return PackageManager.INSTALL_SUCCEEDED;
5221 } else {
5222 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5223 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005224 }
5225
5226 @Override
5227 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005228 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005229 }
5230
5231 @Override
5232 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005233 return packagePath;
5234 }
5235
5236 @Override
5237 String getNativeLibraryPath() {
5238 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005239 }
5240
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005241 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005242 if (status != PackageManager.INSTALL_SUCCEEDED) {
5243 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005244 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005245 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005246 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005247 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005248 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5249 Process.SYSTEM_UID);
5250 if (newCachePath != null) {
5251 setCachePath(newCachePath);
5252 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005253 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5254 }
5255 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005256 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005257 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005258 }
5259
5260 boolean doRename(int status, final String pkgName,
5261 String oldCodePath) {
5262 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005263 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005264 if (PackageHelper.isContainerMounted(cid)) {
5265 // Unmount the container
5266 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005267 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005268 return false;
5269 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005270 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005271 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005272 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5273 " which might be stale. Will try to clean up.");
5274 // Clean up the stale container and proceed to recreate.
5275 if (!PackageHelper.destroySdDir(newCacheId)) {
5276 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5277 return false;
5278 }
5279 // Successfully cleaned up stale container. Try to rename again.
5280 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5281 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5282 + " inspite of cleaning it up.");
5283 return false;
5284 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005285 }
5286 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005287 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005288 newCachePath = PackageHelper.mountSdDir(newCacheId,
5289 getEncryptKey(), Process.SYSTEM_UID);
5290 } else {
5291 newCachePath = PackageHelper.getSdDir(newCacheId);
5292 }
5293 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005294 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005295 return false;
5296 }
5297 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005298 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005299 " at new path: " + newCachePath);
5300 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005301 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005302 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005303 }
5304
Kenny Root85387d72010-08-26 10:13:11 -07005305 private void setCachePath(String newCachePath) {
5306 File cachePath = new File(newCachePath);
5307 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5308 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5309 }
5310
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005311 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005312 if (status != PackageManager.INSTALL_SUCCEEDED) {
5313 cleanUp();
5314 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005315 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005316 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005317 PackageHelper.mountSdDir(cid,
5318 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005319 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005320 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005321 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005322 }
5323
5324 private void cleanUp() {
5325 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005326 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005327 }
5328
5329 void cleanUpResourcesLI() {
5330 String sourceFile = getCodePath();
5331 // Remove dex file
5332 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005333 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005334 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005335 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005336 + " at location "
5337 + sourceFile.toString() + ", retcode=" + retCode);
5338 // we don't consider this to be a failure of the core package deletion
5339 }
5340 }
5341 cleanUp();
5342 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005343
5344 boolean matchContainer(String app) {
5345 if (cid.startsWith(app)) {
5346 return true;
5347 }
5348 return false;
5349 }
5350
5351 String getPackageName() {
5352 int idx = cid.lastIndexOf("-");
5353 if (idx == -1) {
5354 return cid;
5355 }
5356 return cid.substring(0, idx);
5357 }
5358
5359 boolean doPostDeleteLI(boolean delete) {
5360 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005361 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005362 if (mounted) {
5363 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005364 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005365 }
5366 if (ret && delete) {
5367 cleanUpResourcesLI();
5368 }
5369 return ret;
5370 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 };
5372
5373 // Utility method used to create code paths based on package name and available index.
5374 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5375 String idxStr = "";
5376 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005377 // Fall back to default value of idx=1 if prefix is not
5378 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005379 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005380 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005381 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005382 if (subStr.endsWith(suffix)) {
5383 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005384 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005385 // If oldCodePath already contains prefix find out the
5386 // ending index to either increment or decrement.
5387 int sidx = subStr.lastIndexOf(prefix);
5388 if (sidx != -1) {
5389 subStr = subStr.substring(sidx + prefix.length());
5390 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005391 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5392 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005393 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005394 try {
5395 idx = Integer.parseInt(subStr);
5396 if (idx <= 1) {
5397 idx++;
5398 } else {
5399 idx--;
5400 }
5401 } catch(NumberFormatException e) {
5402 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005403 }
5404 }
5405 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005406 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005407 return prefix + idxStr;
5408 }
5409
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005410 // Utility method used to ignore ADD/REMOVE events
5411 // by directory observer.
5412 private static boolean ignoreCodePath(String fullPathStr) {
5413 String apkName = getApkName(fullPathStr);
5414 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5415 if (idx != -1 && ((idx+1) < apkName.length())) {
5416 // Make sure the package ends with a numeral
5417 String version = apkName.substring(idx+1);
5418 try {
5419 Integer.parseInt(version);
5420 return true;
5421 } catch (NumberFormatException e) {}
5422 }
5423 return false;
5424 }
5425
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005426 // Utility method that returns the relative package path with respect
5427 // to the installation directory. Like say for /data/data/com.test-1.apk
5428 // string com.test-1 is returned.
5429 static String getApkName(String codePath) {
5430 if (codePath == null) {
5431 return null;
5432 }
5433 int sidx = codePath.lastIndexOf("/");
5434 int eidx = codePath.lastIndexOf(".");
5435 if (eidx == -1) {
5436 eidx = codePath.length();
5437 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005438 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005439 return null;
5440 }
5441 return codePath.substring(sidx+1, eidx);
5442 }
5443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005444 class PackageInstalledInfo {
5445 String name;
5446 int uid;
5447 PackageParser.Package pkg;
5448 int returnCode;
5449 PackageRemovedInfo removedInfo;
5450 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 /*
5453 * Install a non-existing package.
5454 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005455 private void installNewPackageLI(PackageParser.Package pkg,
5456 int parseFlags,
5457 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005458 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005460 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005461
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005462 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 res.name = pkgName;
5464 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005465 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5466 // A package with the same name is already installed, though
5467 // it has been renamed to an older name. The package we
5468 // are trying to install should be installed as an update to
5469 // the existing one, but that has not been requested, so bail.
5470 Slog.w(TAG, "Attempt to re-install " + pkgName
5471 + " without first uninstalling package running as "
5472 + mSettings.mRenamedPackages.get(pkgName));
5473 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5474 return;
5475 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005476 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005478 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 + " without first uninstalling.");
5480 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5481 return;
5482 }
5483 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005484 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005485 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5486 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005487 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005488 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5490 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5491 }
5492 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005493 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005494 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 res);
5496 // delete the partially installed application. the data directory will have to be
5497 // restored if it was already existing
5498 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5499 // remove package from internal structures. Note that we want deletePackageX to
5500 // delete the package data and cache directories that it created in
5501 // scanPackageLocked, unless those directories existed before we even tried to
5502 // install.
5503 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005504 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005505 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005506 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005507 }
5508 }
5509 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005510
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005511 private void replacePackageLI(PackageParser.Package pkg,
5512 int parseFlags,
5513 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005514 String installerPackageName, PackageInstalledInfo res) {
5515
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005516 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005517 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 // First find the old package info and check signatures
5519 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005520 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005521 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005522 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005523 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5524 return;
5525 }
5526 }
Kenny Root85387d72010-08-26 10:13:11 -07005527 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005528 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005529 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005531 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 }
5533 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005536 PackageParser.Package pkg,
5537 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005538 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 PackageParser.Package newPackage = null;
5540 String pkgName = deletedPackage.packageName;
5541 boolean deletedPkg = true;
5542 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005543
Jacek Surazski65e13172009-04-28 15:26:38 +02005544 String oldInstallerPackageName = null;
5545 synchronized (mPackages) {
5546 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005548
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005549 long origUpdateTime;
5550 if (pkg.mExtras != null) {
5551 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5552 } else {
5553 origUpdateTime = 0;
5554 }
5555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005557 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005558 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005559 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005560 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5561 deletedPkg = false;
5562 } else {
5563 // Successfully deleted the old package. Now proceed with re-installation
5564 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005565 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5566 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005568 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005569 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5570 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005571 }
5572 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005573 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005574 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 res);
5576 updatedSettings = true;
5577 }
5578 }
5579
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005580 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005581 // remove package from internal structures. Note that we want deletePackageX to
5582 // delete the package data and cache directories that it created in
5583 // scanPackageLocked, unless those directories existed before we even tried to
5584 // install.
5585 if(updatedSettings) {
5586 deletePackageLI(
5587 pkgName, true,
5588 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005589 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 }
5591 // Since we failed to install the new package we need to restore the old
5592 // package that we deleted.
5593 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005594 File restoreFile = new File(deletedPackage.mPath);
5595 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005596 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005597 return;
5598 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005599 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005600 boolean oldOnSd = isExternal(deletedPackage);
5601 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5602 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5603 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005604 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5605 | SCAN_UPDATE_TIME;
5606 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5607 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005608 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5609 return;
5610 }
5611 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005612 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005613 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005614 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005615 mSettings.writeLP();
5616 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005617 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 }
5619 }
5620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005622 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005623 PackageParser.Package pkg,
5624 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005625 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 PackageParser.Package newPackage = null;
5627 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005628 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005629 PackageParser.PARSE_IS_SYSTEM;
5630 String packageName = deletedPackage.packageName;
5631 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5632 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005633 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 return;
5635 }
5636 PackageParser.Package oldPkg;
5637 PackageSetting oldPkgSetting;
5638 synchronized (mPackages) {
5639 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005640 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5642 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005643 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 return;
5645 }
5646 }
5647 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5648 res.removedInfo.removedPackage = packageName;
5649 // Remove existing system package
5650 removePackageLI(oldPkg, true);
5651 synchronized (mPackages) {
5652 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5653 }
5654
5655 // Successfully disabled the old package. Now proceed with re-installation
5656 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5657 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005658 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005660 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5662 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5663 }
5664 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005665 if (newPackage.mExtras != null) {
5666 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5667 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5668 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5669 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005670 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 updatedSettings = true;
5672 }
5673
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005674 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005675 // Re installation failed. Restore old information
5676 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005677 if (newPackage != null) {
5678 removePackageLI(newPackage, true);
5679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005681 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 // Restore the old system information in Settings
5683 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005684 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005686 mSettings.setInstallerPackageName(packageName,
5687 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005688 }
5689 mSettings.writeLP();
5690 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005691 } else {
5692 // If this is an update to an existing update, setup
5693 // to remove the existing update.
5694 synchronized (mPackages) {
5695 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5696 if (ps != null && ps.codePathString != null &&
5697 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005698 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005699 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005700 }
5701 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005702 }
5703 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005704
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005705 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005706 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005707 int retCode;
5708 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5709 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5710 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005711 if (mNoDexOpt) {
5712 /*
5713 * If we're in an engineering build, programs are lazily run
5714 * through dexopt. If the .dex file doesn't exist yet, it
5715 * will be created when the program is run next.
5716 */
5717 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5718 } else {
5719 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5720 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5721 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005722 }
5723 }
5724 return PackageManager.INSTALL_SUCCEEDED;
5725 }
5726
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005727 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005728 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005729 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 synchronized (mPackages) {
5731 //write settings. the installStatus will be incomplete at this stage.
5732 //note that the new package setting would have already been
5733 //added to mPackages. It hasn't been persisted yet.
5734 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5735 mSettings.writeLP();
5736 }
5737
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005738 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005739 != PackageManager.INSTALL_SUCCEEDED) {
5740 // Discontinue if moving dex files failed.
5741 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005742 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005743 if((res.returnCode = setPermissionsLI(newPackage))
5744 != PackageManager.INSTALL_SUCCEEDED) {
5745 if (mInstaller != null) {
5746 mInstaller.rmdex(newPackage.mScanPath);
5747 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005748 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005749 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005750 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005753 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005754 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 res.name = pkgName;
5756 res.uid = newPackage.applicationInfo.uid;
5757 res.pkg = newPackage;
5758 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005759 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005760 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5761 //to update install status
5762 mSettings.writeLP();
5763 }
5764 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005765
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005766 private void installPackageLI(InstallArgs args,
5767 boolean newInstall, PackageInstalledInfo res) {
5768 int pFlags = args.flags;
5769 String installerPackageName = args.installerPackageName;
5770 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005771 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005772 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005773 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005774 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005775 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005776 // Result object to be returned
5777 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5778
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005779 // Retrieve PackageSettings and parse package
5780 int parseFlags = PackageParser.PARSE_CHATTY |
5781 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5782 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5783 parseFlags |= mDefParseFlags;
5784 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5785 pp.setSeparateProcesses(mSeparateProcesses);
5786 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5787 null, mMetrics, parseFlags);
5788 if (pkg == null) {
5789 res.returnCode = pp.getParseError();
5790 return;
5791 }
5792 String pkgName = res.name = pkg.packageName;
5793 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5794 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5795 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5796 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005798 }
5799 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5800 res.returnCode = pp.getParseError();
5801 return;
5802 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005803 // Get rid of all references to package scan path via parser.
5804 pp = null;
5805 String oldCodePath = null;
5806 boolean systemApp = false;
5807 synchronized (mPackages) {
5808 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005809 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5810 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005811 if (pkg.mOriginalPackages != null
5812 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005813 && mPackages.containsKey(oldName)) {
5814 // This package is derived from an original package,
5815 // and this device has been updating from that original
5816 // name. We must continue using the original name, so
5817 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005818 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005819 pkgName = pkg.packageName;
5820 replace = true;
5821 } else if (mPackages.containsKey(pkgName)) {
5822 // This package, under its official name, already exists
5823 // on the device; we should replace it.
5824 replace = true;
5825 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005826 }
5827 PackageSetting ps = mSettings.mPackages.get(pkgName);
5828 if (ps != null) {
5829 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5830 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5831 systemApp = (ps.pkg.applicationInfo.flags &
5832 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005833 }
5834 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005836
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005837 if (systemApp && onSd) {
5838 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005839 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005840 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5841 return;
5842 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005843
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005844 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5845 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5846 return;
5847 }
5848 // Set application objects path explicitly after the rename
5849 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005850 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005851 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005852 replacePackageLI(pkg, parseFlags, scanMode,
5853 installerPackageName, res);
5854 } else {
5855 installNewPackageLI(pkg, parseFlags, scanMode,
5856 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 }
5858 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005859
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005860 private int setPermissionsLI(PackageParser.Package newPackage) {
5861 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005862 int retCode = 0;
5863 // TODO Gross hack but fix later. Ideally move this to be a post installation
5864 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005865 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005866 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 try {
5868 extractPublicFiles(newPackage, destResourceFile);
5869 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005870 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 -08005871 " forward-locked app.");
5872 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5873 } finally {
5874 //TODO clean up the extracted public files
5875 }
5876 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005877 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 newPackage.applicationInfo.uid);
5879 } else {
5880 final int filePermissions =
5881 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005882 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005883 newPackage.applicationInfo.uid);
5884 }
5885 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005886 // The permissions on the resource file was set when it was copied for
5887 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005888 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005890 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005891 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005892 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005893 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005894 // TODO Define new internal error
5895 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005896 }
5897 return PackageManager.INSTALL_SUCCEEDED;
5898 }
5899
Kenny Root85387d72010-08-26 10:13:11 -07005900 private static boolean isForwardLocked(PackageParser.Package pkg) {
5901 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 }
5903
Kenny Root85387d72010-08-26 10:13:11 -07005904 private static boolean isExternal(PackageParser.Package pkg) {
5905 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5906 }
5907
5908 private static boolean isSystemApp(PackageParser.Package pkg) {
5909 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5910 }
5911
5912 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5913 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005914 }
5915
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 private void extractPublicFiles(PackageParser.Package newPackage,
5917 File publicZipFile) throws IOException {
5918 final ZipOutputStream publicZipOutStream =
5919 new ZipOutputStream(new FileOutputStream(publicZipFile));
5920 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5921
5922 // Copy manifest, resources.arsc and res directory to public zip
5923
5924 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5925 while (privateZipEntries.hasMoreElements()) {
5926 final ZipEntry zipEntry = privateZipEntries.nextElement();
5927 final String zipEntryName = zipEntry.getName();
5928 if ("AndroidManifest.xml".equals(zipEntryName)
5929 || "resources.arsc".equals(zipEntryName)
5930 || zipEntryName.startsWith("res/")) {
5931 try {
5932 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5933 } catch (IOException e) {
5934 try {
5935 publicZipOutStream.close();
5936 throw e;
5937 } finally {
5938 publicZipFile.delete();
5939 }
5940 }
5941 }
5942 }
5943
5944 publicZipOutStream.close();
5945 FileUtils.setPermissions(
5946 publicZipFile.getAbsolutePath(),
5947 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5948 -1, -1);
5949 }
5950
5951 private static void copyZipEntry(ZipEntry zipEntry,
5952 ZipFile inZipFile,
5953 ZipOutputStream outZipStream) throws IOException {
5954 byte[] buffer = new byte[4096];
5955 int num;
5956
5957 ZipEntry newEntry;
5958 if (zipEntry.getMethod() == ZipEntry.STORED) {
5959 // Preserve the STORED method of the input entry.
5960 newEntry = new ZipEntry(zipEntry);
5961 } else {
5962 // Create a new entry so that the compressed len is recomputed.
5963 newEntry = new ZipEntry(zipEntry.getName());
5964 }
5965 outZipStream.putNextEntry(newEntry);
5966
5967 InputStream data = inZipFile.getInputStream(zipEntry);
5968 while ((num = data.read(buffer)) > 0) {
5969 outZipStream.write(buffer, 0, num);
5970 }
5971 outZipStream.flush();
5972 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 private void deleteTempPackageFiles() {
5975 FilenameFilter filter = new FilenameFilter() {
5976 public boolean accept(File dir, String name) {
5977 return name.startsWith("vmdl") && name.endsWith(".tmp");
5978 }
5979 };
5980 String tmpFilesList[] = mAppInstallDir.list(filter);
5981 if(tmpFilesList == null) {
5982 return;
5983 }
5984 for(int i = 0; i < tmpFilesList.length; i++) {
5985 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5986 tmpFile.delete();
5987 }
5988 }
5989
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005990 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 File tmpPackageFile;
5992 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005993 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005994 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005995 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 return null;
5997 }
5998 try {
5999 FileUtils.setPermissions(
6000 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6001 -1, -1);
6002 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006003 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006004 return null;
6005 }
6006 return tmpPackageFile;
6007 }
6008
6009 public void deletePackage(final String packageName,
6010 final IPackageDeleteObserver observer,
6011 final int flags) {
6012 mContext.enforceCallingOrSelfPermission(
6013 android.Manifest.permission.DELETE_PACKAGES, null);
6014 // Queue up an async operation since the package deletion may take a little while.
6015 mHandler.post(new Runnable() {
6016 public void run() {
6017 mHandler.removeCallbacks(this);
6018 final boolean succeded = deletePackageX(packageName, true, true, flags);
6019 if (observer != null) {
6020 try {
6021 observer.packageDeleted(succeded);
6022 } catch (RemoteException e) {
6023 Log.i(TAG, "Observer no longer exists.");
6024 } //end catch
6025 } //end if
6026 } //end run
6027 });
6028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 /**
6031 * This method is an internal method that could be get invoked either
6032 * to delete an installed package or to clean up a failed installation.
6033 * After deleting an installed package, a broadcast is sent to notify any
6034 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006035 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006036 * installation wouldn't have sent the initial broadcast either
6037 * The key steps in deleting a package are
6038 * deleting the package information in internal structures like mPackages,
6039 * deleting the packages base directories through installd
6040 * updating mSettings to reflect current status
6041 * persisting settings for later use
6042 * sending a broadcast if necessary
6043 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6045 boolean deleteCodeAndResources, int flags) {
6046 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006047 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006048
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006049 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6050 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6051 try {
6052 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006053 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006054 return false;
6055 }
6056 } catch (RemoteException e) {
6057 }
6058
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006060 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006061 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006062 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006065 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006066 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006067
6068 // If the removed package was a system update, the old system packaged
6069 // was re-enabled; we need to broadcast this information
6070 if (systemUpdate) {
6071 Bundle extras = new Bundle(1);
6072 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6073 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6074
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006075 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6076 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006077 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006079 // Force a gc here.
6080 Runtime.getRuntime().gc();
6081 // Delete the resources here after sending the broadcast to let
6082 // other processes clean up before deleting resources.
6083 if (info.args != null) {
6084 synchronized (mInstallLock) {
6085 info.args.doPostDeleteLI(deleteCodeAndResources);
6086 }
6087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 return res;
6089 }
6090
6091 static class PackageRemovedInfo {
6092 String removedPackage;
6093 int uid = -1;
6094 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006095 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006096 // Clean up resources deleted packages.
6097 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006098
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006099 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 Bundle extras = new Bundle(1);
6101 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6102 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6103 if (replacing) {
6104 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6105 }
6106 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006107 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 }
6109 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006110 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 }
6112 }
6113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 /*
6116 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6117 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006118 * 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 -08006119 * delete a partially installed application.
6120 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006121 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006122 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006124 if (outInfo != null) {
6125 outInfo.removedPackage = packageName;
6126 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006127 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 // Retrieve object to delete permissions for shared user later on
6129 PackageSetting deletedPs;
6130 synchronized (mPackages) {
6131 deletedPs = mSettings.mPackages.get(packageName);
6132 }
6133 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006134 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006136 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006137 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006138 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006139 + packageName + ", retcode=" + retCode);
6140 // we don't consider this to be a failure of the core package deletion
6141 }
6142 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006143 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 PackageParser.Package pkg = mPackages.get(packageName);
6145 File dataDir = new File(pkg.applicationInfo.dataDir);
6146 dataDir.delete();
6147 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006148 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 }
6150 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006151 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006152 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6153 if (outInfo != null) {
6154 outInfo.removedUid = mSettings.removePackageLP(packageName);
6155 }
6156 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006157 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006158 if (deletedPs.sharedUser != null) {
6159 // remove permissions associated with package
6160 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6161 }
6162 }
6163 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006164 // remove from preferred activities.
6165 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6166 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6167 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6168 removed.add(pa);
6169 }
6170 }
6171 for (PreferredActivity pa : removed) {
6172 mSettings.mPreferredActivities.removeFilter(pa);
6173 }
6174 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006175 if (writeSettings) {
6176 // Save settings now
6177 mSettings.writeLP();
6178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 }
6180 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 /*
6183 * Tries to delete system package.
6184 */
6185 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006186 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 ApplicationInfo applicationInfo = p.applicationInfo;
6188 //applicable for non-partially installed applications only
6189 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006190 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006191 return false;
6192 }
6193 PackageSetting ps = null;
6194 // Confirm if the system package has been updated
6195 // An updated system app can be deleted. This will also have to restore
6196 // the system pkg from system partition
6197 synchronized (mPackages) {
6198 ps = mSettings.getDisabledSystemPkg(p.packageName);
6199 }
6200 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006201 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 return false;
6203 } else {
6204 Log.i(TAG, "Deleting system pkg from data partition");
6205 }
6206 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006207 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006208 final boolean deleteCodeAndResources;
6209 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006210 // Delete code and resources for downgrades
6211 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006212 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006213 } else {
6214 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006215 deleteCodeAndResources = false;
6216 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006217 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006218 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6219 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 if (!ret) {
6221 return false;
6222 }
6223 synchronized (mPackages) {
6224 // Reinstate the old system package
6225 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006226 // Remove any native libraries from the upgraded package.
6227 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006228 }
6229 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006230 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006232 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006235 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 return false;
6237 }
6238 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006239 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006240 if (writeSettings) {
6241 mSettings.writeLP();
6242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 }
6244 return true;
6245 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006247 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006248 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6249 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006250 ApplicationInfo applicationInfo = p.applicationInfo;
6251 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006252 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006253 return false;
6254 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006255 if (outInfo != null) {
6256 outInfo.uid = applicationInfo.uid;
6257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258
6259 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006260 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006261
6262 // Delete application code and resources
6263 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006264 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006265 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6266 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6267 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6268 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 }
6270 return true;
6271 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 /*
6274 * This method handles package deletion in general
6275 */
6276 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006277 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6278 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006280 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 return false;
6282 }
6283 PackageParser.Package p;
6284 boolean dataOnly = false;
6285 synchronized (mPackages) {
6286 p = mPackages.get(packageName);
6287 if (p == null) {
6288 //this retrieves partially installed apps
6289 dataOnly = true;
6290 PackageSetting ps = mSettings.mPackages.get(packageName);
6291 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006292 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293 return false;
6294 }
6295 p = ps.pkg;
6296 }
6297 }
6298 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006299 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 return false;
6301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 if (dataOnly) {
6304 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006305 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006306 return true;
6307 }
6308 // At this point the package should have ApplicationInfo associated with it
6309 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006310 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 return false;
6312 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006313 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006314 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 Log.i(TAG, "Removing system package:"+p.packageName);
6316 // When an updated system application is deleted we delete the existing resources as well and
6317 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006318 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006319 } else {
6320 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006321 // Kill application pre-emptively especially for apps on sd.
6322 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006323 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6324 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006325 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006326 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006329 public void clearApplicationUserData(final String packageName,
6330 final IPackageDataObserver observer) {
6331 mContext.enforceCallingOrSelfPermission(
6332 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6333 // Queue up an async operation since the package deletion may take a little while.
6334 mHandler.post(new Runnable() {
6335 public void run() {
6336 mHandler.removeCallbacks(this);
6337 final boolean succeeded;
6338 synchronized (mInstallLock) {
6339 succeeded = clearApplicationUserDataLI(packageName);
6340 }
6341 if (succeeded) {
6342 // invoke DeviceStorageMonitor's update method to clear any notifications
6343 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6344 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6345 if (dsm != null) {
6346 dsm.updateMemory();
6347 }
6348 }
6349 if(observer != null) {
6350 try {
6351 observer.onRemoveCompleted(packageName, succeeded);
6352 } catch (RemoteException e) {
6353 Log.i(TAG, "Observer no longer exists.");
6354 }
6355 } //end if observer
6356 } //end run
6357 });
6358 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 private boolean clearApplicationUserDataLI(String packageName) {
6361 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006362 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 return false;
6364 }
6365 PackageParser.Package p;
6366 boolean dataOnly = false;
6367 synchronized (mPackages) {
6368 p = mPackages.get(packageName);
6369 if(p == null) {
6370 dataOnly = true;
6371 PackageSetting ps = mSettings.mPackages.get(packageName);
6372 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006373 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 return false;
6375 }
6376 p = ps.pkg;
6377 }
6378 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006379 boolean useEncryptedFSDir = false;
6380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006381 if(!dataOnly) {
6382 //need to check this only for fully installed applications
6383 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006384 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006385 return false;
6386 }
6387 final ApplicationInfo applicationInfo = p.applicationInfo;
6388 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006389 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 return false;
6391 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006392 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393 }
6394 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006395 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006397 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 + packageName);
6399 return false;
6400 }
6401 }
6402 return true;
6403 }
6404
6405 public void deleteApplicationCacheFiles(final String packageName,
6406 final IPackageDataObserver observer) {
6407 mContext.enforceCallingOrSelfPermission(
6408 android.Manifest.permission.DELETE_CACHE_FILES, null);
6409 // Queue up an async operation since the package deletion may take a little while.
6410 mHandler.post(new Runnable() {
6411 public void run() {
6412 mHandler.removeCallbacks(this);
6413 final boolean succeded;
6414 synchronized (mInstallLock) {
6415 succeded = deleteApplicationCacheFilesLI(packageName);
6416 }
6417 if(observer != null) {
6418 try {
6419 observer.onRemoveCompleted(packageName, succeded);
6420 } catch (RemoteException e) {
6421 Log.i(TAG, "Observer no longer exists.");
6422 }
6423 } //end if observer
6424 } //end run
6425 });
6426 }
6427
6428 private boolean deleteApplicationCacheFilesLI(String packageName) {
6429 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006430 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 return false;
6432 }
6433 PackageParser.Package p;
6434 synchronized (mPackages) {
6435 p = mPackages.get(packageName);
6436 }
6437 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006438 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 return false;
6440 }
6441 final ApplicationInfo applicationInfo = p.applicationInfo;
6442 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006443 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 return false;
6445 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006446 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006448 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006449 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006450 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006451 + packageName);
6452 return false;
6453 }
6454 }
6455 return true;
6456 }
6457
6458 public void getPackageSizeInfo(final String packageName,
6459 final IPackageStatsObserver observer) {
6460 mContext.enforceCallingOrSelfPermission(
6461 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6462 // Queue up an async operation since the package deletion may take a little while.
6463 mHandler.post(new Runnable() {
6464 public void run() {
6465 mHandler.removeCallbacks(this);
6466 PackageStats lStats = new PackageStats(packageName);
6467 final boolean succeded;
6468 synchronized (mInstallLock) {
6469 succeded = getPackageSizeInfoLI(packageName, lStats);
6470 }
6471 if(observer != null) {
6472 try {
6473 observer.onGetStatsCompleted(lStats, succeded);
6474 } catch (RemoteException e) {
6475 Log.i(TAG, "Observer no longer exists.");
6476 }
6477 } //end if observer
6478 } //end run
6479 });
6480 }
6481
6482 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6483 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006484 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 return false;
6486 }
6487 PackageParser.Package p;
6488 boolean dataOnly = false;
6489 synchronized (mPackages) {
6490 p = mPackages.get(packageName);
6491 if(p == null) {
6492 dataOnly = true;
6493 PackageSetting ps = mSettings.mPackages.get(packageName);
6494 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006495 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 return false;
6497 }
6498 p = ps.pkg;
6499 }
6500 }
6501 String publicSrcDir = null;
6502 if(!dataOnly) {
6503 final ApplicationInfo applicationInfo = p.applicationInfo;
6504 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006505 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006506 return false;
6507 }
6508 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6509 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006510 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006511 if (mInstaller != null) {
6512 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006513 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006514 if (res < 0) {
6515 return false;
6516 } else {
6517 return true;
6518 }
6519 }
6520 return true;
6521 }
6522
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006525 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 }
6527
6528 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006529 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006530 }
6531
6532 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006533 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 }
6535
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006536 int getUidTargetSdkVersionLockedLP(int uid) {
6537 Object obj = mSettings.getUserIdLP(uid);
6538 if (obj instanceof SharedUserSetting) {
6539 SharedUserSetting sus = (SharedUserSetting)obj;
6540 final int N = sus.packages.size();
6541 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6542 Iterator<PackageSetting> it = sus.packages.iterator();
6543 int i=0;
6544 while (it.hasNext()) {
6545 PackageSetting ps = it.next();
6546 if (ps.pkg != null) {
6547 int v = ps.pkg.applicationInfo.targetSdkVersion;
6548 if (v < vers) vers = v;
6549 }
6550 }
6551 return vers;
6552 } else if (obj instanceof PackageSetting) {
6553 PackageSetting ps = (PackageSetting)obj;
6554 if (ps.pkg != null) {
6555 return ps.pkg.applicationInfo.targetSdkVersion;
6556 }
6557 }
6558 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6559 }
6560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 public void addPreferredActivity(IntentFilter filter, int match,
6562 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006563 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006564 if (mContext.checkCallingOrSelfPermission(
6565 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6566 != PackageManager.PERMISSION_GRANTED) {
6567 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6568 < Build.VERSION_CODES.FROYO) {
6569 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6570 + Binder.getCallingUid());
6571 return;
6572 }
6573 mContext.enforceCallingOrSelfPermission(
6574 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6575 }
6576
6577 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006578 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6579 mSettings.mPreferredActivities.addFilter(
6580 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006581 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006582 }
6583 }
6584
Satish Sampath8dbe6122009-06-02 23:35:54 +01006585 public void replacePreferredActivity(IntentFilter filter, int match,
6586 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006587 if (filter.countActions() != 1) {
6588 throw new IllegalArgumentException(
6589 "replacePreferredActivity expects filter to have only 1 action.");
6590 }
6591 if (filter.countCategories() != 1) {
6592 throw new IllegalArgumentException(
6593 "replacePreferredActivity expects filter to have only 1 category.");
6594 }
6595 if (filter.countDataAuthorities() != 0
6596 || filter.countDataPaths() != 0
6597 || filter.countDataSchemes() != 0
6598 || filter.countDataTypes() != 0) {
6599 throw new IllegalArgumentException(
6600 "replacePreferredActivity expects filter to have no data authorities, " +
6601 "paths, schemes or types.");
6602 }
6603 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006604 if (mContext.checkCallingOrSelfPermission(
6605 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6606 != PackageManager.PERMISSION_GRANTED) {
6607 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6608 < Build.VERSION_CODES.FROYO) {
6609 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6610 + Binder.getCallingUid());
6611 return;
6612 }
6613 mContext.enforceCallingOrSelfPermission(
6614 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6615 }
6616
Satish Sampath8dbe6122009-06-02 23:35:54 +01006617 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6618 String action = filter.getAction(0);
6619 String category = filter.getCategory(0);
6620 while (it.hasNext()) {
6621 PreferredActivity pa = it.next();
6622 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6623 it.remove();
6624 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6625 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6626 }
6627 }
6628 addPreferredActivity(filter, match, set, activity);
6629 }
6630 }
6631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006632 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006633 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006634 int uid = Binder.getCallingUid();
6635 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006636 if (pkg == null || pkg.applicationInfo.uid != uid) {
6637 if (mContext.checkCallingOrSelfPermission(
6638 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6639 != PackageManager.PERMISSION_GRANTED) {
6640 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6641 < Build.VERSION_CODES.FROYO) {
6642 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6643 + Binder.getCallingUid());
6644 return;
6645 }
6646 mContext.enforceCallingOrSelfPermission(
6647 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6648 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006649 }
6650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006652 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 }
6654 }
6655 }
6656
6657 boolean clearPackagePreferredActivitiesLP(String packageName) {
6658 boolean changed = false;
6659 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6660 while (it.hasNext()) {
6661 PreferredActivity pa = it.next();
6662 if (pa.mActivity.getPackageName().equals(packageName)) {
6663 it.remove();
6664 changed = true;
6665 }
6666 }
6667 return changed;
6668 }
6669
6670 public int getPreferredActivities(List<IntentFilter> outFilters,
6671 List<ComponentName> outActivities, String packageName) {
6672
6673 int num = 0;
6674 synchronized (mPackages) {
6675 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6676 while (it.hasNext()) {
6677 PreferredActivity pa = it.next();
6678 if (packageName == null
6679 || pa.mActivity.getPackageName().equals(packageName)) {
6680 if (outFilters != null) {
6681 outFilters.add(new IntentFilter(pa));
6682 }
6683 if (outActivities != null) {
6684 outActivities.add(pa.mActivity);
6685 }
6686 }
6687 }
6688 }
6689
6690 return num;
6691 }
6692
6693 public void setApplicationEnabledSetting(String appPackageName,
6694 int newState, int flags) {
6695 setEnabledSetting(appPackageName, null, newState, flags);
6696 }
6697
6698 public void setComponentEnabledSetting(ComponentName componentName,
6699 int newState, int flags) {
6700 setEnabledSetting(componentName.getPackageName(),
6701 componentName.getClassName(), newState, flags);
6702 }
6703
6704 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006705 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6707 || newState == COMPONENT_ENABLED_STATE_ENABLED
6708 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6709 throw new IllegalArgumentException("Invalid new component state: "
6710 + newState);
6711 }
6712 PackageSetting pkgSetting;
6713 final int uid = Binder.getCallingUid();
6714 final int permission = mContext.checkCallingPermission(
6715 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6716 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006717 boolean sendNow = false;
6718 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006719 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006721 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006723 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006725 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006726 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006727 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 }
6729 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006730 "Unknown component: " + packageName
6731 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 }
6733 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6734 throw new SecurityException(
6735 "Permission Denial: attempt to change component state from pid="
6736 + Binder.getCallingPid()
6737 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6738 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006739 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006740 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006741 if (pkgSetting.enabled == newState) {
6742 // Nothing to do
6743 return;
6744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006745 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006746 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006747 } else {
6748 // We're dealing with a component level state change
6749 switch (newState) {
6750 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006751 if (!pkgSetting.enableComponentLP(className)) {
6752 return;
6753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006754 break;
6755 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006756 if (!pkgSetting.disableComponentLP(className)) {
6757 return;
6758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 break;
6760 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006761 if (!pkgSetting.restoreComponentLP(className)) {
6762 return;
6763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 break;
6765 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006766 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006767 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 }
6769 }
6770 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006771 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006772 components = mPendingBroadcasts.get(packageName);
6773 boolean newPackage = components == null;
6774 if (newPackage) {
6775 components = new ArrayList<String>();
6776 }
6777 if (!components.contains(componentName)) {
6778 components.add(componentName);
6779 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006780 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6781 sendNow = true;
6782 // Purge entry from pending broadcast list if another one exists already
6783 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006784 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006785 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006786 if (newPackage) {
6787 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006788 }
6789 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6790 // Schedule a message
6791 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6792 }
6793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006796 long callingId = Binder.clearCallingIdentity();
6797 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006798 if (sendNow) {
6799 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006800 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 } finally {
6803 Binder.restoreCallingIdentity(callingId);
6804 }
6805 }
6806
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006807 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006808 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6809 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6810 + " components=" + componentNames);
6811 Bundle extras = new Bundle(4);
6812 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6813 String nameList[] = new String[componentNames.size()];
6814 componentNames.toArray(nameList);
6815 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006816 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6817 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006818 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006819 }
6820
Jacek Surazski65e13172009-04-28 15:26:38 +02006821 public String getInstallerPackageName(String packageName) {
6822 synchronized (mPackages) {
6823 PackageSetting pkg = mSettings.mPackages.get(packageName);
6824 if (pkg == null) {
6825 throw new IllegalArgumentException("Unknown package: " + packageName);
6826 }
6827 return pkg.installerPackageName;
6828 }
6829 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006831 public int getApplicationEnabledSetting(String appPackageName) {
6832 synchronized (mPackages) {
6833 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6834 if (pkg == null) {
6835 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6836 }
6837 return pkg.enabled;
6838 }
6839 }
6840
6841 public int getComponentEnabledSetting(ComponentName componentName) {
6842 synchronized (mPackages) {
6843 final String packageNameStr = componentName.getPackageName();
6844 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6845 if (pkg == null) {
6846 throw new IllegalArgumentException("Unknown component: " + componentName);
6847 }
6848 final String classNameStr = componentName.getClassName();
6849 return pkg.currentEnabledStateLP(classNameStr);
6850 }
6851 }
6852
6853 public void enterSafeMode() {
6854 if (!mSystemReady) {
6855 mSafeMode = true;
6856 }
6857 }
6858
6859 public void systemReady() {
6860 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006861
6862 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006863 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006864 mContext.getContentResolver(),
6865 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006866 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006867 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006868 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006870 }
6871
6872 public boolean isSafeMode() {
6873 return mSafeMode;
6874 }
6875
6876 public boolean hasSystemUidErrors() {
6877 return mHasSystemUidErrors;
6878 }
6879
6880 static String arrayToString(int[] array) {
6881 StringBuffer buf = new StringBuffer(128);
6882 buf.append('[');
6883 if (array != null) {
6884 for (int i=0; i<array.length; i++) {
6885 if (i > 0) buf.append(", ");
6886 buf.append(array[i]);
6887 }
6888 }
6889 buf.append(']');
6890 return buf.toString();
6891 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006893 @Override
6894 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6895 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6896 != PackageManager.PERMISSION_GRANTED) {
6897 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6898 + Binder.getCallingPid()
6899 + ", uid=" + Binder.getCallingUid()
6900 + " without permission "
6901 + android.Manifest.permission.DUMP);
6902 return;
6903 }
6904
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006905 boolean dumpStar = true;
6906 boolean dumpLibs = false;
6907 boolean dumpFeatures = false;
6908 boolean dumpResolvers = false;
6909 boolean dumpPermissions = false;
6910 boolean dumpPackages = false;
6911 boolean dumpSharedUsers = false;
6912 boolean dumpMessages = false;
6913 boolean dumpProviders = false;
6914
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006915 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006916 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006917
6918 int opti = 0;
6919 while (opti < args.length) {
6920 String opt = args[opti];
6921 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6922 break;
6923 }
6924 opti++;
6925 if ("-a".equals(opt)) {
6926 // Right now we only know how to print all.
6927 } else if ("-h".equals(opt)) {
6928 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006929 pw.println(" [-h] [-f] [cmd] ...");
6930 pw.println(" -f: print details of intent filters");
6931 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006932 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006933 pw.println(" l[ibraries]: list known shared libraries");
6934 pw.println(" f[ibraries]: list device features");
6935 pw.println(" r[esolvers]: dump intent resolvers");
6936 pw.println(" perm[issions]: dump permissions");
6937 pw.println(" prov[iders]: dump content providers");
6938 pw.println(" p[ackages]: dump installed packages");
6939 pw.println(" s[hared-users]: dump shared user IDs");
6940 pw.println(" m[essages]: print collected runtime messages");
6941 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006942 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006943 } else if ("-f".equals(opt)) {
6944 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006945 } else {
6946 pw.println("Unknown argument: " + opt + "; use -h for help");
6947 }
6948 }
6949
6950 // Is the caller requesting to dump a particular piece of data?
6951 if (opti < args.length) {
6952 String cmd = args[opti];
6953 opti++;
6954 // Is this a package name?
6955 if ("android".equals(cmd) || cmd.contains(".")) {
6956 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006957 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
6958 dumpStar = false;
6959 dumpLibs = true;
6960 } else if ("f".equals(cmd) || "features".equals(cmd)) {
6961 dumpStar = false;
6962 dumpFeatures = true;
6963 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
6964 dumpStar = false;
6965 dumpResolvers = true;
6966 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
6967 dumpStar = false;
6968 dumpPermissions = true;
6969 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
6970 dumpStar = false;
6971 dumpPackages = true;
6972 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
6973 dumpStar = false;
6974 dumpSharedUsers = true;
6975 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
6976 dumpStar = false;
6977 dumpProviders = true;
6978 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
6979 dumpStar = false;
6980 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006981 }
6982 }
6983
6984 boolean printedTitle = false;
6985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006986 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006987 if ((dumpStar || dumpLibs) && packageName == null) {
6988 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006989 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006990 pw.println("Libraries:");
6991 Iterator<String> it = mSharedLibraries.keySet().iterator();
6992 while (it.hasNext()) {
6993 String name = it.next();
6994 pw.print(" ");
6995 pw.print(name);
6996 pw.print(" -> ");
6997 pw.println(mSharedLibraries.get(name));
6998 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006999 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007000
7001 if ((dumpStar || dumpFeatures) && packageName == null) {
7002 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007003 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007004 pw.println("Features:");
7005 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7006 while (it.hasNext()) {
7007 String name = it.next();
7008 pw.print(" ");
7009 pw.println(name);
7010 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007011 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007012
7013 if (dumpStar || dumpResolvers) {
7014 if (mActivities.dump(pw, printedTitle
7015 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7016 " ", packageName, showFilters)) {
7017 printedTitle = true;
7018 }
7019 if (mReceivers.dump(pw, printedTitle
7020 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7021 " ", packageName, showFilters)) {
7022 printedTitle = true;
7023 }
7024 if (mServices.dump(pw, printedTitle
7025 ? "\nService Resolver Table:" : "Service Resolver Table:",
7026 " ", packageName, showFilters)) {
7027 printedTitle = true;
7028 }
7029 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7030 ? "\nPreferred Activities:" : "Preferred Activities:",
7031 " ", packageName, showFilters)) {
7032 printedTitle = true;
7033 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007034 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007035
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007036 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007037 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007038 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007039 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7040 continue;
7041 }
7042 if (!printedSomething) {
7043 if (printedTitle) pw.println(" ");
7044 pw.println("Permissions:");
7045 printedSomething = true;
7046 printedTitle = true;
7047 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007048 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7049 pw.print(Integer.toHexString(System.identityHashCode(p)));
7050 pw.println("):");
7051 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7052 pw.print(" uid="); pw.print(p.uid);
7053 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007054 pw.print(" type="); pw.print(p.type);
7055 pw.print(" prot="); pw.println(p.protectionLevel);
7056 if (p.packageSetting != null) {
7057 pw.print(" packageSetting="); pw.println(p.packageSetting);
7058 }
7059 if (p.perm != null) {
7060 pw.print(" perm="); pw.println(p.perm);
7061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 }
7063 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007064
7065 if (dumpStar || dumpProviders) {
7066 printedSomething = false;
7067 for (PackageParser.Provider p : mProviders.values()) {
7068 if (packageName != null && !packageName.equals(p.info.packageName)) {
7069 continue;
7070 }
7071 if (!printedSomething) {
7072 if (printedTitle) pw.println(" ");
7073 pw.println("Registered ContentProviders:");
7074 printedSomething = true;
7075 printedTitle = true;
7076 }
7077 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7078 pw.println(p.toString());
7079 }
7080 }
7081
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007082 printedSomething = false;
7083 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007084 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007085 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7086 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007087 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007088 if (packageName != null && !packageName.equals(ps.realName)
7089 && !packageName.equals(ps.name)) {
7090 continue;
7091 }
7092 if (!printedSomething) {
7093 if (printedTitle) pw.println(" ");
7094 pw.println("Packages:");
7095 printedSomething = true;
7096 printedTitle = true;
7097 }
7098 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007099 pw.print(" Package [");
7100 pw.print(ps.realName != null ? ps.realName : ps.name);
7101 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007102 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7103 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007104 if (ps.realName != null) {
7105 pw.print(" compat name="); pw.println(ps.name);
7106 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007107 pw.print(" userId="); pw.print(ps.userId);
7108 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7109 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7110 pw.print(" pkg="); pw.println(ps.pkg);
7111 pw.print(" codePath="); pw.println(ps.codePathString);
7112 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007113 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007114 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007115 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007116 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007117 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007118 if (ps.pkg.mOperationPending) {
7119 pw.println(" mOperationPending=true");
7120 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007121 pw.print(" supportsScreens=[");
7122 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007123 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007124 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7125 if (!first) pw.print(", ");
7126 first = false;
7127 pw.print("small");
7128 }
7129 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007130 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007131 if (!first) pw.print(", ");
7132 first = false;
7133 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007134 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007135 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007136 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007137 if (!first) pw.print(", ");
7138 first = false;
7139 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007140 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007141 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007142 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007143 if (!first) pw.print(", ");
7144 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007145 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007146 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007147 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007148 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007149 if (!first) pw.print(", ");
7150 first = false;
7151 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007152 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007153 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007154 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7155 if (!first) pw.print(", ");
7156 first = false;
7157 pw.print("anyDensity");
7158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007159 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007160 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007161 pw.print(" timeStamp=");
7162 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7163 pw.print(" firstInstallTime=");
7164 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7165 pw.print(" lastUpdateTime=");
7166 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007167 pw.print(" signatures="); pw.println(ps.signatures);
7168 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007169 pw.print(" haveGids="); pw.println(ps.haveGids);
7170 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007171 pw.print(" installStatus="); pw.print(ps.installStatus);
7172 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 if (ps.disabledComponents.size() > 0) {
7174 pw.println(" disabledComponents:");
7175 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007176 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 }
7178 }
7179 if (ps.enabledComponents.size() > 0) {
7180 pw.println(" enabledComponents:");
7181 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007182 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 }
7184 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007185 if (ps.grantedPermissions.size() > 0) {
7186 pw.println(" grantedPermissions:");
7187 for (String s : ps.grantedPermissions) {
7188 pw.print(" "); pw.println(s);
7189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007191 }
7192 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007193 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007194 if (dumpStar || dumpPackages) {
7195 if (mSettings.mRenamedPackages.size() > 0) {
7196 for (HashMap.Entry<String, String> e
7197 : mSettings.mRenamedPackages.entrySet()) {
7198 if (packageName != null && !packageName.equals(e.getKey())
7199 && !packageName.equals(e.getValue())) {
7200 continue;
7201 }
7202 if (!printedSomething) {
7203 if (printedTitle) pw.println(" ");
7204 pw.println("Renamed packages:");
7205 printedSomething = true;
7206 printedTitle = true;
7207 }
7208 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7209 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007210 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007211 }
7212 printedSomething = false;
7213 if (mSettings.mDisabledSysPackages.size() > 0) {
7214 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7215 if (packageName != null && !packageName.equals(ps.realName)
7216 && !packageName.equals(ps.name)) {
7217 continue;
7218 }
7219 if (!printedSomething) {
7220 if (printedTitle) pw.println(" ");
7221 pw.println("Hidden system packages:");
7222 printedSomething = true;
7223 printedTitle = true;
7224 }
7225 pw.print(" Package [");
7226 pw.print(ps.realName != null ? ps.realName : ps.name);
7227 pw.print("] (");
7228 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7229 pw.println("):");
7230 if (ps.realName != null) {
7231 pw.print(" compat name="); pw.println(ps.name);
7232 }
7233 pw.print(" userId="); pw.println(ps.userId);
7234 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7235 pw.print(" codePath="); pw.println(ps.codePathString);
7236 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007237 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007238 }
7239 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007240 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007241 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007242 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007243 if (packageName != null && su != packageSharedUser) {
7244 continue;
7245 }
7246 if (!printedSomething) {
7247 if (printedTitle) pw.println(" ");
7248 pw.println("Shared users:");
7249 printedSomething = true;
7250 printedTitle = true;
7251 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007252 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7253 pw.print(Integer.toHexString(System.identityHashCode(su)));
7254 pw.println("):");
7255 pw.print(" userId="); pw.print(su.userId);
7256 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007257 pw.println(" grantedPermissions:");
7258 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007259 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007261 }
7262 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007263
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007264 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007265 if (printedTitle) pw.println(" ");
7266 printedTitle = true;
7267 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007268 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007269
7270 pw.println(" ");
7271 pw.println("Package warning messages:");
7272 File fname = getSettingsProblemFile();
7273 FileInputStream in;
7274 try {
7275 in = new FileInputStream(fname);
7276 int avail = in.available();
7277 byte[] data = new byte[avail];
7278 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007279 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007280 } catch (FileNotFoundException e) {
7281 } catch (IOException e) {
7282 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007283 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007284 }
7285 }
7286
7287 static final class BasePermission {
7288 final static int TYPE_NORMAL = 0;
7289 final static int TYPE_BUILTIN = 1;
7290 final static int TYPE_DYNAMIC = 2;
7291
7292 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007293 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007294 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007296 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007297 PackageParser.Permission perm;
7298 PermissionInfo pendingInfo;
7299 int uid;
7300 int[] gids;
7301
7302 BasePermission(String _name, String _sourcePackage, int _type) {
7303 name = _name;
7304 sourcePackage = _sourcePackage;
7305 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007306 // Default to most conservative protection level.
7307 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7308 }
7309
7310 public String toString() {
7311 return "BasePermission{"
7312 + Integer.toHexString(System.identityHashCode(this))
7313 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007314 }
7315 }
7316
7317 static class PackageSignatures {
7318 private Signature[] mSignatures;
7319
7320 PackageSignatures(Signature[] sigs) {
7321 assignSignatures(sigs);
7322 }
7323
7324 PackageSignatures() {
7325 }
7326
7327 void writeXml(XmlSerializer serializer, String tagName,
7328 ArrayList<Signature> pastSignatures) throws IOException {
7329 if (mSignatures == null) {
7330 return;
7331 }
7332 serializer.startTag(null, tagName);
7333 serializer.attribute(null, "count",
7334 Integer.toString(mSignatures.length));
7335 for (int i=0; i<mSignatures.length; i++) {
7336 serializer.startTag(null, "cert");
7337 final Signature sig = mSignatures[i];
7338 final int sigHash = sig.hashCode();
7339 final int numPast = pastSignatures.size();
7340 int j;
7341 for (j=0; j<numPast; j++) {
7342 Signature pastSig = pastSignatures.get(j);
7343 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7344 serializer.attribute(null, "index", Integer.toString(j));
7345 break;
7346 }
7347 }
7348 if (j >= numPast) {
7349 pastSignatures.add(sig);
7350 serializer.attribute(null, "index", Integer.toString(numPast));
7351 serializer.attribute(null, "key", sig.toCharsString());
7352 }
7353 serializer.endTag(null, "cert");
7354 }
7355 serializer.endTag(null, tagName);
7356 }
7357
7358 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7359 throws IOException, XmlPullParserException {
7360 String countStr = parser.getAttributeValue(null, "count");
7361 if (countStr == null) {
7362 reportSettingsProblem(Log.WARN,
7363 "Error in package manager settings: <signatures> has"
7364 + " no count at " + parser.getPositionDescription());
7365 XmlUtils.skipCurrentTag(parser);
7366 }
7367 final int count = Integer.parseInt(countStr);
7368 mSignatures = new Signature[count];
7369 int pos = 0;
7370
7371 int outerDepth = parser.getDepth();
7372 int type;
7373 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7374 && (type != XmlPullParser.END_TAG
7375 || parser.getDepth() > outerDepth)) {
7376 if (type == XmlPullParser.END_TAG
7377 || type == XmlPullParser.TEXT) {
7378 continue;
7379 }
7380
7381 String tagName = parser.getName();
7382 if (tagName.equals("cert")) {
7383 if (pos < count) {
7384 String index = parser.getAttributeValue(null, "index");
7385 if (index != null) {
7386 try {
7387 int idx = Integer.parseInt(index);
7388 String key = parser.getAttributeValue(null, "key");
7389 if (key == null) {
7390 if (idx >= 0 && idx < pastSignatures.size()) {
7391 Signature sig = pastSignatures.get(idx);
7392 if (sig != null) {
7393 mSignatures[pos] = pastSignatures.get(idx);
7394 pos++;
7395 } else {
7396 reportSettingsProblem(Log.WARN,
7397 "Error in package manager settings: <cert> "
7398 + "index " + index + " is not defined at "
7399 + parser.getPositionDescription());
7400 }
7401 } else {
7402 reportSettingsProblem(Log.WARN,
7403 "Error in package manager settings: <cert> "
7404 + "index " + index + " is out of bounds at "
7405 + parser.getPositionDescription());
7406 }
7407 } else {
7408 while (pastSignatures.size() <= idx) {
7409 pastSignatures.add(null);
7410 }
7411 Signature sig = new Signature(key);
7412 pastSignatures.set(idx, sig);
7413 mSignatures[pos] = sig;
7414 pos++;
7415 }
7416 } catch (NumberFormatException e) {
7417 reportSettingsProblem(Log.WARN,
7418 "Error in package manager settings: <cert> "
7419 + "index " + index + " is not a number at "
7420 + parser.getPositionDescription());
7421 }
7422 } else {
7423 reportSettingsProblem(Log.WARN,
7424 "Error in package manager settings: <cert> has"
7425 + " no index at " + parser.getPositionDescription());
7426 }
7427 } else {
7428 reportSettingsProblem(Log.WARN,
7429 "Error in package manager settings: too "
7430 + "many <cert> tags, expected " + count
7431 + " at " + parser.getPositionDescription());
7432 }
7433 } else {
7434 reportSettingsProblem(Log.WARN,
7435 "Unknown element under <cert>: "
7436 + parser.getName());
7437 }
7438 XmlUtils.skipCurrentTag(parser);
7439 }
7440
7441 if (pos < count) {
7442 // Should never happen -- there is an error in the written
7443 // settings -- but if it does we don't want to generate
7444 // a bad array.
7445 Signature[] newSigs = new Signature[pos];
7446 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7447 mSignatures = newSigs;
7448 }
7449 }
7450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007451 private void assignSignatures(Signature[] sigs) {
7452 if (sigs == null) {
7453 mSignatures = null;
7454 return;
7455 }
7456 mSignatures = new Signature[sigs.length];
7457 for (int i=0; i<sigs.length; i++) {
7458 mSignatures[i] = sigs[i];
7459 }
7460 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007462 @Override
7463 public String toString() {
7464 StringBuffer buf = new StringBuffer(128);
7465 buf.append("PackageSignatures{");
7466 buf.append(Integer.toHexString(System.identityHashCode(this)));
7467 buf.append(" [");
7468 if (mSignatures != null) {
7469 for (int i=0; i<mSignatures.length; i++) {
7470 if (i > 0) buf.append(", ");
7471 buf.append(Integer.toHexString(
7472 System.identityHashCode(mSignatures[i])));
7473 }
7474 }
7475 buf.append("]}");
7476 return buf.toString();
7477 }
7478 }
7479
7480 static class PreferredActivity extends IntentFilter {
7481 final int mMatch;
7482 final String[] mSetPackages;
7483 final String[] mSetClasses;
7484 final String[] mSetComponents;
7485 final ComponentName mActivity;
7486 final String mShortActivity;
7487 String mParseError;
7488
7489 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7490 ComponentName activity) {
7491 super(filter);
7492 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7493 mActivity = activity;
7494 mShortActivity = activity.flattenToShortString();
7495 mParseError = null;
7496 if (set != null) {
7497 final int N = set.length;
7498 String[] myPackages = new String[N];
7499 String[] myClasses = new String[N];
7500 String[] myComponents = new String[N];
7501 for (int i=0; i<N; i++) {
7502 ComponentName cn = set[i];
7503 if (cn == null) {
7504 mSetPackages = null;
7505 mSetClasses = null;
7506 mSetComponents = null;
7507 return;
7508 }
7509 myPackages[i] = cn.getPackageName().intern();
7510 myClasses[i] = cn.getClassName().intern();
7511 myComponents[i] = cn.flattenToShortString().intern();
7512 }
7513 mSetPackages = myPackages;
7514 mSetClasses = myClasses;
7515 mSetComponents = myComponents;
7516 } else {
7517 mSetPackages = null;
7518 mSetClasses = null;
7519 mSetComponents = null;
7520 }
7521 }
7522
7523 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7524 IOException {
7525 mShortActivity = parser.getAttributeValue(null, "name");
7526 mActivity = ComponentName.unflattenFromString(mShortActivity);
7527 if (mActivity == null) {
7528 mParseError = "Bad activity name " + mShortActivity;
7529 }
7530 String matchStr = parser.getAttributeValue(null, "match");
7531 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7532 String setCountStr = parser.getAttributeValue(null, "set");
7533 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7534
7535 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7536 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7537 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7538
7539 int setPos = 0;
7540
7541 int outerDepth = parser.getDepth();
7542 int type;
7543 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7544 && (type != XmlPullParser.END_TAG
7545 || parser.getDepth() > outerDepth)) {
7546 if (type == XmlPullParser.END_TAG
7547 || type == XmlPullParser.TEXT) {
7548 continue;
7549 }
7550
7551 String tagName = parser.getName();
7552 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7553 // + parser.getDepth() + " tag=" + tagName);
7554 if (tagName.equals("set")) {
7555 String name = parser.getAttributeValue(null, "name");
7556 if (name == null) {
7557 if (mParseError == null) {
7558 mParseError = "No name in set tag in preferred activity "
7559 + mShortActivity;
7560 }
7561 } else if (setPos >= setCount) {
7562 if (mParseError == null) {
7563 mParseError = "Too many set tags in preferred activity "
7564 + mShortActivity;
7565 }
7566 } else {
7567 ComponentName cn = ComponentName.unflattenFromString(name);
7568 if (cn == null) {
7569 if (mParseError == null) {
7570 mParseError = "Bad set name " + name + " in preferred activity "
7571 + mShortActivity;
7572 }
7573 } else {
7574 myPackages[setPos] = cn.getPackageName();
7575 myClasses[setPos] = cn.getClassName();
7576 myComponents[setPos] = name;
7577 setPos++;
7578 }
7579 }
7580 XmlUtils.skipCurrentTag(parser);
7581 } else if (tagName.equals("filter")) {
7582 //Log.i(TAG, "Starting to parse filter...");
7583 readFromXml(parser);
7584 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7585 // + parser.getDepth() + " tag=" + parser.getName());
7586 } else {
7587 reportSettingsProblem(Log.WARN,
7588 "Unknown element under <preferred-activities>: "
7589 + parser.getName());
7590 XmlUtils.skipCurrentTag(parser);
7591 }
7592 }
7593
7594 if (setPos != setCount) {
7595 if (mParseError == null) {
7596 mParseError = "Not enough set tags (expected " + setCount
7597 + " but found " + setPos + ") in " + mShortActivity;
7598 }
7599 }
7600
7601 mSetPackages = myPackages;
7602 mSetClasses = myClasses;
7603 mSetComponents = myComponents;
7604 }
7605
7606 public void writeToXml(XmlSerializer serializer) throws IOException {
7607 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7608 serializer.attribute(null, "name", mShortActivity);
7609 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7610 serializer.attribute(null, "set", Integer.toString(NS));
7611 for (int s=0; s<NS; s++) {
7612 serializer.startTag(null, "set");
7613 serializer.attribute(null, "name", mSetComponents[s]);
7614 serializer.endTag(null, "set");
7615 }
7616 serializer.startTag(null, "filter");
7617 super.writeToXml(serializer);
7618 serializer.endTag(null, "filter");
7619 }
7620
7621 boolean sameSet(List<ResolveInfo> query, int priority) {
7622 if (mSetPackages == null) return false;
7623 final int NQ = query.size();
7624 final int NS = mSetPackages.length;
7625 int numMatch = 0;
7626 for (int i=0; i<NQ; i++) {
7627 ResolveInfo ri = query.get(i);
7628 if (ri.priority != priority) continue;
7629 ActivityInfo ai = ri.activityInfo;
7630 boolean good = false;
7631 for (int j=0; j<NS; j++) {
7632 if (mSetPackages[j].equals(ai.packageName)
7633 && mSetClasses[j].equals(ai.name)) {
7634 numMatch++;
7635 good = true;
7636 break;
7637 }
7638 }
7639 if (!good) return false;
7640 }
7641 return numMatch == NS;
7642 }
7643 }
7644
7645 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007646 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007648 HashSet<String> grantedPermissions = new HashSet<String>();
7649 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007651 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007652 setFlags(pkgFlags);
7653 }
7654
7655 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007656 this.pkgFlags = pkgFlags & (
7657 ApplicationInfo.FLAG_SYSTEM |
7658 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007659 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007660 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 }
7662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007664 /**
7665 * Settings base class for pending and resolved classes.
7666 */
7667 static class PackageSettingBase extends GrantedPermissions {
7668 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007669 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007670 File codePath;
7671 String codePathString;
7672 File resourcePath;
7673 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007674 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007675 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007676 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007677 long firstInstallTime;
7678 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007679 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007680
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007681 boolean uidError;
7682
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007683 PackageSignatures signatures = new PackageSignatures();
7684
7685 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007686 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 /* Explicitly disabled components */
7689 HashSet<String> disabledComponents = new HashSet<String>(0);
7690 /* Explicitly enabled components */
7691 HashSet<String> enabledComponents = new HashSet<String>(0);
7692 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7693 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007694
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007695 PackageSettingBase origPackage;
7696
Jacek Surazski65e13172009-04-28 15:26:38 +02007697 /* package name of the app that installed this package */
7698 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007699
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007700 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007701 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 super(pkgFlags);
7703 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007704 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007705 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007706 }
7707
Kenny Root806cc132010-09-12 08:34:19 -07007708 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7709 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007710 this.codePath = codePath;
7711 this.codePathString = codePath.toString();
7712 this.resourcePath = resourcePath;
7713 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007714 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007715 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 }
Kenny Root85387d72010-08-26 10:13:11 -07007717
Jacek Surazski65e13172009-04-28 15:26:38 +02007718 public void setInstallerPackageName(String packageName) {
7719 installerPackageName = packageName;
7720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007721
Jacek Surazski65e13172009-04-28 15:26:38 +02007722 String getInstallerPackageName() {
7723 return installerPackageName;
7724 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 public void setInstallStatus(int newStatus) {
7727 installStatus = newStatus;
7728 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 public int getInstallStatus() {
7731 return installStatus;
7732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007735 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 }
7737
7738 public void copyFrom(PackageSettingBase base) {
7739 grantedPermissions = base.grantedPermissions;
7740 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007743 firstInstallTime = base.firstInstallTime;
7744 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007745 signatures = base.signatures;
7746 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007747 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 disabledComponents = base.disabledComponents;
7749 enabledComponents = base.enabledComponents;
7750 enabled = base.enabled;
7751 installStatus = base.installStatus;
7752 }
7753
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007754 boolean enableComponentLP(String componentClassName) {
7755 boolean changed = disabledComponents.remove(componentClassName);
7756 changed |= enabledComponents.add(componentClassName);
7757 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007758 }
7759
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007760 boolean disableComponentLP(String componentClassName) {
7761 boolean changed = enabledComponents.remove(componentClassName);
7762 changed |= disabledComponents.add(componentClassName);
7763 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 }
7765
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007766 boolean restoreComponentLP(String componentClassName) {
7767 boolean changed = enabledComponents.remove(componentClassName);
7768 changed |= disabledComponents.remove(componentClassName);
7769 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007770 }
7771
7772 int currentEnabledStateLP(String componentName) {
7773 if (enabledComponents.contains(componentName)) {
7774 return COMPONENT_ENABLED_STATE_ENABLED;
7775 } else if (disabledComponents.contains(componentName)) {
7776 return COMPONENT_ENABLED_STATE_DISABLED;
7777 } else {
7778 return COMPONENT_ENABLED_STATE_DEFAULT;
7779 }
7780 }
7781 }
7782
7783 /**
7784 * Settings data for a particular package we know about.
7785 */
7786 static final class PackageSetting extends PackageSettingBase {
7787 int userId;
7788 PackageParser.Package pkg;
7789 SharedUserSetting sharedUser;
7790
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007791 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007792 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7793 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7794 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 @Override
7798 public String toString() {
7799 return "PackageSetting{"
7800 + Integer.toHexString(System.identityHashCode(this))
7801 + " " + name + "/" + userId + "}";
7802 }
7803 }
7804
7805 /**
7806 * Settings data for a particular shared user ID we know about.
7807 */
7808 static final class SharedUserSetting extends GrantedPermissions {
7809 final String name;
7810 int userId;
7811 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7812 final PackageSignatures signatures = new PackageSignatures();
7813
7814 SharedUserSetting(String _name, int _pkgFlags) {
7815 super(_pkgFlags);
7816 name = _name;
7817 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007819 @Override
7820 public String toString() {
7821 return "SharedUserSetting{"
7822 + Integer.toHexString(System.identityHashCode(this))
7823 + " " + name + "/" + userId + "}";
7824 }
7825 }
7826
7827 /**
7828 * Holds information about dynamic settings.
7829 */
7830 private static final class Settings {
7831 private final File mSettingsFilename;
7832 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007833 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 private final HashMap<String, PackageSetting> mPackages =
7835 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 // List of replaced system applications
7837 final HashMap<String, PackageSetting> mDisabledSysPackages =
7838 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007839
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007840 // These are the last platform API version we were using for
7841 // the apps installed on internal and external storage. It is
7842 // used to grant newer permissions one time during a system upgrade.
7843 int mInternalSdkPlatform;
7844 int mExternalSdkPlatform;
7845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007846 // The user's preferred activities associated with particular intent
7847 // filters.
7848 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7849 new IntentResolver<PreferredActivity, PreferredActivity>() {
7850 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007851 protected String packageForFilter(PreferredActivity filter) {
7852 return filter.mActivity.getPackageName();
7853 }
7854 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007855 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007857 out.print(prefix); out.print(
7858 Integer.toHexString(System.identityHashCode(filter)));
7859 out.print(' ');
7860 out.print(filter.mActivity.flattenToShortString());
7861 out.print(" match=0x");
7862 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007863 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007864 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007865 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007866 out.print(prefix); out.print(" ");
7867 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007868 }
7869 }
7870 }
7871 };
7872 private final HashMap<String, SharedUserSetting> mSharedUsers =
7873 new HashMap<String, SharedUserSetting>();
7874 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7875 private final SparseArray<Object> mOtherUserIds =
7876 new SparseArray<Object>();
7877
7878 // For reading/writing settings file.
7879 private final ArrayList<Signature> mPastSignatures =
7880 new ArrayList<Signature>();
7881
7882 // Mapping from permission names to info about them.
7883 final HashMap<String, BasePermission> mPermissions =
7884 new HashMap<String, BasePermission>();
7885
7886 // Mapping from permission tree names to info about them.
7887 final HashMap<String, BasePermission> mPermissionTrees =
7888 new HashMap<String, BasePermission>();
7889
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007890 // Packages that have been uninstalled and still need their external
7891 // storage data deleted.
7892 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7893
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007894 // Packages that have been renamed since they were first installed.
7895 // Keys are the new names of the packages, values are the original
7896 // names. The packages appear everwhere else under their original
7897 // names.
7898 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 private final StringBuilder mReadMessages = new StringBuilder();
7901
7902 private static final class PendingPackage extends PackageSettingBase {
7903 final int sharedId;
7904
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007905 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007906 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7907 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7908 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 this.sharedId = sharedId;
7910 }
7911 }
7912 private final ArrayList<PendingPackage> mPendingPackages
7913 = new ArrayList<PendingPackage>();
7914
7915 Settings() {
7916 File dataDir = Environment.getDataDirectory();
7917 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007918 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7919 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007920 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007921 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007922 FileUtils.setPermissions(systemDir.toString(),
7923 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7924 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7925 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007926 FileUtils.setPermissions(systemSecureDir.toString(),
7927 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7928 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7929 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 mSettingsFilename = new File(systemDir, "packages.xml");
7931 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007932 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 }
7934
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007935 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007936 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007937 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007938 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007939 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007940 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007941 return p;
7942 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007943
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007944 PackageSetting peekPackageLP(String name) {
7945 return mPackages.get(name);
7946 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007947 PackageSetting p = mPackages.get(name);
7948 if (p != null && p.codePath.getPath().equals(codePath)) {
7949 return p;
7950 }
7951 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007952 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007954
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007955 void setInstallStatus(String pkgName, int status) {
7956 PackageSetting p = mPackages.get(pkgName);
7957 if(p != null) {
7958 if(p.getInstallStatus() != status) {
7959 p.setInstallStatus(status);
7960 }
7961 }
7962 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007963
Jacek Surazski65e13172009-04-28 15:26:38 +02007964 void setInstallerPackageName(String pkgName,
7965 String installerPkgName) {
7966 PackageSetting p = mPackages.get(pkgName);
7967 if(p != null) {
7968 p.setInstallerPackageName(installerPkgName);
7969 }
7970 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007971
Jacek Surazski65e13172009-04-28 15:26:38 +02007972 String getInstallerPackageName(String pkgName) {
7973 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007974 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007975 }
7976
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007977 int getInstallStatus(String pkgName) {
7978 PackageSetting p = mPackages.get(pkgName);
7979 if(p != null) {
7980 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007981 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 return -1;
7983 }
7984
7985 SharedUserSetting getSharedUserLP(String name,
7986 int pkgFlags, boolean create) {
7987 SharedUserSetting s = mSharedUsers.get(name);
7988 if (s == null) {
7989 if (!create) {
7990 return null;
7991 }
7992 s = new SharedUserSetting(name, pkgFlags);
7993 if (MULTIPLE_APPLICATION_UIDS) {
7994 s.userId = newUserIdLP(s);
7995 } else {
7996 s.userId = FIRST_APPLICATION_UID;
7997 }
7998 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7999 // < 0 means we couldn't assign a userid; fall out and return
8000 // s, which is currently null
8001 if (s.userId >= 0) {
8002 mSharedUsers.put(name, s);
8003 }
8004 }
8005
8006 return s;
8007 }
8008
8009 int disableSystemPackageLP(String name) {
8010 PackageSetting p = mPackages.get(name);
8011 if(p == null) {
8012 Log.w(TAG, "Package:"+name+" is not an installed package");
8013 return -1;
8014 }
8015 PackageSetting dp = mDisabledSysPackages.get(name);
8016 // always make sure the system package code and resource paths dont change
8017 if(dp == null) {
8018 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8019 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8020 }
8021 mDisabledSysPackages.put(name, p);
8022 }
8023 return removePackageLP(name);
8024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008026 PackageSetting enableSystemPackageLP(String name) {
8027 PackageSetting p = mDisabledSysPackages.get(name);
8028 if(p == null) {
8029 Log.w(TAG, "Package:"+name+" is not disabled");
8030 return null;
8031 }
8032 // Reset flag in ApplicationInfo object
8033 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8034 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8035 }
Kenny Root806cc132010-09-12 08:34:19 -07008036 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8037 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008038 mDisabledSysPackages.remove(name);
8039 return ret;
8040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008041
Kenny Root806cc132010-09-12 08:34:19 -07008042 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8043 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008044 PackageSetting p = mPackages.get(name);
8045 if (p != null) {
8046 if (p.userId == uid) {
8047 return p;
8048 }
8049 reportSettingsProblem(Log.ERROR,
8050 "Adding duplicate package, keeping first: " + name);
8051 return null;
8052 }
Kenny Root806cc132010-09-12 08:34:19 -07008053 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8054 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008055 p.userId = uid;
8056 if (addUserIdLP(uid, p, name)) {
8057 mPackages.put(name, p);
8058 return p;
8059 }
8060 return null;
8061 }
8062
8063 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8064 SharedUserSetting s = mSharedUsers.get(name);
8065 if (s != null) {
8066 if (s.userId == uid) {
8067 return s;
8068 }
8069 reportSettingsProblem(Log.ERROR,
8070 "Adding duplicate shared user, keeping first: " + name);
8071 return null;
8072 }
8073 s = new SharedUserSetting(name, pkgFlags);
8074 s.userId = uid;
8075 if (addUserIdLP(uid, s, name)) {
8076 mSharedUsers.put(name, s);
8077 return s;
8078 }
8079 return null;
8080 }
8081
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008082 // Transfer ownership of permissions from one package to another.
8083 private void transferPermissions(String origPkg, String newPkg) {
8084 // Transfer ownership of permissions to the new package.
8085 for (int i=0; i<2; i++) {
8086 HashMap<String, BasePermission> permissions =
8087 i == 0 ? mPermissionTrees : mPermissions;
8088 for (BasePermission bp : permissions.values()) {
8089 if (origPkg.equals(bp.sourcePackage)) {
8090 if (DEBUG_UPGRADE) Log.v(TAG,
8091 "Moving permission " + bp.name
8092 + " from pkg " + bp.sourcePackage
8093 + " to " + newPkg);
8094 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008095 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008096 bp.perm = null;
8097 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008098 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008099 }
8100 bp.uid = 0;
8101 bp.gids = null;
8102 }
8103 }
8104 }
8105 }
8106
8107 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008108 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008109 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008110 PackageSetting p = mPackages.get(name);
8111 if (p != null) {
8112 if (!p.codePath.equals(codePath)) {
8113 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008114 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008115 // This is an updated system app with versions in both system
8116 // and data partition. Just let the most recent version
8117 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008118 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008119 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008120 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008121 // Just a change in the code path is not an issue, but
8122 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008123 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008124 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008125 /*
8126 * Since we've changed paths, we need to prefer the new
8127 * native library path over the one stored in the
8128 * package settings since we might have moved from
8129 * internal to external storage or vice versa.
8130 */
8131 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008132 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008133 }
8134 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008135 reportSettingsProblem(Log.WARN,
8136 "Package " + name + " shared user changed from "
8137 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8138 + " to "
8139 + (sharedUser != null ? sharedUser.name : "<nothing>")
8140 + "; replacing with new");
8141 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008142 } else {
8143 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8144 // If what we are scanning is a system package, then
8145 // make it so, regardless of whether it was previously
8146 // installed only in the data partition.
8147 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008149 }
8150 }
8151 if (p == null) {
8152 // Create a new PackageSettings entry. this can end up here because
8153 // of code path mismatch or user id mismatch of an updated system partition
8154 if (!create) {
8155 return null;
8156 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008157 if (origPackage != null) {
8158 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008159 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8160 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008161 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8162 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008163 // Note that we will retain the new package's signature so
8164 // that we can keep its data.
8165 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008166 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008167 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008168 p.sharedUser = origPackage.sharedUser;
8169 p.userId = origPackage.userId;
8170 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008171 mRenamedPackages.put(name, origPackage.name);
8172 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008173 // Update new package state.
8174 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008176 p = new PackageSetting(name, realName, codePath, resourcePath,
8177 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008178 p.setTimeStamp(codePath.lastModified());
8179 p.sharedUser = sharedUser;
8180 if (sharedUser != null) {
8181 p.userId = sharedUser.userId;
8182 } else if (MULTIPLE_APPLICATION_UIDS) {
8183 // Clone the setting here for disabled system packages
8184 PackageSetting dis = mDisabledSysPackages.get(name);
8185 if (dis != null) {
8186 // For disabled packages a new setting is created
8187 // from the existing user id. This still has to be
8188 // added to list of user id's
8189 // Copy signatures from previous setting
8190 if (dis.signatures.mSignatures != null) {
8191 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8192 }
8193 p.userId = dis.userId;
8194 // Clone permissions
8195 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008196 // Clone component info
8197 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8198 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8199 // Add new setting to list of user ids
8200 addUserIdLP(p.userId, p, name);
8201 } else {
8202 // Assign new user id
8203 p.userId = newUserIdLP(p);
8204 }
8205 } else {
8206 p.userId = FIRST_APPLICATION_UID;
8207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008208 }
8209 if (p.userId < 0) {
8210 reportSettingsProblem(Log.WARN,
8211 "Package " + name + " could not be assigned a valid uid");
8212 return null;
8213 }
8214 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008215 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008216 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008217 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008218 }
8219 }
8220 return p;
8221 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008222
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008223 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008224 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008225 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008226 final String codePath = pkg.applicationInfo.sourceDir;
8227 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008228 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008229 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008230 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008231 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008232 p.codePath = new File(codePath);
8233 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008234 }
8235 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008236 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008237 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008238 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008239 p.resourcePath = new File(resourcePath);
8240 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008241 }
Kenny Root85387d72010-08-26 10:13:11 -07008242 // Update the native library path if needed
8243 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8244 if (nativeLibraryPath != null
8245 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8246 p.nativeLibraryPathString = nativeLibraryPath;
8247 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008248 // Update version code if needed
8249 if (pkg.mVersionCode != p.versionCode) {
8250 p.versionCode = pkg.mVersionCode;
8251 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008252 // Update signatures if needed.
8253 if (p.signatures.mSignatures == null) {
8254 p.signatures.assignSignatures(pkg.mSignatures);
8255 }
8256 // If this app defines a shared user id initialize
8257 // the shared user signatures as well.
8258 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8259 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8260 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008261 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8262 }
8263
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008264 // Utility method that adds a PackageSetting to mPackages and
8265 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008266 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008267 SharedUserSetting sharedUser) {
8268 mPackages.put(name, p);
8269 if (sharedUser != null) {
8270 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8271 reportSettingsProblem(Log.ERROR,
8272 "Package " + p.name + " was user "
8273 + p.sharedUser + " but is now " + sharedUser
8274 + "; I am not changing its files so it will probably fail!");
8275 p.sharedUser.packages.remove(p);
8276 } else if (p.userId != sharedUser.userId) {
8277 reportSettingsProblem(Log.ERROR,
8278 "Package " + p.name + " was user id " + p.userId
8279 + " but is now user " + sharedUser
8280 + " with id " + sharedUser.userId
8281 + "; I am not changing its files so it will probably fail!");
8282 }
8283
8284 sharedUser.packages.add(p);
8285 p.sharedUser = sharedUser;
8286 p.userId = sharedUser.userId;
8287 }
8288 }
8289
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008290 /*
8291 * Update the shared user setting when a package using
8292 * specifying the shared user id is removed. The gids
8293 * associated with each permission of the deleted package
8294 * are removed from the shared user's gid list only if its
8295 * not in use by other permissions of packages in the
8296 * shared user setting.
8297 */
8298 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008299 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008300 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008301 return;
8302 }
8303 // No sharedUserId
8304 if (deletedPs.sharedUser == null) {
8305 return;
8306 }
8307 SharedUserSetting sus = deletedPs.sharedUser;
8308 // Update permissions
8309 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8310 boolean used = false;
8311 if (!sus.grantedPermissions.contains (eachPerm)) {
8312 continue;
8313 }
8314 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008315 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008316 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008317 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008318 used = true;
8319 break;
8320 }
8321 }
8322 if (!used) {
8323 // can safely delete this permission from list
8324 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 }
8326 }
8327 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008328 int newGids[] = globalGids;
8329 for (String eachPerm : sus.grantedPermissions) {
8330 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008331 if (bp != null) {
8332 newGids = appendInts(newGids, bp.gids);
8333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008334 }
8335 sus.gids = newGids;
8336 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 private int removePackageLP(String name) {
8339 PackageSetting p = mPackages.get(name);
8340 if (p != null) {
8341 mPackages.remove(name);
8342 if (p.sharedUser != null) {
8343 p.sharedUser.packages.remove(p);
8344 if (p.sharedUser.packages.size() == 0) {
8345 mSharedUsers.remove(p.sharedUser.name);
8346 removeUserIdLP(p.sharedUser.userId);
8347 return p.sharedUser.userId;
8348 }
8349 } else {
8350 removeUserIdLP(p.userId);
8351 return p.userId;
8352 }
8353 }
8354 return -1;
8355 }
8356
8357 private boolean addUserIdLP(int uid, Object obj, Object name) {
8358 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8359 return false;
8360 }
8361
8362 if (uid >= FIRST_APPLICATION_UID) {
8363 int N = mUserIds.size();
8364 final int index = uid - FIRST_APPLICATION_UID;
8365 while (index >= N) {
8366 mUserIds.add(null);
8367 N++;
8368 }
8369 if (mUserIds.get(index) != null) {
8370 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008371 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008372 + " name=" + name);
8373 return false;
8374 }
8375 mUserIds.set(index, obj);
8376 } else {
8377 if (mOtherUserIds.get(uid) != null) {
8378 reportSettingsProblem(Log.ERROR,
8379 "Adding duplicate shared id: " + uid
8380 + " name=" + name);
8381 return false;
8382 }
8383 mOtherUserIds.put(uid, obj);
8384 }
8385 return true;
8386 }
8387
8388 public Object getUserIdLP(int uid) {
8389 if (uid >= FIRST_APPLICATION_UID) {
8390 int N = mUserIds.size();
8391 final int index = uid - FIRST_APPLICATION_UID;
8392 return index < N ? mUserIds.get(index) : null;
8393 } else {
8394 return mOtherUserIds.get(uid);
8395 }
8396 }
8397
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008398 private Set<String> findPackagesWithFlag(int flag) {
8399 Set<String> ret = new HashSet<String>();
8400 for (PackageSetting ps : mPackages.values()) {
8401 // Has to match atleast all the flag bits set on flag
8402 if ((ps.pkgFlags & flag) == flag) {
8403 ret.add(ps.name);
8404 }
8405 }
8406 return ret;
8407 }
8408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 private void removeUserIdLP(int uid) {
8410 if (uid >= FIRST_APPLICATION_UID) {
8411 int N = mUserIds.size();
8412 final int index = uid - FIRST_APPLICATION_UID;
8413 if (index < N) mUserIds.set(index, null);
8414 } else {
8415 mOtherUserIds.remove(uid);
8416 }
8417 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008419 void writeLP() {
8420 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8421
8422 // Keep the old settings around until we know the new ones have
8423 // been successfully written.
8424 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008425 // Presence of backup settings file indicates that we failed
8426 // to persist settings earlier. So preserve the older
8427 // backup for future reference since the current settings
8428 // might have been corrupted.
8429 if (!mBackupSettingsFilename.exists()) {
8430 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008431 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008432 return;
8433 }
8434 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008435 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008436 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008438 }
8439
8440 mPastSignatures.clear();
8441
8442 try {
Kenny Root9f306d72010-09-26 11:19:47 -07008443 BufferedOutputStream str = new BufferedOutputStream(new FileOutputStream(
8444 mSettingsFilename));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008445
8446 //XmlSerializer serializer = XmlUtils.serializerInstance();
8447 XmlSerializer serializer = new FastXmlSerializer();
8448 serializer.setOutput(str, "utf-8");
8449 serializer.startDocument(null, true);
8450 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8451
8452 serializer.startTag(null, "packages");
8453
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008454 serializer.startTag(null, "last-platform-version");
8455 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8456 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8457 serializer.endTag(null, "last-platform-version");
8458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459 serializer.startTag(null, "permission-trees");
8460 for (BasePermission bp : mPermissionTrees.values()) {
8461 writePermission(serializer, bp);
8462 }
8463 serializer.endTag(null, "permission-trees");
8464
8465 serializer.startTag(null, "permissions");
8466 for (BasePermission bp : mPermissions.values()) {
8467 writePermission(serializer, bp);
8468 }
8469 serializer.endTag(null, "permissions");
8470
8471 for (PackageSetting pkg : mPackages.values()) {
8472 writePackage(serializer, pkg);
8473 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8476 writeDisabledSysPackage(serializer, pkg);
8477 }
8478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008479 serializer.startTag(null, "preferred-activities");
8480 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8481 serializer.startTag(null, "item");
8482 pa.writeToXml(serializer);
8483 serializer.endTag(null, "item");
8484 }
8485 serializer.endTag(null, "preferred-activities");
8486
8487 for (SharedUserSetting usr : mSharedUsers.values()) {
8488 serializer.startTag(null, "shared-user");
8489 serializer.attribute(null, "name", usr.name);
8490 serializer.attribute(null, "userId",
8491 Integer.toString(usr.userId));
8492 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8493 serializer.startTag(null, "perms");
8494 for (String name : usr.grantedPermissions) {
8495 serializer.startTag(null, "item");
8496 serializer.attribute(null, "name", name);
8497 serializer.endTag(null, "item");
8498 }
8499 serializer.endTag(null, "perms");
8500 serializer.endTag(null, "shared-user");
8501 }
8502
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008503 if (mPackagesToBeCleaned.size() > 0) {
8504 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8505 serializer.startTag(null, "cleaning-package");
8506 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8507 serializer.endTag(null, "cleaning-package");
8508 }
8509 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008510
8511 if (mRenamedPackages.size() > 0) {
8512 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8513 serializer.startTag(null, "renamed-package");
8514 serializer.attribute(null, "new", e.getKey());
8515 serializer.attribute(null, "old", e.getValue());
8516 serializer.endTag(null, "renamed-package");
8517 }
8518 }
8519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008520 serializer.endTag(null, "packages");
8521
8522 serializer.endDocument();
8523
8524 str.flush();
8525 str.close();
8526
8527 // New settings successfully written, old ones are no longer
8528 // needed.
8529 mBackupSettingsFilename.delete();
8530 FileUtils.setPermissions(mSettingsFilename.toString(),
8531 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8532 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8533 |FileUtils.S_IROTH,
8534 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008535
8536 // Write package list file now, use a JournaledFile.
8537 //
8538 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8539 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8540
Kenny Root9f306d72010-09-26 11:19:47 -07008541 str = new BufferedOutputStream(new FileOutputStream(journal.chooseForWrite()));
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008542 try {
8543 StringBuilder sb = new StringBuilder();
8544 for (PackageSetting pkg : mPackages.values()) {
8545 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008546 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008547 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8548
8549 // Avoid any application that has a space in its path
8550 // or that is handled by the system.
8551 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8552 continue;
8553
8554 // we store on each line the following information for now:
8555 //
8556 // pkgName - package name
8557 // userId - application-specific user id
8558 // debugFlag - 0 or 1 if the package is debuggable.
8559 // dataPath - path to package's data path
8560 //
8561 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8562 //
8563 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8564 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8565 // system/core/run-as/run-as.c
8566 //
8567 sb.setLength(0);
8568 sb.append(ai.packageName);
8569 sb.append(" ");
8570 sb.append((int)ai.uid);
8571 sb.append(isDebug ? " 1 " : " 0 ");
8572 sb.append(dataPath);
8573 sb.append("\n");
8574 str.write(sb.toString().getBytes());
8575 }
8576 str.flush();
8577 str.close();
8578 journal.commit();
8579 }
8580 catch (Exception e) {
8581 journal.rollback();
8582 }
8583
8584 FileUtils.setPermissions(mPackageListFilename.toString(),
8585 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8586 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8587 |FileUtils.S_IROTH,
8588 -1, -1);
8589
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008590 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008591
8592 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008593 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 -08008594 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008595 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 -08008596 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008597 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008598 if (mSettingsFilename.exists()) {
8599 if (!mSettingsFilename.delete()) {
8600 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8601 }
8602 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008603 //Debug.stopMethodTracing();
8604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008605
8606 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008607 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008608 serializer.startTag(null, "updated-package");
8609 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008610 if (pkg.realName != null) {
8611 serializer.attribute(null, "realName", pkg.realName);
8612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008614 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8615 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8616 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008617 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008618 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8619 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8620 }
Kenny Root85387d72010-08-26 10:13:11 -07008621 if (pkg.nativeLibraryPathString != null) {
8622 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624 if (pkg.sharedUser == null) {
8625 serializer.attribute(null, "userId",
8626 Integer.toString(pkg.userId));
8627 } else {
8628 serializer.attribute(null, "sharedUserId",
8629 Integer.toString(pkg.userId));
8630 }
8631 serializer.startTag(null, "perms");
8632 if (pkg.sharedUser == null) {
8633 // If this is a shared user, the permissions will
8634 // be written there. We still need to write an
8635 // empty permissions list so permissionsFixed will
8636 // be set.
8637 for (final String name : pkg.grantedPermissions) {
8638 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008639 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 // We only need to write signature or system permissions but this wont
8641 // match the semantics of grantedPermissions. So write all permissions.
8642 serializer.startTag(null, "item");
8643 serializer.attribute(null, "name", name);
8644 serializer.endTag(null, "item");
8645 }
8646 }
8647 }
8648 serializer.endTag(null, "perms");
8649 serializer.endTag(null, "updated-package");
8650 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008651
8652 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008653 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654 serializer.startTag(null, "package");
8655 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008656 if (pkg.realName != null) {
8657 serializer.attribute(null, "realName", pkg.realName);
8658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008659 serializer.attribute(null, "codePath", pkg.codePathString);
8660 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8661 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8662 }
Kenny Root85387d72010-08-26 10:13:11 -07008663 if (pkg.nativeLibraryPathString != null) {
8664 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8665 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008666 serializer.attribute(null, "flags",
8667 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008668 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8669 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8670 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008671 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008672 if (pkg.sharedUser == null) {
8673 serializer.attribute(null, "userId",
8674 Integer.toString(pkg.userId));
8675 } else {
8676 serializer.attribute(null, "sharedUserId",
8677 Integer.toString(pkg.userId));
8678 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008679 if (pkg.uidError) {
8680 serializer.attribute(null, "uidError", "true");
8681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008682 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8683 serializer.attribute(null, "enabled",
8684 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8685 ? "true" : "false");
8686 }
8687 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8688 serializer.attribute(null, "installStatus", "false");
8689 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008690 if (pkg.installerPackageName != null) {
8691 serializer.attribute(null, "installer", pkg.installerPackageName);
8692 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008693 if (pkg.obbPathString != null) {
8694 serializer.attribute(null, "obbPath", pkg.obbPathString);
8695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8697 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8698 serializer.startTag(null, "perms");
8699 if (pkg.sharedUser == null) {
8700 // If this is a shared user, the permissions will
8701 // be written there. We still need to write an
8702 // empty permissions list so permissionsFixed will
8703 // be set.
8704 for (final String name : pkg.grantedPermissions) {
8705 serializer.startTag(null, "item");
8706 serializer.attribute(null, "name", name);
8707 serializer.endTag(null, "item");
8708 }
8709 }
8710 serializer.endTag(null, "perms");
8711 }
8712 if (pkg.disabledComponents.size() > 0) {
8713 serializer.startTag(null, "disabled-components");
8714 for (final String name : pkg.disabledComponents) {
8715 serializer.startTag(null, "item");
8716 serializer.attribute(null, "name", name);
8717 serializer.endTag(null, "item");
8718 }
8719 serializer.endTag(null, "disabled-components");
8720 }
8721 if (pkg.enabledComponents.size() > 0) {
8722 serializer.startTag(null, "enabled-components");
8723 for (final String name : pkg.enabledComponents) {
8724 serializer.startTag(null, "item");
8725 serializer.attribute(null, "name", name);
8726 serializer.endTag(null, "item");
8727 }
8728 serializer.endTag(null, "enabled-components");
8729 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008731 serializer.endTag(null, "package");
8732 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008733
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008734 void writePermission(XmlSerializer serializer, BasePermission bp)
8735 throws XmlPullParserException, java.io.IOException {
8736 if (bp.type != BasePermission.TYPE_BUILTIN
8737 && bp.sourcePackage != null) {
8738 serializer.startTag(null, "item");
8739 serializer.attribute(null, "name", bp.name);
8740 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008741 if (bp.protectionLevel !=
8742 PermissionInfo.PROTECTION_NORMAL) {
8743 serializer.attribute(null, "protection",
8744 Integer.toString(bp.protectionLevel));
8745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008746 if (DEBUG_SETTINGS) Log.v(TAG,
8747 "Writing perm: name=" + bp.name + " type=" + bp.type);
8748 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8749 PermissionInfo pi = bp.perm != null ? bp.perm.info
8750 : bp.pendingInfo;
8751 if (pi != null) {
8752 serializer.attribute(null, "type", "dynamic");
8753 if (pi.icon != 0) {
8754 serializer.attribute(null, "icon",
8755 Integer.toString(pi.icon));
8756 }
8757 if (pi.nonLocalizedLabel != null) {
8758 serializer.attribute(null, "label",
8759 pi.nonLocalizedLabel.toString());
8760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 }
8762 }
8763 serializer.endTag(null, "item");
8764 }
8765 }
8766
8767 String getReadMessagesLP() {
8768 return mReadMessages.toString();
8769 }
8770
Oscar Montemayora8529f62009-11-18 10:14:20 -08008771 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8773 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008774 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008775 while(its.hasNext()) {
8776 String key = its.next();
8777 PackageSetting ps = mPackages.get(key);
8778 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008779 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008780 }
8781 }
8782 return ret;
8783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 boolean readLP() {
8786 FileInputStream str = null;
8787 if (mBackupSettingsFilename.exists()) {
8788 try {
8789 str = new FileInputStream(mBackupSettingsFilename);
8790 mReadMessages.append("Reading from backup settings file\n");
8791 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008792 if (mSettingsFilename.exists()) {
8793 // If both the backup and settings file exist, we
8794 // ignore the settings since it might have been
8795 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008796 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008797 mSettingsFilename.delete();
8798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 } catch (java.io.IOException e) {
8800 // We'll try for the normal settings file.
8801 }
8802 }
8803
8804 mPastSignatures.clear();
8805
8806 try {
8807 if (str == null) {
8808 if (!mSettingsFilename.exists()) {
8809 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008810 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008811 return false;
8812 }
8813 str = new FileInputStream(mSettingsFilename);
8814 }
8815 XmlPullParser parser = Xml.newPullParser();
8816 parser.setInput(str, null);
8817
8818 int type;
8819 while ((type=parser.next()) != XmlPullParser.START_TAG
8820 && type != XmlPullParser.END_DOCUMENT) {
8821 ;
8822 }
8823
8824 if (type != XmlPullParser.START_TAG) {
8825 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008826 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008827 return false;
8828 }
8829
8830 int outerDepth = parser.getDepth();
8831 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8832 && (type != XmlPullParser.END_TAG
8833 || parser.getDepth() > outerDepth)) {
8834 if (type == XmlPullParser.END_TAG
8835 || type == XmlPullParser.TEXT) {
8836 continue;
8837 }
8838
8839 String tagName = parser.getName();
8840 if (tagName.equals("package")) {
8841 readPackageLP(parser);
8842 } else if (tagName.equals("permissions")) {
8843 readPermissionsLP(mPermissions, parser);
8844 } else if (tagName.equals("permission-trees")) {
8845 readPermissionsLP(mPermissionTrees, parser);
8846 } else if (tagName.equals("shared-user")) {
8847 readSharedUserLP(parser);
8848 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008849 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008850 } else if (tagName.equals("preferred-activities")) {
8851 readPreferredActivitiesLP(parser);
8852 } else if(tagName.equals("updated-package")) {
8853 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008854 } else if (tagName.equals("cleaning-package")) {
8855 String name = parser.getAttributeValue(null, "name");
8856 if (name != null) {
8857 mPackagesToBeCleaned.add(name);
8858 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008859 } else if (tagName.equals("renamed-package")) {
8860 String nname = parser.getAttributeValue(null, "new");
8861 String oname = parser.getAttributeValue(null, "old");
8862 if (nname != null && oname != null) {
8863 mRenamedPackages.put(nname, oname);
8864 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008865 } else if (tagName.equals("last-platform-version")) {
8866 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8867 try {
8868 String internal = parser.getAttributeValue(null, "internal");
8869 if (internal != null) {
8870 mInternalSdkPlatform = Integer.parseInt(internal);
8871 }
8872 String external = parser.getAttributeValue(null, "external");
8873 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008874 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008875 }
8876 } catch (NumberFormatException e) {
8877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008878 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008879 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008880 + parser.getName());
8881 XmlUtils.skipCurrentTag(parser);
8882 }
8883 }
8884
8885 str.close();
8886
8887 } catch(XmlPullParserException e) {
8888 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008889 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890
8891 } catch(java.io.IOException e) {
8892 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008893 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008894
8895 }
8896
8897 int N = mPendingPackages.size();
8898 for (int i=0; i<N; i++) {
8899 final PendingPackage pp = mPendingPackages.get(i);
8900 Object idObj = getUserIdLP(pp.sharedId);
8901 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008902 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008903 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8904 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008906 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 + pp.name);
8908 continue;
8909 }
8910 p.copyFrom(pp);
8911 } else if (idObj != null) {
8912 String msg = "Bad package setting: package " + pp.name
8913 + " has shared uid " + pp.sharedId
8914 + " that is not a shared uid\n";
8915 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008916 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008917 } else {
8918 String msg = "Bad package setting: package " + pp.name
8919 + " has shared uid " + pp.sharedId
8920 + " that is not defined\n";
8921 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008922 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923 }
8924 }
8925 mPendingPackages.clear();
8926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 mReadMessages.append("Read completed successfully: "
8928 + mPackages.size() + " packages, "
8929 + mSharedUsers.size() + " shared uids\n");
8930
8931 return true;
8932 }
8933
8934 private int readInt(XmlPullParser parser, String ns, String name,
8935 int defValue) {
8936 String v = parser.getAttributeValue(ns, name);
8937 try {
8938 if (v == null) {
8939 return defValue;
8940 }
8941 return Integer.parseInt(v);
8942 } catch (NumberFormatException e) {
8943 reportSettingsProblem(Log.WARN,
8944 "Error in package manager settings: attribute " +
8945 name + " has bad integer value " + v + " at "
8946 + parser.getPositionDescription());
8947 }
8948 return defValue;
8949 }
8950
8951 private void readPermissionsLP(HashMap<String, BasePermission> out,
8952 XmlPullParser parser)
8953 throws IOException, XmlPullParserException {
8954 int outerDepth = parser.getDepth();
8955 int type;
8956 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8957 && (type != XmlPullParser.END_TAG
8958 || parser.getDepth() > outerDepth)) {
8959 if (type == XmlPullParser.END_TAG
8960 || type == XmlPullParser.TEXT) {
8961 continue;
8962 }
8963
8964 String tagName = parser.getName();
8965 if (tagName.equals("item")) {
8966 String name = parser.getAttributeValue(null, "name");
8967 String sourcePackage = parser.getAttributeValue(null, "package");
8968 String ptype = parser.getAttributeValue(null, "type");
8969 if (name != null && sourcePackage != null) {
8970 boolean dynamic = "dynamic".equals(ptype);
8971 BasePermission bp = new BasePermission(name, sourcePackage,
8972 dynamic
8973 ? BasePermission.TYPE_DYNAMIC
8974 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008975 bp.protectionLevel = readInt(parser, null, "protection",
8976 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008977 if (dynamic) {
8978 PermissionInfo pi = new PermissionInfo();
8979 pi.packageName = sourcePackage.intern();
8980 pi.name = name.intern();
8981 pi.icon = readInt(parser, null, "icon", 0);
8982 pi.nonLocalizedLabel = parser.getAttributeValue(
8983 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008984 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 bp.pendingInfo = pi;
8986 }
8987 out.put(bp.name, bp);
8988 } else {
8989 reportSettingsProblem(Log.WARN,
8990 "Error in package manager settings: permissions has"
8991 + " no name at " + parser.getPositionDescription());
8992 }
8993 } else {
8994 reportSettingsProblem(Log.WARN,
8995 "Unknown element reading permissions: "
8996 + parser.getName() + " at "
8997 + parser.getPositionDescription());
8998 }
8999 XmlUtils.skipCurrentTag(parser);
9000 }
9001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009002
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009003 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009004 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009005 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009006 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009007 String codePathStr = parser.getAttributeValue(null, "codePath");
9008 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009009 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009010 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011 resourcePathStr = codePathStr;
9012 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009013 String version = parser.getAttributeValue(null, "version");
9014 int versionCode = 0;
9015 if (version != null) {
9016 try {
9017 versionCode = Integer.parseInt(version);
9018 } catch (NumberFormatException e) {
9019 }
9020 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009022 int pkgFlags = 0;
9023 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009024 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9025 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009026 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009027 if (timeStampStr != null) {
9028 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009029 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009030 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 } catch (NumberFormatException e) {
9032 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009033 } else {
9034 timeStampStr = parser.getAttributeValue(null, "ts");
9035 if (timeStampStr != null) {
9036 try {
9037 long timeStamp = Long.parseLong(timeStampStr);
9038 ps.setTimeStamp(timeStamp);
9039 } catch (NumberFormatException e) {
9040 }
9041 }
9042 }
9043 timeStampStr = parser.getAttributeValue(null, "it");
9044 if (timeStampStr != null) {
9045 try {
9046 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9047 } catch (NumberFormatException e) {
9048 }
9049 }
9050 timeStampStr = parser.getAttributeValue(null, "ut");
9051 if (timeStampStr != null) {
9052 try {
9053 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9054 } catch (NumberFormatException e) {
9055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009056 }
9057 String idStr = parser.getAttributeValue(null, "userId");
9058 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9059 if(ps.userId <= 0) {
9060 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9061 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9062 }
9063 int outerDepth = parser.getDepth();
9064 int type;
9065 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9066 && (type != XmlPullParser.END_TAG
9067 || parser.getDepth() > outerDepth)) {
9068 if (type == XmlPullParser.END_TAG
9069 || type == XmlPullParser.TEXT) {
9070 continue;
9071 }
9072
9073 String tagName = parser.getName();
9074 if (tagName.equals("perms")) {
9075 readGrantedPermissionsLP(parser,
9076 ps.grantedPermissions);
9077 } else {
9078 reportSettingsProblem(Log.WARN,
9079 "Unknown element under <updated-package>: "
9080 + parser.getName());
9081 XmlUtils.skipCurrentTag(parser);
9082 }
9083 }
9084 mDisabledSysPackages.put(name, ps);
9085 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009087 private void readPackageLP(XmlPullParser parser)
9088 throws XmlPullParserException, IOException {
9089 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009090 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009091 String idStr = null;
9092 String sharedIdStr = null;
9093 String codePathStr = null;
9094 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009095 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009096 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009097 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009098 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009099 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009100 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009101 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009102 long firstInstallTime = 0;
9103 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009104 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009105 String version = null;
9106 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009107 try {
9108 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009109 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009110 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009111 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009112 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9113 codePathStr = parser.getAttributeValue(null, "codePath");
9114 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009115 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009116 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009117 version = parser.getAttributeValue(null, "version");
9118 if (version != null) {
9119 try {
9120 versionCode = Integer.parseInt(version);
9121 } catch (NumberFormatException e) {
9122 }
9123 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009124 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009125
9126 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009127 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009128 try {
9129 pkgFlags = Integer.parseInt(systemStr);
9130 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009131 }
9132 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009133 // For backward compatibility
9134 systemStr = parser.getAttributeValue(null, "system");
9135 if (systemStr != null) {
9136 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9137 } else {
9138 // Old settings that don't specify system... just treat
9139 // them as system, good enough.
9140 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009143 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009144 if (timeStampStr != null) {
9145 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009146 timeStamp = Long.parseLong(timeStampStr, 16);
9147 } catch (NumberFormatException e) {
9148 }
9149 } else {
9150 timeStampStr = parser.getAttributeValue(null, "ts");
9151 if (timeStampStr != null) {
9152 try {
9153 timeStamp = Long.parseLong(timeStampStr);
9154 } catch (NumberFormatException e) {
9155 }
9156 }
9157 }
9158 timeStampStr = parser.getAttributeValue(null, "it");
9159 if (timeStampStr != null) {
9160 try {
9161 firstInstallTime = Long.parseLong(timeStampStr, 16);
9162 } catch (NumberFormatException e) {
9163 }
9164 }
9165 timeStampStr = parser.getAttributeValue(null, "ut");
9166 if (timeStampStr != null) {
9167 try {
9168 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 } catch (NumberFormatException e) {
9170 }
9171 }
9172 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9173 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9174 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9175 if (resourcePathStr == null) {
9176 resourcePathStr = codePathStr;
9177 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009178 if (realName != null) {
9179 realName = realName.intern();
9180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 if (name == null) {
9182 reportSettingsProblem(Log.WARN,
9183 "Error in package manager settings: <package> has no name at "
9184 + parser.getPositionDescription());
9185 } else if (codePathStr == null) {
9186 reportSettingsProblem(Log.WARN,
9187 "Error in package manager settings: <package> has no codePath at "
9188 + parser.getPositionDescription());
9189 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009190 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9191 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9192 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009193 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9194 + ": userId=" + userId + " pkg=" + packageSetting);
9195 if (packageSetting == null) {
9196 reportSettingsProblem(Log.ERROR,
9197 "Failure adding uid " + userId
9198 + " while parsing settings at "
9199 + parser.getPositionDescription());
9200 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009201 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009202 packageSetting.firstInstallTime = firstInstallTime;
9203 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009204 }
9205 } else if (sharedIdStr != null) {
9206 userId = sharedIdStr != null
9207 ? Integer.parseInt(sharedIdStr) : 0;
9208 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009209 packageSetting = new PendingPackage(name.intern(), realName,
9210 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009211 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009212 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009213 packageSetting.firstInstallTime = firstInstallTime;
9214 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009215 mPendingPackages.add((PendingPackage) packageSetting);
9216 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9217 + ": sharedUserId=" + userId + " pkg="
9218 + packageSetting);
9219 } else {
9220 reportSettingsProblem(Log.WARN,
9221 "Error in package manager settings: package "
9222 + name + " has bad sharedId " + sharedIdStr
9223 + " at " + parser.getPositionDescription());
9224 }
9225 } else {
9226 reportSettingsProblem(Log.WARN,
9227 "Error in package manager settings: package "
9228 + name + " has bad userId " + idStr + " at "
9229 + parser.getPositionDescription());
9230 }
9231 } catch (NumberFormatException e) {
9232 reportSettingsProblem(Log.WARN,
9233 "Error in package manager settings: package "
9234 + name + " has bad userId " + idStr + " at "
9235 + parser.getPositionDescription());
9236 }
9237 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009238 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009239 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009240 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009241 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009242 final String enabledStr = parser.getAttributeValue(null, "enabled");
9243 if (enabledStr != null) {
9244 if (enabledStr.equalsIgnoreCase("true")) {
9245 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9246 } else if (enabledStr.equalsIgnoreCase("false")) {
9247 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9248 } else if (enabledStr.equalsIgnoreCase("default")) {
9249 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9250 } else {
9251 reportSettingsProblem(Log.WARN,
9252 "Error in package manager settings: package "
9253 + name + " has bad enabled value: " + idStr
9254 + " at " + parser.getPositionDescription());
9255 }
9256 } else {
9257 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9258 }
9259 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9260 if (installStatusStr != null) {
9261 if (installStatusStr.equalsIgnoreCase("false")) {
9262 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9263 } else {
9264 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9265 }
9266 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009267
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009268 int outerDepth = parser.getDepth();
9269 int type;
9270 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9271 && (type != XmlPullParser.END_TAG
9272 || parser.getDepth() > outerDepth)) {
9273 if (type == XmlPullParser.END_TAG
9274 || type == XmlPullParser.TEXT) {
9275 continue;
9276 }
9277
9278 String tagName = parser.getName();
9279 if (tagName.equals("disabled-components")) {
9280 readDisabledComponentsLP(packageSetting, parser);
9281 } else if (tagName.equals("enabled-components")) {
9282 readEnabledComponentsLP(packageSetting, parser);
9283 } else if (tagName.equals("sigs")) {
9284 packageSetting.signatures.readXml(parser, mPastSignatures);
9285 } else if (tagName.equals("perms")) {
9286 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009287 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009288 packageSetting.permissionsFixed = true;
9289 } else {
9290 reportSettingsProblem(Log.WARN,
9291 "Unknown element under <package>: "
9292 + parser.getName());
9293 XmlUtils.skipCurrentTag(parser);
9294 }
9295 }
9296 } else {
9297 XmlUtils.skipCurrentTag(parser);
9298 }
9299 }
9300
9301 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9302 XmlPullParser parser)
9303 throws IOException, XmlPullParserException {
9304 int outerDepth = parser.getDepth();
9305 int type;
9306 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9307 && (type != XmlPullParser.END_TAG
9308 || parser.getDepth() > outerDepth)) {
9309 if (type == XmlPullParser.END_TAG
9310 || type == XmlPullParser.TEXT) {
9311 continue;
9312 }
9313
9314 String tagName = parser.getName();
9315 if (tagName.equals("item")) {
9316 String name = parser.getAttributeValue(null, "name");
9317 if (name != null) {
9318 packageSetting.disabledComponents.add(name.intern());
9319 } else {
9320 reportSettingsProblem(Log.WARN,
9321 "Error in package manager settings: <disabled-components> has"
9322 + " no name at " + parser.getPositionDescription());
9323 }
9324 } else {
9325 reportSettingsProblem(Log.WARN,
9326 "Unknown element under <disabled-components>: "
9327 + parser.getName());
9328 }
9329 XmlUtils.skipCurrentTag(parser);
9330 }
9331 }
9332
9333 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9334 XmlPullParser parser)
9335 throws IOException, XmlPullParserException {
9336 int outerDepth = parser.getDepth();
9337 int type;
9338 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9339 && (type != XmlPullParser.END_TAG
9340 || parser.getDepth() > outerDepth)) {
9341 if (type == XmlPullParser.END_TAG
9342 || type == XmlPullParser.TEXT) {
9343 continue;
9344 }
9345
9346 String tagName = parser.getName();
9347 if (tagName.equals("item")) {
9348 String name = parser.getAttributeValue(null, "name");
9349 if (name != null) {
9350 packageSetting.enabledComponents.add(name.intern());
9351 } else {
9352 reportSettingsProblem(Log.WARN,
9353 "Error in package manager settings: <enabled-components> has"
9354 + " no name at " + parser.getPositionDescription());
9355 }
9356 } else {
9357 reportSettingsProblem(Log.WARN,
9358 "Unknown element under <enabled-components>: "
9359 + parser.getName());
9360 }
9361 XmlUtils.skipCurrentTag(parser);
9362 }
9363 }
9364
9365 private void readSharedUserLP(XmlPullParser parser)
9366 throws XmlPullParserException, IOException {
9367 String name = null;
9368 String idStr = null;
9369 int pkgFlags = 0;
9370 SharedUserSetting su = null;
9371 try {
9372 name = parser.getAttributeValue(null, "name");
9373 idStr = parser.getAttributeValue(null, "userId");
9374 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9375 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9376 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9377 }
9378 if (name == null) {
9379 reportSettingsProblem(Log.WARN,
9380 "Error in package manager settings: <shared-user> has no name at "
9381 + parser.getPositionDescription());
9382 } else if (userId == 0) {
9383 reportSettingsProblem(Log.WARN,
9384 "Error in package manager settings: shared-user "
9385 + name + " has bad userId " + idStr + " at "
9386 + parser.getPositionDescription());
9387 } else {
9388 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9389 reportSettingsProblem(Log.ERROR,
9390 "Occurred while parsing settings at "
9391 + parser.getPositionDescription());
9392 }
9393 }
9394 } catch (NumberFormatException e) {
9395 reportSettingsProblem(Log.WARN,
9396 "Error in package manager settings: package "
9397 + name + " has bad userId " + idStr + " at "
9398 + parser.getPositionDescription());
9399 };
9400
9401 if (su != null) {
9402 int outerDepth = parser.getDepth();
9403 int type;
9404 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9405 && (type != XmlPullParser.END_TAG
9406 || parser.getDepth() > outerDepth)) {
9407 if (type == XmlPullParser.END_TAG
9408 || type == XmlPullParser.TEXT) {
9409 continue;
9410 }
9411
9412 String tagName = parser.getName();
9413 if (tagName.equals("sigs")) {
9414 su.signatures.readXml(parser, mPastSignatures);
9415 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009416 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009417 } else {
9418 reportSettingsProblem(Log.WARN,
9419 "Unknown element under <shared-user>: "
9420 + parser.getName());
9421 XmlUtils.skipCurrentTag(parser);
9422 }
9423 }
9424
9425 } else {
9426 XmlUtils.skipCurrentTag(parser);
9427 }
9428 }
9429
9430 private void readGrantedPermissionsLP(XmlPullParser parser,
9431 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9432 int outerDepth = parser.getDepth();
9433 int type;
9434 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9435 && (type != XmlPullParser.END_TAG
9436 || parser.getDepth() > outerDepth)) {
9437 if (type == XmlPullParser.END_TAG
9438 || type == XmlPullParser.TEXT) {
9439 continue;
9440 }
9441
9442 String tagName = parser.getName();
9443 if (tagName.equals("item")) {
9444 String name = parser.getAttributeValue(null, "name");
9445 if (name != null) {
9446 outPerms.add(name.intern());
9447 } else {
9448 reportSettingsProblem(Log.WARN,
9449 "Error in package manager settings: <perms> has"
9450 + " no name at " + parser.getPositionDescription());
9451 }
9452 } else {
9453 reportSettingsProblem(Log.WARN,
9454 "Unknown element under <perms>: "
9455 + parser.getName());
9456 }
9457 XmlUtils.skipCurrentTag(parser);
9458 }
9459 }
9460
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009461 private void readPreferredActivitiesLP(XmlPullParser parser)
9462 throws XmlPullParserException, IOException {
9463 int outerDepth = parser.getDepth();
9464 int type;
9465 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9466 && (type != XmlPullParser.END_TAG
9467 || parser.getDepth() > outerDepth)) {
9468 if (type == XmlPullParser.END_TAG
9469 || type == XmlPullParser.TEXT) {
9470 continue;
9471 }
9472
9473 String tagName = parser.getName();
9474 if (tagName.equals("item")) {
9475 PreferredActivity pa = new PreferredActivity(parser);
9476 if (pa.mParseError == null) {
9477 mPreferredActivities.addFilter(pa);
9478 } else {
9479 reportSettingsProblem(Log.WARN,
9480 "Error in package manager settings: <preferred-activity> "
9481 + pa.mParseError + " at "
9482 + parser.getPositionDescription());
9483 }
9484 } else {
9485 reportSettingsProblem(Log.WARN,
9486 "Unknown element under <preferred-activities>: "
9487 + parser.getName());
9488 XmlUtils.skipCurrentTag(parser);
9489 }
9490 }
9491 }
9492
9493 // Returns -1 if we could not find an available UserId to assign
9494 private int newUserIdLP(Object obj) {
9495 // Let's be stupidly inefficient for now...
9496 final int N = mUserIds.size();
9497 for (int i=0; i<N; i++) {
9498 if (mUserIds.get(i) == null) {
9499 mUserIds.set(i, obj);
9500 return FIRST_APPLICATION_UID + i;
9501 }
9502 }
9503
9504 // None left?
9505 if (N >= MAX_APPLICATION_UIDS) {
9506 return -1;
9507 }
9508
9509 mUserIds.add(obj);
9510 return FIRST_APPLICATION_UID + N;
9511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009513 public PackageSetting getDisabledSystemPkg(String name) {
9514 synchronized(mPackages) {
9515 PackageSetting ps = mDisabledSysPackages.get(name);
9516 return ps;
9517 }
9518 }
9519
9520 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009521 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9522 return true;
9523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009524 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9525 if (Config.LOGV) {
9526 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9527 + " componentName = " + componentInfo.name);
9528 Log.v(TAG, "enabledComponents: "
9529 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9530 Log.v(TAG, "disabledComponents: "
9531 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9532 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009533 if (packageSettings == null) {
9534 if (false) {
9535 Log.w(TAG, "WAITING FOR DEBUGGER");
9536 Debug.waitForDebugger();
9537 Log.i(TAG, "We will crash!");
9538 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009539 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009540 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009541 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9542 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9543 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9544 return false;
9545 }
9546 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9547 return true;
9548 }
9549 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9550 return false;
9551 }
9552 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009553 }
9554 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009555
9556 // ------- apps on sdcard specific code -------
9557 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009558 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9559 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9560 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009561 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009562
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009563 private String getEncryptKey() {
9564 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009565 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9566 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009567 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009568 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9569 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009570 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009571 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009572 return null;
9573 }
9574 }
9575 return sdEncKey;
9576 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009577 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009578 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009579 } catch (IOException ioe) {
9580 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9581 + ioe);
9582 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009583 }
Rich Cannings8d578832010-09-09 15:12:40 -07009584
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009585 }
9586
Kenny Rootc78a8072010-07-27 15:18:38 -07009587 /* package */ static String getTempContainerId() {
9588 int tmpIdx = 1;
9589 String list[] = PackageHelper.getSecureContainerList();
9590 if (list != null) {
9591 for (final String name : list) {
9592 // Ignore null and non-temporary container entries
9593 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9594 continue;
9595 }
9596
9597 String subStr = name.substring(mTempContainerPrefix.length());
9598 try {
9599 int cid = Integer.parseInt(subStr);
9600 if (cid >= tmpIdx) {
9601 tmpIdx = cid + 1;
9602 }
9603 } catch (NumberFormatException e) {
9604 }
9605 }
9606 }
9607 return mTempContainerPrefix + tmpIdx;
9608 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009609
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009610 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009611 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009612 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009613 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9614 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9615 throw new SecurityException("Media status can only be updated by the system");
9616 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009617 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009618 Log.i(TAG, "Updating external media status from " +
9619 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9620 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009621 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9622 mediaStatus+", mMediaMounted=" + mMediaMounted);
9623 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009624 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9625 reportStatus ? 1 : 0, -1);
9626 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009627 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009628 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009629 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009630 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009631 // Queue up an async operation since the package installation may take a little while.
9632 mHandler.post(new Runnable() {
9633 public void run() {
9634 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009635 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009636 }
9637 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009638 }
9639
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009640 /*
9641 * Collect information of applications on external media, map them
9642 * against existing containers and update information based on current
9643 * mount status. Please note that we always have to report status
9644 * if reportStatus has been set to true especially when unloading packages.
9645 */
9646 private void updateExternalMediaStatusInner(boolean mediaStatus,
9647 boolean reportStatus) {
9648 // Collection of uids
9649 int uidArr[] = null;
9650 // Collection of stale containers
9651 HashSet<String> removeCids = new HashSet<String>();
9652 // Collection of packages on external media with valid containers.
9653 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9654 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009655 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009656 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009657 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009658 } else {
9659 // Process list of secure containers and categorize them
9660 // as active or stale based on their package internal state.
9661 int uidList[] = new int[list.length];
9662 int num = 0;
9663 synchronized (mPackages) {
9664 for (String cid : list) {
9665 SdInstallArgs args = new SdInstallArgs(cid);
9666 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009667 String pkgName = args.getPackageName();
9668 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009669 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9670 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009671 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009672 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009673 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9674 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009675 // The package status is changed only if the code path
9676 // matches between settings and the container id.
9677 if (ps != null && ps.codePathString != null &&
9678 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009679 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9680 " corresponds to pkg : " + pkgName +
9681 " at code path: " + ps.codePathString);
9682 // We do have a valid package installed on sdcard
9683 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009684 int uid = ps.userId;
9685 if (uid != -1) {
9686 uidList[num++] = uid;
9687 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009688 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009689 // Stale container on sdcard. Just delete
9690 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9691 removeCids.add(cid);
9692 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009693 }
9694 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009695
9696 if (num > 0) {
9697 // Sort uid list
9698 Arrays.sort(uidList, 0, num);
9699 // Throw away duplicates
9700 uidArr = new int[num];
9701 uidArr[0] = uidList[0];
9702 int di = 0;
9703 for (int i = 1; i < num; i++) {
9704 if (uidList[i-1] != uidList[i]) {
9705 uidArr[di++] = uidList[i];
9706 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009707 }
9708 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009709 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009710 // Process packages with valid entries.
9711 if (mediaStatus) {
9712 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009713 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009714 startCleaningPackages();
9715 } else {
9716 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009717 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009718 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009719 }
9720
9721 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009722 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009723 int size = pkgList.size();
9724 if (size > 0) {
9725 // Send broadcasts here
9726 Bundle extras = new Bundle();
9727 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9728 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009729 if (uidArr != null) {
9730 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9731 }
9732 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9733 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009734 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009735 }
9736 }
9737
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009738 /*
9739 * Look at potentially valid container ids from processCids
9740 * If package information doesn't match the one on record
9741 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009742 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009743 */
9744 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009745 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009746 ArrayList<String> pkgList = new ArrayList<String>();
9747 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009748 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009749 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009750 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009751 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9752 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009753 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009754 try {
9755 // Make sure there are no container errors first.
9756 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9757 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009758 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009759 " when installing from sdcard");
9760 continue;
9761 }
9762 // Check code path here.
9763 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009764 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009765 " does not match one in settings " + codePath);
9766 continue;
9767 }
9768 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009769 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009770 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009771 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009772 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009773 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009774 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009775 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009776 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009777 retCode = PackageManager.INSTALL_SUCCEEDED;
9778 pkgList.add(pkg.packageName);
9779 // Post process args
9780 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9781 }
9782 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009783 Slog.i(TAG, "Failed to install pkg from " +
9784 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009785 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009786 }
9787
9788 } finally {
9789 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9790 // Don't destroy container here. Wait till gc clears things up.
9791 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009792 }
9793 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009794 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009795 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009796 // If the platform SDK has changed since the last time we booted,
9797 // we need to re-grant app permission to catch any new ones that
9798 // appear. This is really a hack, and means that apps can in some
9799 // cases get permissions that the user didn't initially explicitly
9800 // allow... it would be nice to have some better way to handle
9801 // this situation.
9802 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9803 != mSdkVersion;
9804 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9805 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9806 + "; regranting permissions for external storage");
9807 mSettings.mExternalSdkPlatform = mSdkVersion;
9808
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009809 // Make sure group IDs have been assigned, and any permission
9810 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009811 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009812 // Persist settings
9813 mSettings.writeLP();
9814 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009815 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009816 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009817 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009818 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009819 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009820 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009821 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009822 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009823 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009824 if (removeCids != null) {
9825 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009826 if (cid.startsWith(mTempContainerPrefix)) {
9827 Log.i(TAG, "Destroying stale temporary container " + cid);
9828 PackageHelper.destroySdDir(cid);
9829 } else {
9830 Log.w(TAG, "Container " + cid + " is stale");
9831 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009832 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009833 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009834 }
9835
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009836 /*
9837 * Utility method to unload a list of specified containers
9838 */
9839 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9840 // Just unmount all valid containers.
9841 for (SdInstallArgs arg : cidArgs) {
9842 synchronized (mInstallLock) {
9843 arg.doPostDeleteLI(false);
9844 }
9845 }
9846 }
9847
9848 /*
9849 * Unload packages mounted on external media. This involves deleting
9850 * package data from internal structures, sending broadcasts about
9851 * diabled packages, gc'ing to free up references, unmounting all
9852 * secure containers corresponding to packages on external media, and
9853 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9854 * Please note that we always have to post this message if status has
9855 * been requested no matter what.
9856 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009857 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009858 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009859 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009860 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009861 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009862 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009863 for (SdInstallArgs args : keys) {
9864 String cid = args.cid;
9865 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009866 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009867 // Delete package internally
9868 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9869 synchronized (mInstallLock) {
9870 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009871 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009872 if (res) {
9873 pkgList.add(pkgName);
9874 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009875 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009876 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009877 }
9878 }
9879 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009880
9881 synchronized (mPackages) {
9882 // We didn't update the settings after removing each package;
9883 // write them now for all packages.
9884 mSettings.writeLP();
9885 }
9886
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009887 // We have to absolutely send UPDATED_MEDIA_STATUS only
9888 // after confirming that all the receivers processed the ordered
9889 // broadcast when packages get disabled, force a gc to clean things up.
9890 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009891 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009892 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9893 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9894 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009895 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9896 reportStatus ? 1 : 0, 1, keys);
9897 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009898 }
9899 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009900 } else {
9901 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9902 reportStatus ? 1 : 0, -1, keys);
9903 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009904 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009905 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009906
9907 public void movePackage(final String packageName,
9908 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009909 mContext.enforceCallingOrSelfPermission(
9910 android.Manifest.permission.MOVE_PACKAGE, null);
9911 int returnCode = PackageManager.MOVE_SUCCEEDED;
9912 int currFlags = 0;
9913 int newFlags = 0;
9914 synchronized (mPackages) {
9915 PackageParser.Package pkg = mPackages.get(packageName);
9916 if (pkg == null) {
9917 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009918 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009919 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009920 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009921 Slog.w(TAG, "Cannot move system application");
9922 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009923 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009924 Slog.w(TAG, "Cannot move forward locked app.");
9925 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009926 } else if (pkg.mOperationPending) {
9927 Slog.w(TAG, "Attempt to move package which has pending operations");
9928 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009929 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009930 // Find install location first
9931 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9932 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9933 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009934 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009935 } else {
9936 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9937 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009938 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9939 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009940 if (newFlags == currFlags) {
9941 Slog.w(TAG, "No move required. Trying to move to same location");
9942 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9943 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009944 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009945 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9946 pkg.mOperationPending = true;
9947 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009948 }
9949 }
9950 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009951 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009952 } else {
9953 Message msg = mHandler.obtainMessage(INIT_COPY);
9954 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009955 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9956 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9957 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009958 msg.obj = mp;
9959 mHandler.sendMessage(msg);
9960 }
9961 }
9962 }
9963
9964 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9965 // Queue up an async operation since the package deletion may take a little while.
9966 mHandler.post(new Runnable() {
9967 public void run() {
9968 mHandler.removeCallbacks(this);
9969 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009970 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9971 int uidArr[] = null;
9972 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009973 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009974 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009975 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009976 Slog.w(TAG, " Package " + mp.packageName +
9977 " doesn't exist. Aborting move");
9978 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9979 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9980 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9981 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9982 " Aborting move and returning error");
9983 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9984 } else {
9985 uidArr = new int[] { pkg.applicationInfo.uid };
9986 pkgList = new ArrayList<String>();
9987 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009988 }
9989 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009990 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9991 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009992 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009993 // Update package code and resource paths
9994 synchronized (mInstallLock) {
9995 synchronized (mPackages) {
9996 PackageParser.Package pkg = mPackages.get(mp.packageName);
9997 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -07009998 if (pkg == null) {
9999 Slog.w(TAG, " Package " + mp.packageName
10000 + " doesn't exist. Aborting move");
10001 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010002 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10003 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10004 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10005 " Aborting move and returning error");
10006 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10007 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010008 final String oldCodePath = pkg.mPath;
10009 final String newCodePath = mp.targetArgs.getCodePath();
10010 final String newResPath = mp.targetArgs.getResourcePath();
10011 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010012
10013 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10014 if (mInstaller
10015 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10016 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10017 } else {
10018 NativeLibraryHelper.copyNativeBinariesLI(
10019 new File(newCodePath), new File(newNativePath));
10020 }
10021 } else {
10022 if (mInstaller.linkNativeLibraryDirectory(
10023 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10024 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10025 }
10026 }
10027
10028 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10029 pkg.mPath = newCodePath;
10030 // Move dex files around
10031 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10032 // Moving of dex files failed. Set
10033 // error code and abort move.
10034 pkg.mPath = pkg.mScanPath;
10035 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10036 }
10037 }
10038
10039 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010040 pkg.mScanPath = newCodePath;
10041 pkg.applicationInfo.sourceDir = newCodePath;
10042 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010043 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010044 PackageSetting ps = (PackageSetting) pkg.mExtras;
10045 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10046 ps.codePathString = ps.codePath.getPath();
10047 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10048 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010049 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010050 // Set the application info flag correctly.
10051 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10052 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10053 } else {
10054 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10055 }
10056 ps.setFlags(pkg.applicationInfo.flags);
10057 mAppDirs.remove(oldCodePath);
10058 mAppDirs.put(newCodePath, pkg);
10059 // Persist settings
10060 mSettings.writeLP();
10061 }
10062 }
10063 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010064 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010065 // Send resources available broadcast
10066 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010067 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010068 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010069 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010070 // Clean up failed installation
10071 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010072 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010073 }
10074 } else {
10075 // Force a gc to clear things up.
10076 Runtime.getRuntime().gc();
10077 // Delete older code
10078 synchronized (mInstallLock) {
10079 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010080 }
10081 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010082
10083 // Allow more operations on this file if we didn't fail because
10084 // an operation was already pending for this package.
10085 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10086 synchronized (mPackages) {
10087 PackageParser.Package pkg = mPackages.get(mp.packageName);
10088 if (pkg != null) {
10089 pkg.mOperationPending = false;
10090 }
10091 }
10092 }
10093
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010094 IPackageMoveObserver observer = mp.observer;
10095 if (observer != null) {
10096 try {
10097 observer.packageMoved(mp.packageName, returnCode);
10098 } catch (RemoteException e) {
10099 Log.i(TAG, "Observer no longer exists.");
10100 }
10101 }
10102 }
10103 });
10104 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010105
10106 public boolean setInstallLocation(int loc) {
10107 mContext.enforceCallingOrSelfPermission(
10108 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10109 if (getInstallLocation() == loc) {
10110 return true;
10111 }
10112 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10113 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10114 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10115 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10116 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10117 return true;
10118 }
10119 return false;
10120 }
10121
10122 public int getInstallLocation() {
10123 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10124 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010126}