blob: a2d329802ac354a21537b0564559bae01d9990c4 [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
94import java.io.File;
95import java.io.FileDescriptor;
96import java.io.FileInputStream;
97import java.io.FileNotFoundException;
98import java.io.FileOutputStream;
99import java.io.FileReader;
100import java.io.FilenameFilter;
101import java.io.IOException;
102import java.io.InputStream;
103import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800104import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800105import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.ArrayList;
107import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700108import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Collections;
110import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800111import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import java.util.Enumeration;
113import java.util.HashMap;
114import java.util.HashSet;
115import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700116import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import java.util.List;
118import java.util.Map;
119import java.util.Set;
120import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800121import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import java.util.zip.ZipFile;
123import java.util.zip.ZipOutputStream;
124
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700125/**
126 * Keep track of all those .apks everywhere.
127 *
128 * This is very central to the platform's security; please run the unit
129 * tests whenever making modifications here:
130 *
131mmm frameworks/base/tests/AndroidTests
132adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
133adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
134 *
135 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136class PackageManagerService extends IPackageManager.Stub {
137 private static final String TAG = "PackageManager";
138 private static final boolean DEBUG_SETTINGS = false;
139 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800140 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800141 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700142 private static final boolean DEBUG_NATIVE = 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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700187 static final int REMOVE_CHATTY = 1<<16;
188
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800189 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
190 "com.android.defcontainer",
191 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700192
Kenny Root85387d72010-08-26 10:13:11 -0700193 private static final String LIB_DIR_NAME = "lib";
194
Kenny Rootc78a8072010-07-27 15:18:38 -0700195 static final String mTempContainerPrefix = "smdl2tmp";
196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
198 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700199 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Dianne Hackborn851a5412009-05-08 12:06:44 -0700201 final int mSdkVersion = Build.VERSION.SDK_INT;
202 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
203 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 final Context mContext;
206 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700207 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 final DisplayMetrics mMetrics;
209 final int mDefParseFlags;
210 final String[] mSeparateProcesses;
211
212 // This is where all application persistent data goes.
213 final File mAppDataDir;
214
Oscar Montemayora8529f62009-11-18 10:14:20 -0800215 // If Encrypted File System feature is enabled, all application persistent data
216 // should go here instead.
217 final File mSecureAppDataDir;
218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 // This is the object monitoring the framework dir.
220 final FileObserver mFrameworkInstallObserver;
221
222 // This is the object monitoring the system app dir.
223 final FileObserver mSystemInstallObserver;
224
225 // This is the object monitoring mAppInstallDir.
226 final FileObserver mAppInstallObserver;
227
228 // This is the object monitoring mDrmAppPrivateInstallDir.
229 final FileObserver mDrmAppInstallObserver;
230
231 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
232 // LOCK HELD. Can be called with mInstallLock held.
233 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 final File mFrameworkDir;
236 final File mSystemAppDir;
237 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700238 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
241 // apps.
242 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 // Lock for state used when installing and doing other long running
247 // operations. Methods that must be called with this lock held have
248 // the prefix "LI".
249 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // These are the directories in the 3rd party applications installed dir
252 // that we have currently loaded packages from. Keys are the application's
253 // installed zip file (absolute codePath), and values are Package.
254 final HashMap<String, PackageParser.Package> mAppDirs =
255 new HashMap<String, PackageParser.Package>();
256
257 // Information for the parser to write more useful error messages.
258 File mScanningPath;
259 int mLastScanError;
260
261 final int[] mOutPermissions = new int[3];
262
263 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 // Keys are String (package name), values are Package. This also serves
266 // as the lock for the global state. Methods that must be called with
267 // this lock held have the prefix "LP".
268 final HashMap<String, PackageParser.Package> mPackages =
269 new HashMap<String, PackageParser.Package>();
270
271 final Settings mSettings;
272 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273
274 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
275 int[] mGlobalGids;
276
277 // These are the built-in uid -> permission mappings that were read from the
278 // etc/permissions.xml file.
279 final SparseArray<HashSet<String>> mSystemPermissions =
280 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 // These are the built-in shared libraries that were read from the
283 // etc/permissions.xml file.
284 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800285
Dianne Hackborn49237342009-08-27 20:08:01 -0700286 // Temporary for building the final shared libraries for an .apk.
287 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800288
Dianne Hackborn49237342009-08-27 20:08:01 -0700289 // These are the features this devices supports that were read from the
290 // etc/permissions.xml file.
291 final HashMap<String, FeatureInfo> mAvailableFeatures =
292 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 // All available activities, for your resolving pleasure.
295 final ActivityIntentResolver mActivities =
296 new ActivityIntentResolver();
297
298 // All available receivers, for your resolving pleasure.
299 final ActivityIntentResolver mReceivers =
300 new ActivityIntentResolver();
301
302 // All available services, for your resolving pleasure.
303 final ServiceIntentResolver mServices = new ServiceIntentResolver();
304
305 // Keys are String (provider class name), values are Provider.
306 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
307 new HashMap<ComponentName, PackageParser.Provider>();
308
309 // Mapping from provider base names (first directory in content URI codePath)
310 // to the provider information.
311 final HashMap<String, PackageParser.Provider> mProviders =
312 new HashMap<String, PackageParser.Provider>();
313
314 // Mapping from instrumentation class names to info about them.
315 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
316 new HashMap<ComponentName, PackageParser.Instrumentation>();
317
318 // Mapping from permission names to info about them.
319 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
320 new HashMap<String, PackageParser.PermissionGroup>();
321
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800322 // Packages whose data we have transfered into another package, thus
323 // should no longer exist.
324 final HashSet<String> mTransferedPackages = new HashSet<String>();
325
Dianne Hackborn854060af2009-07-09 18:14:31 -0700326 // Broadcast actions that are only available to the system.
327 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 boolean mSystemReady;
330 boolean mSafeMode;
331 boolean mHasSystemUidErrors;
332
333 ApplicationInfo mAndroidApplication;
334 final ActivityInfo mResolveActivity = new ActivityInfo();
335 final ResolveInfo mResolveInfo = new ResolveInfo();
336 ComponentName mResolveComponentName;
337 PackageParser.Package mPlatformPackage;
338
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700339 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800340 final HashMap<String, ArrayList<String>> mPendingBroadcasts
341 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800342 // Service Connection to remote media container service to copy
343 // package uri's from external media onto secure containers
344 // or internal storage.
345 private IMediaContainerService mContainerService = null;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800348 static final int MCS_BOUND = 3;
349 static final int END_COPY = 4;
350 static final int INIT_COPY = 5;
351 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800352 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800353 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800354 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800355 static final int MCS_RECONNECT = 10;
356 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700357 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700358 static final int WRITE_SETTINGS = 13;
359
360 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800361
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700362 // Delay time in millisecs
363 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800364 final private DefaultContainerConnection mDefContainerConn =
365 new DefaultContainerConnection();
366 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800367 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800368 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800369 IMediaContainerService imcs =
370 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800371 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800372 }
373
374 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 }
377 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378
Christopher Tate1bb69062010-02-19 17:02:12 -0800379 // Recordkeeping of restore-after-install operations that are currently in flight
380 // between the Package Manager and the Backup Manager
381 class PostInstallData {
382 public InstallArgs args;
383 public PackageInstalledInfo res;
384
385 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
386 args = _a;
387 res = _r;
388 }
389 };
390 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
391 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
392
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700393 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800394 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800395 final ArrayList<HandlerParams> mPendingInstalls =
396 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397
398 private boolean connectToService() {
399 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
400 " DefaultContainerService");
401 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700402 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800403 if (mContext.bindService(service, mDefContainerConn,
404 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406 mBound = true;
407 return true;
408 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 return false;
411 }
412
413 private void disconnectService() {
414 mContainerService = null;
415 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700416 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800417 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800419 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800420
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 PackageHandler(Looper looper) {
422 super(looper);
423 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700424
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700425 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700426 try {
427 doHandleMessage(msg);
428 } finally {
429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
430 }
431 }
432
433 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700434 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800435 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800436 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800437 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800438 int idx = mPendingInstalls.size();
439 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
440 // If a bind was already initiated we dont really
441 // need to do anything. The pending install
442 // will be processed later on.
443 if (!mBound) {
444 // If this is the only one pending we might
445 // have to bind to the service again.
446 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800447 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800448 params.serviceError();
449 return;
450 } else {
451 // Once we bind to the service, the first
452 // pending request will be processed.
453 mPendingInstalls.add(idx, params);
454 }
455 } else {
456 mPendingInstalls.add(idx, params);
457 // Already bound to the service. Just make
458 // sure we trigger off processing the first request.
459 if (idx == 0) {
460 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800461 }
462 }
463 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800464 }
465 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800466 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800467 if (msg.obj != null) {
468 mContainerService = (IMediaContainerService) msg.obj;
469 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (mContainerService == null) {
471 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800472 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800473 for (HandlerParams params : mPendingInstalls) {
474 mPendingInstalls.remove(0);
475 // Indicate service bind error
476 params.serviceError();
477 }
478 mPendingInstalls.clear();
479 } else if (mPendingInstalls.size() > 0) {
480 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800481 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800482 params.startCopy();
483 }
484 } else {
485 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800486 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 }
488 break;
489 }
490 case MCS_RECONNECT : {
491 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
492 if (mPendingInstalls.size() > 0) {
493 if (mBound) {
494 disconnectService();
495 }
496 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800497 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800498 for (HandlerParams params : mPendingInstalls) {
499 mPendingInstalls.remove(0);
500 // Indicate service bind error
501 params.serviceError();
502 }
503 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800504 }
505 }
506 break;
507 }
508 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800509 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
510 // Delete pending install
511 if (mPendingInstalls.size() > 0) {
512 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800513 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800514 if (mPendingInstalls.size() == 0) {
515 if (mBound) {
516 disconnectService();
517 }
518 } else {
519 // There are more pending requests in queue.
520 // Just post MCS_BOUND message to trigger processing
521 // of next pending install.
522 mHandler.sendEmptyMessage(MCS_BOUND);
523 }
524 break;
525 }
526 case MCS_GIVE_UP: {
527 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
528 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800529 break;
530 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800532 String packages[];
533 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700534 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700536 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800538 if (mPendingBroadcasts == null) {
539 return;
540 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 size = mPendingBroadcasts.size();
542 if (size <= 0) {
543 // Nothing to be done. Just return
544 return;
545 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800546 packages = new String[size];
547 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700548 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800549 Iterator<HashMap.Entry<String, ArrayList<String>>>
550 it = mPendingBroadcasts.entrySet().iterator();
551 int i = 0;
552 while (it.hasNext() && i < size) {
553 HashMap.Entry<String, ArrayList<String>> ent = it.next();
554 packages[i] = ent.getKey();
555 components[i] = ent.getValue();
556 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700557 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800558 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700559 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800560 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700561 mPendingBroadcasts.clear();
562 }
563 // Send broadcasts
564 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800565 sendPackageChangedBroadcast(packages[i], true,
566 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700567 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700569 break;
570 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800571 case START_CLEANING_PACKAGE: {
572 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800574 synchronized (mPackages) {
575 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
576 mSettings.mPackagesToBeCleaned.add(packageName);
577 }
578 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800580 startCleaningPackages();
581 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800582 case POST_INSTALL: {
583 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
584 PostInstallData data = mRunningInstalls.get(msg.arg1);
585 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700586 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800587
588 if (data != null) {
589 InstallArgs args = data.args;
590 PackageInstalledInfo res = data.res;
591
592 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700593 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 Bundle extras = new Bundle(1);
595 extras.putInt(Intent.EXTRA_UID, res.uid);
596 final boolean update = res.removedInfo.removedPackage != null;
597 if (update) {
598 extras.putBoolean(Intent.EXTRA_REPLACING, true);
599 }
600 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
601 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700602 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800603 if (update) {
604 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
605 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700606 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800607 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700608 if (res.removedInfo.args != null) {
609 // Remove the replaced package's older resources safely now
610 deleteOld = true;
611 }
612 }
613 // Force a gc to clear up things
614 Runtime.getRuntime().gc();
615 // We delete after a gc for applications on sdcard.
616 if (deleteOld) {
617 synchronized (mInstallLock) {
618 res.removedInfo.args.doPostDeleteLI(true);
619 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800620 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800621 if (args.observer != null) {
622 try {
623 args.observer.packageInstalled(res.name, res.returnCode);
624 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800625 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800626 }
627 }
628 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800629 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800630 }
631 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700632 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700633 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
634 boolean reportStatus = msg.arg1 == 1;
635 boolean doGc = msg.arg2 == 1;
636 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
637 if (doGc) {
638 // Force a gc to clear up stale containers.
639 Runtime.getRuntime().gc();
640 }
641 if (msg.obj != null) {
642 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
644 // Unload containers
645 unloadAllContainers(args);
646 }
647 if (reportStatus) {
648 try {
649 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
650 PackageHelper.getMountService().finishMediaUpdate();
651 } catch (RemoteException e) {
652 Log.e(TAG, "MountService not running?");
653 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700654 }
655 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700656 case WRITE_SETTINGS: {
657 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
658 synchronized (mPackages) {
659 removeMessages(WRITE_SETTINGS);
660 mSettings.writeLP();
661 }
662 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
663 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700664 }
665 }
666 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800667
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700668 void scheduleWriteSettingsLocked() {
669 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
670 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
671 }
672 }
673
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800674 static boolean installOnSd(int flags) {
675 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700676 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800677 return false;
678 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700679 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
680 return true;
681 }
682 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800683 }
684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 public static final IPackageManager main(Context context, boolean factoryTest) {
686 PackageManagerService m = new PackageManagerService(context, factoryTest);
687 ServiceManager.addService("package", m);
688 return m;
689 }
690
691 static String[] splitString(String str, char sep) {
692 int count = 1;
693 int i = 0;
694 while ((i=str.indexOf(sep, i)) >= 0) {
695 count++;
696 i++;
697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 String[] res = new String[count];
700 i=0;
701 count = 0;
702 int lastI=0;
703 while ((i=str.indexOf(sep, i)) >= 0) {
704 res[count] = str.substring(lastI, i);
705 count++;
706 i++;
707 lastI = i;
708 }
709 res[count] = str.substring(lastI, str.length());
710 return res;
711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800718 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 mContext = context;
722 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700723 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 mMetrics = new DisplayMetrics();
725 mSettings = new Settings();
726 mSettings.addSharedUserLP("android.uid.system",
727 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
728 mSettings.addSharedUserLP("android.uid.phone",
729 MULTIPLE_APPLICATION_UIDS
730 ? RADIO_UID : FIRST_APPLICATION_UID,
731 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400732 mSettings.addSharedUserLP("android.uid.log",
733 MULTIPLE_APPLICATION_UIDS
734 ? LOG_UID : FIRST_APPLICATION_UID,
735 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736
737 String separateProcesses = SystemProperties.get("debug.separate_processes");
738 if (separateProcesses != null && separateProcesses.length() > 0) {
739 if ("*".equals(separateProcesses)) {
740 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
741 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800742 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 } else {
744 mDefParseFlags = 0;
745 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800746 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 + separateProcesses);
748 }
749 } else {
750 mDefParseFlags = 0;
751 mSeparateProcesses = null;
752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 Installer installer = new Installer();
755 // Little hacky thing to check if installd is here, to determine
756 // whether we are running on the simulator and thus need to take
757 // care of building the /data file structure ourself.
758 // (apparently the sim now has a working installer)
759 if (installer.ping() && Process.supportsProcesses()) {
760 mInstaller = installer;
761 } else {
762 mInstaller = null;
763 }
764
765 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
766 Display d = wm.getDefaultDisplay();
767 d.getMetrics(mMetrics);
768
769 synchronized (mInstallLock) {
770 synchronized (mPackages) {
771 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700772 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 File dataDir = Environment.getDataDirectory();
775 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800776 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
778
779 if (mInstaller == null) {
780 // Make sure these dirs exist, when we are running in
781 // the simulator.
782 // Make a wide-open directory for random misc stuff.
783 File miscDir = new File(dataDir, "misc");
784 miscDir.mkdirs();
785 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800786 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 mDrmAppPrivateInstallDir.mkdirs();
788 }
789
790 readPermissions();
791
792 mRestoredSettings = mSettings.readLP();
793 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800794
795 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800798 // Set flag to monitor and not change apk file paths when
799 // scanning install directories.
800 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700801 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800802 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800803 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700804 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700809 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700812 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 /**
815 * Out of paranoia, ensure that everything in the boot class
816 * path has been dexed.
817 */
818 String bootClassPath = System.getProperty("java.boot.class.path");
819 if (bootClassPath != null) {
820 String[] paths = splitString(bootClassPath, ':');
821 for (int i=0; i<paths.length; i++) {
822 try {
823 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
824 libFiles.add(paths[i]);
825 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700826 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 }
828 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800829 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800831 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833 }
834 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800835 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 /**
839 * Also ensure all external libraries have had dexopt run on them.
840 */
841 if (mSharedLibraries.size() > 0) {
842 Iterator<String> libs = mSharedLibraries.values().iterator();
843 while (libs.hasNext()) {
844 String lib = libs.next();
845 try {
846 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
847 libFiles.add(lib);
848 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700849 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
851 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800852 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800854 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 }
857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 // Gross hack for now: we know this file doesn't contain any
860 // code, so don't dexopt it to avoid the resulting log spew.
861 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 /**
864 * And there are a number of commands implemented in Java, which
865 * we currently need to do the dexopt on so that they can be
866 * run from a non-root shell.
867 */
868 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700869 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 for (int i=0; i<frameworkFiles.length; i++) {
871 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
872 String path = libPath.getPath();
873 // Skip the file if we alrady did it.
874 if (libFiles.contains(path)) {
875 continue;
876 }
877 // Skip the file if it is not a type we want to dexopt.
878 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
879 continue;
880 }
881 try {
882 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
883 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700884 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800887 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800889 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
891 }
892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700894 if (didDexOpt) {
895 // If we had to do a dexopt of one of the previous
896 // things, then something on the system has changed.
897 // Consider this significant, and wipe away all other
898 // existing dexopt files to ensure we don't leave any
899 // dangling around.
900 String[] files = mDalvikCacheDir.list();
901 if (files != null) {
902 for (int i=0; i<files.length; i++) {
903 String fn = files[i];
904 if (fn.startsWith("data@app@")
905 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800906 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700907 (new File(mDalvikCacheDir, fn)).delete();
908 }
909 }
910 }
911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800913
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800914 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 mFrameworkInstallObserver = new AppDirObserver(
916 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
917 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700918 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
919 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800920 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800921
922 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
924 mSystemInstallObserver = new AppDirObserver(
925 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
926 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700927 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
928 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800929
930 if (mInstaller != null) {
931 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
932 mInstaller.moveFiles();
933 }
934
935 // Prune any system packages that no longer exist.
936 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
937 while (psit.hasNext()) {
938 PackageSetting ps = psit.next();
939 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800940 && !mPackages.containsKey(ps.name)
941 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800942 psit.remove();
943 String msg = "System package " + ps.name
944 + " no longer exists; wiping its data";
945 reportSettingsProblem(Log.WARN, msg);
946 if (mInstaller != null) {
947 // XXX how to set useEncryptedFSDir for packages that
948 // are not encrypted?
949 mInstaller.remove(ps.name, true);
950 }
951 }
952 }
953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 mAppInstallDir = new File(dataDir, "app");
955 if (mInstaller == null) {
956 // Make sure these dirs exist, when we are running in
957 // the simulator.
958 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
959 }
960 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800961 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 //clean up list
963 for(int i = 0; i < deletePkgsList.size(); i++) {
964 //clean up here
965 cleanupInstallFailedPackage(deletePkgsList.get(i));
966 }
967 //delete tmp files
968 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800969
970 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 SystemClock.uptimeMillis());
972 mAppInstallObserver = new AppDirObserver(
973 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
974 mAppInstallObserver.startWatching();
975 scanDirLI(mAppInstallDir, 0, scanMode);
976
977 mDrmAppInstallObserver = new AppDirObserver(
978 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
979 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800980 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800984 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 + ((SystemClock.uptimeMillis()-startTime)/1000f)
986 + " seconds");
987
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700988 // If the platform SDK has changed since the last time we booted,
989 // we need to re-grant app permission to catch any new ones that
990 // appear. This is really a hack, and means that apps can in some
991 // cases get permissions that the user didn't initially explicitly
992 // allow... it would be nice to have some better way to handle
993 // this situation.
994 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
995 != mSdkVersion;
996 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
997 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
998 + "; regranting permissions for internal storage");
999 mSettings.mInternalSdkPlatform = mSdkVersion;
1000
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001001 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002
1003 mSettings.writeLP();
1004
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001005 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 // Now after opening every single application zip, make sure they
1009 // are all flushed. Not really needed, but keeps things nice and
1010 // tidy.
1011 Runtime.getRuntime().gc();
1012 } // synchronized (mPackages)
1013 } // synchronized (mInstallLock)
1014 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 @Override
1017 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1018 throws RemoteException {
1019 try {
1020 return super.onTransact(code, data, reply, flags);
1021 } catch (RuntimeException e) {
1022 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001023 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025 throw e;
1026 }
1027 }
1028
Dianne Hackborne6620b22010-01-22 14:46:21 -08001029 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001030 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001032 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1033 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001035 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001036 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038 } else {
1039 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001040 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 File dataDir = new File(pkg.applicationInfo.dataDir);
1042 dataDir.delete();
1043 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001044 if (ps.codePath != null) {
1045 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001046 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001047 }
1048 }
1049 if (ps.resourcePath != null) {
1050 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001052 }
1053 }
1054 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
1056
1057 void readPermissions() {
1058 // Read permissions from .../etc/permission directory.
1059 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1060 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001061 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 return;
1063 }
1064 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001065 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 return;
1067 }
1068
1069 // Iterate over the files in the directory and scan .xml files
1070 for (File f : libraryDir.listFiles()) {
1071 // We'll read platform.xml last
1072 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1073 continue;
1074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001077 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 continue;
1079 }
1080 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001081 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 continue;
1083 }
1084
1085 readPermissionsFromXml(f);
1086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1089 final File permFile = new File(Environment.getRootDirectory(),
1090 "etc/permissions/platform.xml");
1091 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001093 StringBuilder sb = new StringBuilder(128);
1094 sb.append("Libs:");
1095 Iterator<String> it = mSharedLibraries.keySet().iterator();
1096 while (it.hasNext()) {
1097 sb.append(' ');
1098 String name = it.next();
1099 sb.append(name);
1100 sb.append(':');
1101 sb.append(mSharedLibraries.get(name));
1102 }
1103 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001104
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001105 sb.setLength(0);
1106 sb.append("Features:");
1107 it = mAvailableFeatures.keySet().iterator();
1108 while (it.hasNext()) {
1109 sb.append(' ');
1110 sb.append(it.next());
1111 }
1112 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
1115 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 FileReader permReader = null;
1117 try {
1118 permReader = new FileReader(permFile);
1119 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001120 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 return;
1122 }
1123
1124 try {
1125 XmlPullParser parser = Xml.newPullParser();
1126 parser.setInput(permReader);
1127
1128 XmlUtils.beginDocument(parser, "permissions");
1129
1130 while (true) {
1131 XmlUtils.nextElement(parser);
1132 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1133 break;
1134 }
1135
1136 String name = parser.getName();
1137 if ("group".equals(name)) {
1138 String gidStr = parser.getAttributeValue(null, "gid");
1139 if (gidStr != null) {
1140 int gid = Integer.parseInt(gidStr);
1141 mGlobalGids = appendInt(mGlobalGids, gid);
1142 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + parser.getPositionDescription());
1145 }
1146
1147 XmlUtils.skipCurrentTag(parser);
1148 continue;
1149 } else if ("permission".equals(name)) {
1150 String perm = parser.getAttributeValue(null, "name");
1151 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 + parser.getPositionDescription());
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157 perm = perm.intern();
1158 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 } else if ("assign-permission".equals(name)) {
1161 String perm = parser.getAttributeValue(null, "name");
1162 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001163 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 + parser.getPositionDescription());
1165 XmlUtils.skipCurrentTag(parser);
1166 continue;
1167 }
1168 String uidStr = parser.getAttributeValue(null, "uid");
1169 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001170 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 + parser.getPositionDescription());
1172 XmlUtils.skipCurrentTag(parser);
1173 continue;
1174 }
1175 int uid = Process.getUidForName(uidStr);
1176 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 + uidStr + "\" at "
1179 + parser.getPositionDescription());
1180 XmlUtils.skipCurrentTag(parser);
1181 continue;
1182 }
1183 perm = perm.intern();
1184 HashSet<String> perms = mSystemPermissions.get(uid);
1185 if (perms == null) {
1186 perms = new HashSet<String>();
1187 mSystemPermissions.put(uid, perms);
1188 }
1189 perms.add(perm);
1190 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 } else if ("library".equals(name)) {
1193 String lname = parser.getAttributeValue(null, "name");
1194 String lfile = parser.getAttributeValue(null, "file");
1195 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001196 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 + parser.getPositionDescription());
1198 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 + parser.getPositionDescription());
1201 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001202 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 mSharedLibraries.put(lname, lfile);
1204 }
1205 XmlUtils.skipCurrentTag(parser);
1206 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001207
Dianne Hackborn49237342009-08-27 20:08:01 -07001208 } else if ("feature".equals(name)) {
1209 String fname = parser.getAttributeValue(null, "name");
1210 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001211 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001212 + parser.getPositionDescription());
1213 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001214 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 FeatureInfo fi = new FeatureInfo();
1216 fi.name = fname;
1217 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219 XmlUtils.skipCurrentTag(parser);
1220 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } else {
1223 XmlUtils.skipCurrentTag(parser);
1224 continue;
1225 }
1226
1227 }
1228 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001229 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001231 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
1234
1235 void readPermission(XmlPullParser parser, String name)
1236 throws IOException, XmlPullParserException {
1237
1238 name = name.intern();
1239
1240 BasePermission bp = mSettings.mPermissions.get(name);
1241 if (bp == null) {
1242 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1243 mSettings.mPermissions.put(name, bp);
1244 }
1245 int outerDepth = parser.getDepth();
1246 int type;
1247 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1248 && (type != XmlPullParser.END_TAG
1249 || parser.getDepth() > outerDepth)) {
1250 if (type == XmlPullParser.END_TAG
1251 || type == XmlPullParser.TEXT) {
1252 continue;
1253 }
1254
1255 String tagName = parser.getName();
1256 if ("group".equals(tagName)) {
1257 String gidStr = parser.getAttributeValue(null, "gid");
1258 if (gidStr != null) {
1259 int gid = Process.getGidForName(gidStr);
1260 bp.gids = appendInt(bp.gids, gid);
1261 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001262 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 + parser.getPositionDescription());
1264 }
1265 }
1266 XmlUtils.skipCurrentTag(parser);
1267 }
1268 }
1269
1270 static int[] appendInt(int[] cur, int val) {
1271 if (cur == null) {
1272 return new int[] { val };
1273 }
1274 final int N = cur.length;
1275 for (int i=0; i<N; i++) {
1276 if (cur[i] == val) {
1277 return cur;
1278 }
1279 }
1280 int[] ret = new int[N+1];
1281 System.arraycopy(cur, 0, ret, 0, N);
1282 ret[N] = val;
1283 return ret;
1284 }
1285
1286 static int[] appendInts(int[] cur, int[] add) {
1287 if (add == null) return cur;
1288 if (cur == null) return add;
1289 final int N = add.length;
1290 for (int i=0; i<N; i++) {
1291 cur = appendInt(cur, add[i]);
1292 }
1293 return cur;
1294 }
1295
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001296 static int[] removeInt(int[] cur, int val) {
1297 if (cur == null) {
1298 return null;
1299 }
1300 final int N = cur.length;
1301 for (int i=0; i<N; i++) {
1302 if (cur[i] == val) {
1303 int[] ret = new int[N-1];
1304 if (i > 0) {
1305 System.arraycopy(cur, 0, ret, 0, i);
1306 }
1307 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001308 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001309 }
1310 return ret;
1311 }
1312 }
1313 return cur;
1314 }
1315
1316 static int[] removeInts(int[] cur, int[] rem) {
1317 if (rem == null) return cur;
1318 if (cur == null) return cur;
1319 final int N = rem.length;
1320 for (int i=0; i<N; i++) {
1321 cur = removeInt(cur, rem[i]);
1322 }
1323 return cur;
1324 }
1325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001327 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1328 // The package has been uninstalled but has retained data and resources.
1329 return PackageParser.generatePackageInfo(p, null, flags);
1330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 final PackageSetting ps = (PackageSetting)p.mExtras;
1332 if (ps == null) {
1333 return null;
1334 }
1335 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1336 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1337 }
1338
1339 public PackageInfo getPackageInfo(String packageName, int flags) {
1340 synchronized (mPackages) {
1341 PackageParser.Package p = mPackages.get(packageName);
1342 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001343 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 + ": " + p);
1345 if (p != null) {
1346 return generatePackageInfo(p, flags);
1347 }
1348 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1349 return generatePackageInfoFromSettingsLP(packageName, flags);
1350 }
1351 }
1352 return null;
1353 }
1354
Dianne Hackborn47096932010-02-11 15:57:09 -08001355 public String[] currentToCanonicalPackageNames(String[] names) {
1356 String[] out = new String[names.length];
1357 synchronized (mPackages) {
1358 for (int i=names.length-1; i>=0; i--) {
1359 PackageSetting ps = mSettings.mPackages.get(names[i]);
1360 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1361 }
1362 }
1363 return out;
1364 }
1365
1366 public String[] canonicalToCurrentPackageNames(String[] names) {
1367 String[] out = new String[names.length];
1368 synchronized (mPackages) {
1369 for (int i=names.length-1; i>=0; i--) {
1370 String cur = mSettings.mRenamedPackages.get(names[i]);
1371 out[i] = cur != null ? cur : names[i];
1372 }
1373 }
1374 return out;
1375 }
1376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 public int getPackageUid(String packageName) {
1378 synchronized (mPackages) {
1379 PackageParser.Package p = mPackages.get(packageName);
1380 if(p != null) {
1381 return p.applicationInfo.uid;
1382 }
1383 PackageSetting ps = mSettings.mPackages.get(packageName);
1384 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1385 return -1;
1386 }
1387 p = ps.pkg;
1388 return p != null ? p.applicationInfo.uid : -1;
1389 }
1390 }
1391
1392 public int[] getPackageGids(String packageName) {
1393 synchronized (mPackages) {
1394 PackageParser.Package p = mPackages.get(packageName);
1395 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001396 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 + ": " + p);
1398 if (p != null) {
1399 final PackageSetting ps = (PackageSetting)p.mExtras;
1400 final SharedUserSetting suid = ps.sharedUser;
1401 return suid != null ? suid.gids : ps.gids;
1402 }
1403 }
1404 // stupid thing to indicate an error.
1405 return new int[0];
1406 }
1407
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001408 static final PermissionInfo generatePermissionInfo(
1409 BasePermission bp, int flags) {
1410 if (bp.perm != null) {
1411 return PackageParser.generatePermissionInfo(bp.perm, flags);
1412 }
1413 PermissionInfo pi = new PermissionInfo();
1414 pi.name = bp.name;
1415 pi.packageName = bp.sourcePackage;
1416 pi.nonLocalizedLabel = bp.name;
1417 pi.protectionLevel = bp.protectionLevel;
1418 return pi;
1419 }
1420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 public PermissionInfo getPermissionInfo(String name, int flags) {
1422 synchronized (mPackages) {
1423 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001424 if (p != null) {
1425 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427 return null;
1428 }
1429 }
1430
1431 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1432 synchronized (mPackages) {
1433 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1434 for (BasePermission p : mSettings.mPermissions.values()) {
1435 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001436 if (p.perm == null || p.perm.info.group == null) {
1437 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001440 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1442 }
1443 }
1444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 if (out.size() > 0) {
1447 return out;
1448 }
1449 return mPermissionGroups.containsKey(group) ? out : null;
1450 }
1451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1454 synchronized (mPackages) {
1455 return PackageParser.generatePermissionGroupInfo(
1456 mPermissionGroups.get(name), flags);
1457 }
1458 }
1459
1460 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1461 synchronized (mPackages) {
1462 final int N = mPermissionGroups.size();
1463 ArrayList<PermissionGroupInfo> out
1464 = new ArrayList<PermissionGroupInfo>(N);
1465 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1466 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1467 }
1468 return out;
1469 }
1470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1473 PackageSetting ps = mSettings.mPackages.get(packageName);
1474 if(ps != null) {
1475 if(ps.pkg == null) {
1476 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1477 if(pInfo != null) {
1478 return pInfo.applicationInfo;
1479 }
1480 return null;
1481 }
1482 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1483 }
1484 return null;
1485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1488 PackageSetting ps = mSettings.mPackages.get(packageName);
1489 if(ps != null) {
1490 if(ps.pkg == null) {
1491 ps.pkg = new PackageParser.Package(packageName);
1492 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001493 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1494 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1495 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1496 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001497 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001498 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500 return generatePackageInfo(ps.pkg, flags);
1501 }
1502 return null;
1503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1506 synchronized (mPackages) {
1507 PackageParser.Package p = mPackages.get(packageName);
1508 if (Config.LOGV) Log.v(
1509 TAG, "getApplicationInfo " + packageName
1510 + ": " + p);
1511 if (p != null) {
1512 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001513 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
1515 if ("android".equals(packageName)||"system".equals(packageName)) {
1516 return mAndroidApplication;
1517 }
1518 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1519 return generateApplicationInfoFromSettingsLP(packageName, flags);
1520 }
1521 }
1522 return null;
1523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001524
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.CLEAR_APP_CACHE, null);
1529 // Queue up an async operation since clearing cache may take a little while.
1530 mHandler.post(new Runnable() {
1531 public void run() {
1532 mHandler.removeCallbacks(this);
1533 int retCode = -1;
1534 if (mInstaller != null) {
1535 retCode = mInstaller.freeCache(freeStorageSize);
1536 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001537 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 } //end if mInstaller
1540 if (observer != null) {
1541 try {
1542 observer.onRemoveCompleted(null, (retCode >= 0));
1543 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001544 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546 }
1547 }
1548 });
1549 }
1550
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001551 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001552 mContext.enforceCallingOrSelfPermission(
1553 android.Manifest.permission.CLEAR_APP_CACHE, null);
1554 // Queue up an async operation since clearing cache may take a little while.
1555 mHandler.post(new Runnable() {
1556 public void run() {
1557 mHandler.removeCallbacks(this);
1558 int retCode = -1;
1559 if (mInstaller != null) {
1560 retCode = mInstaller.freeCache(freeStorageSize);
1561 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001562 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001563 }
1564 }
1565 if(pi != null) {
1566 try {
1567 // Callback via pending intent
1568 int code = (retCode >= 0) ? 1 : 0;
1569 pi.sendIntent(null, code, null,
1570 null, null);
1571 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001572 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001573 }
1574 }
1575 }
1576 });
1577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1580 synchronized (mPackages) {
1581 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001582
1583 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001585 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587 if (mResolveComponentName.equals(component)) {
1588 return mResolveActivity;
1589 }
1590 }
1591 return null;
1592 }
1593
1594 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1595 synchronized (mPackages) {
1596 PackageParser.Activity a = mReceivers.mActivities.get(component);
1597 if (Config.LOGV) Log.v(
1598 TAG, "getReceiverInfo " + component + ": " + a);
1599 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1600 return PackageParser.generateActivityInfo(a, flags);
1601 }
1602 }
1603 return null;
1604 }
1605
1606 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1607 synchronized (mPackages) {
1608 PackageParser.Service s = mServices.mServices.get(component);
1609 if (Config.LOGV) Log.v(
1610 TAG, "getServiceInfo " + component + ": " + s);
1611 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1612 return PackageParser.generateServiceInfo(s, flags);
1613 }
1614 }
1615 return null;
1616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001617
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001618 public String[] getSystemSharedLibraryNames() {
1619 Set<String> libSet;
1620 synchronized (mPackages) {
1621 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001622 int size = libSet.size();
1623 if (size > 0) {
1624 String[] libs = new String[size];
1625 libSet.toArray(libs);
1626 return libs;
1627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001628 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001629 return null;
1630 }
1631
1632 public FeatureInfo[] getSystemAvailableFeatures() {
1633 Collection<FeatureInfo> featSet;
1634 synchronized (mPackages) {
1635 featSet = mAvailableFeatures.values();
1636 int size = featSet.size();
1637 if (size > 0) {
1638 FeatureInfo[] features = new FeatureInfo[size+1];
1639 featSet.toArray(features);
1640 FeatureInfo fi = new FeatureInfo();
1641 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1642 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1643 features[size] = fi;
1644 return features;
1645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001646 }
1647 return null;
1648 }
1649
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001650 public boolean hasSystemFeature(String name) {
1651 synchronized (mPackages) {
1652 return mAvailableFeatures.containsKey(name);
1653 }
1654 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 public int checkPermission(String permName, String pkgName) {
1657 synchronized (mPackages) {
1658 PackageParser.Package p = mPackages.get(pkgName);
1659 if (p != null && p.mExtras != null) {
1660 PackageSetting ps = (PackageSetting)p.mExtras;
1661 if (ps.sharedUser != null) {
1662 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1663 return PackageManager.PERMISSION_GRANTED;
1664 }
1665 } else if (ps.grantedPermissions.contains(permName)) {
1666 return PackageManager.PERMISSION_GRANTED;
1667 }
1668 }
1669 }
1670 return PackageManager.PERMISSION_DENIED;
1671 }
1672
1673 public int checkUidPermission(String permName, int uid) {
1674 synchronized (mPackages) {
1675 Object obj = mSettings.getUserIdLP(uid);
1676 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001677 GrantedPermissions gp = (GrantedPermissions)obj;
1678 if (gp.grantedPermissions.contains(permName)) {
1679 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 }
1681 } else {
1682 HashSet<String> perms = mSystemPermissions.get(uid);
1683 if (perms != null && perms.contains(permName)) {
1684 return PackageManager.PERMISSION_GRANTED;
1685 }
1686 }
1687 }
1688 return PackageManager.PERMISSION_DENIED;
1689 }
1690
1691 private BasePermission findPermissionTreeLP(String permName) {
1692 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1693 if (permName.startsWith(bp.name) &&
1694 permName.length() > bp.name.length() &&
1695 permName.charAt(bp.name.length()) == '.') {
1696 return bp;
1697 }
1698 }
1699 return null;
1700 }
1701
1702 private BasePermission checkPermissionTreeLP(String permName) {
1703 if (permName != null) {
1704 BasePermission bp = findPermissionTreeLP(permName);
1705 if (bp != null) {
1706 if (bp.uid == Binder.getCallingUid()) {
1707 return bp;
1708 }
1709 throw new SecurityException("Calling uid "
1710 + Binder.getCallingUid()
1711 + " is not allowed to add to permission tree "
1712 + bp.name + " owned by uid " + bp.uid);
1713 }
1714 }
1715 throw new SecurityException("No permission tree found for " + permName);
1716 }
1717
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001718 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1719 if (s1 == null) {
1720 return s2 == null;
1721 }
1722 if (s2 == null) {
1723 return false;
1724 }
1725 if (s1.getClass() != s2.getClass()) {
1726 return false;
1727 }
1728 return s1.equals(s2);
1729 }
1730
1731 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1732 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001733 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001734 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1735 if (!compareStrings(pi1.name, pi2.name)) return false;
1736 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1737 // We'll take care of setting this one.
1738 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1739 // These are not currently stored in settings.
1740 //if (!compareStrings(pi1.group, pi2.group)) return false;
1741 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1742 //if (pi1.labelRes != pi2.labelRes) return false;
1743 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1744 return true;
1745 }
1746
1747 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1748 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1749 throw new SecurityException("Label must be specified in permission");
1750 }
1751 BasePermission tree = checkPermissionTreeLP(info.name);
1752 BasePermission bp = mSettings.mPermissions.get(info.name);
1753 boolean added = bp == null;
1754 boolean changed = true;
1755 if (added) {
1756 bp = new BasePermission(info.name, tree.sourcePackage,
1757 BasePermission.TYPE_DYNAMIC);
1758 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1759 throw new SecurityException(
1760 "Not allowed to modify non-dynamic permission "
1761 + info.name);
1762 } else {
1763 if (bp.protectionLevel == info.protectionLevel
1764 && bp.perm.owner.equals(tree.perm.owner)
1765 && bp.uid == tree.uid
1766 && comparePermissionInfos(bp.perm.info, info)) {
1767 changed = false;
1768 }
1769 }
1770 bp.protectionLevel = info.protectionLevel;
1771 bp.perm = new PackageParser.Permission(tree.perm.owner,
1772 new PermissionInfo(info));
1773 bp.perm.info.packageName = tree.perm.info.packageName;
1774 bp.uid = tree.uid;
1775 if (added) {
1776 mSettings.mPermissions.put(info.name, bp);
1777 }
1778 if (changed) {
1779 if (!async) {
1780 mSettings.writeLP();
1781 } else {
1782 scheduleWriteSettingsLocked();
1783 }
1784 }
1785 return added;
1786 }
1787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 public boolean addPermission(PermissionInfo info) {
1789 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001790 return addPermissionLocked(info, false);
1791 }
1792 }
1793
1794 public boolean addPermissionAsync(PermissionInfo info) {
1795 synchronized (mPackages) {
1796 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798 }
1799
1800 public void removePermission(String name) {
1801 synchronized (mPackages) {
1802 checkPermissionTreeLP(name);
1803 BasePermission bp = mSettings.mPermissions.get(name);
1804 if (bp != null) {
1805 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1806 throw new SecurityException(
1807 "Not allowed to modify non-dynamic permission "
1808 + name);
1809 }
1810 mSettings.mPermissions.remove(name);
1811 mSettings.writeLP();
1812 }
1813 }
1814 }
1815
Dianne Hackborn854060af2009-07-09 18:14:31 -07001816 public boolean isProtectedBroadcast(String actionName) {
1817 synchronized (mPackages) {
1818 return mProtectedBroadcasts.contains(actionName);
1819 }
1820 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 public int checkSignatures(String pkg1, String pkg2) {
1823 synchronized (mPackages) {
1824 PackageParser.Package p1 = mPackages.get(pkg1);
1825 PackageParser.Package p2 = mPackages.get(pkg2);
1826 if (p1 == null || p1.mExtras == null
1827 || p2 == null || p2.mExtras == null) {
1828 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1829 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001830 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 }
1832 }
1833
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001834 public int checkUidSignatures(int uid1, int uid2) {
1835 synchronized (mPackages) {
1836 Signature[] s1;
1837 Signature[] s2;
1838 Object obj = mSettings.getUserIdLP(uid1);
1839 if (obj != null) {
1840 if (obj instanceof SharedUserSetting) {
1841 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1842 } else if (obj instanceof PackageSetting) {
1843 s1 = ((PackageSetting)obj).signatures.mSignatures;
1844 } else {
1845 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1846 }
1847 } else {
1848 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1849 }
1850 obj = mSettings.getUserIdLP(uid2);
1851 if (obj != null) {
1852 if (obj instanceof SharedUserSetting) {
1853 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1854 } else if (obj instanceof PackageSetting) {
1855 s2 = ((PackageSetting)obj).signatures.mSignatures;
1856 } else {
1857 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1858 }
1859 } else {
1860 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1861 }
1862 return checkSignaturesLP(s1, s2);
1863 }
1864 }
1865
1866 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1867 if (s1 == null) {
1868 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1870 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1871 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001872 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1874 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001875 HashSet<Signature> set1 = new HashSet<Signature>();
1876 for (Signature sig : s1) {
1877 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001879 HashSet<Signature> set2 = new HashSet<Signature>();
1880 for (Signature sig : s2) {
1881 set2.add(sig);
1882 }
1883 // Make sure s2 contains all signatures in s1.
1884 if (set1.equals(set2)) {
1885 return PackageManager.SIGNATURE_MATCH;
1886 }
1887 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 }
1889
1890 public String[] getPackagesForUid(int uid) {
1891 synchronized (mPackages) {
1892 Object obj = mSettings.getUserIdLP(uid);
1893 if (obj instanceof SharedUserSetting) {
1894 SharedUserSetting sus = (SharedUserSetting)obj;
1895 final int N = sus.packages.size();
1896 String[] res = new String[N];
1897 Iterator<PackageSetting> it = sus.packages.iterator();
1898 int i=0;
1899 while (it.hasNext()) {
1900 res[i++] = it.next().name;
1901 }
1902 return res;
1903 } else if (obj instanceof PackageSetting) {
1904 PackageSetting ps = (PackageSetting)obj;
1905 return new String[] { ps.name };
1906 }
1907 }
1908 return null;
1909 }
1910
1911 public String getNameForUid(int uid) {
1912 synchronized (mPackages) {
1913 Object obj = mSettings.getUserIdLP(uid);
1914 if (obj instanceof SharedUserSetting) {
1915 SharedUserSetting sus = (SharedUserSetting)obj;
1916 return sus.name + ":" + sus.userId;
1917 } else if (obj instanceof PackageSetting) {
1918 PackageSetting ps = (PackageSetting)obj;
1919 return ps.name;
1920 }
1921 }
1922 return null;
1923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001925 public int getUidForSharedUser(String sharedUserName) {
1926 if(sharedUserName == null) {
1927 return -1;
1928 }
1929 synchronized (mPackages) {
1930 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1931 if(suid == null) {
1932 return -1;
1933 }
1934 return suid.userId;
1935 }
1936 }
1937
1938 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1939 int flags) {
1940 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001941 return chooseBestActivity(intent, resolvedType, flags, query);
1942 }
1943
Mihai Predaeae850c2009-05-13 10:13:48 +02001944 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1945 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 if (query != null) {
1947 final int N = query.size();
1948 if (N == 1) {
1949 return query.get(0);
1950 } else if (N > 1) {
1951 // If there is more than one activity with the same priority,
1952 // then let the user decide between them.
1953 ResolveInfo r0 = query.get(0);
1954 ResolveInfo r1 = query.get(1);
1955 if (false) {
1956 System.out.println(r0.activityInfo.name +
1957 "=" + r0.priority + " vs " +
1958 r1.activityInfo.name +
1959 "=" + r1.priority);
1960 }
1961 // If the first activity has a higher priority, or a different
1962 // default, then it is always desireable to pick it.
1963 if (r0.priority != r1.priority
1964 || r0.preferredOrder != r1.preferredOrder
1965 || r0.isDefault != r1.isDefault) {
1966 return query.get(0);
1967 }
1968 // If we have saved a preference for a preferred activity for
1969 // this Intent, use that.
1970 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1971 flags, query, r0.priority);
1972 if (ri != null) {
1973 return ri;
1974 }
1975 return mResolveInfo;
1976 }
1977 }
1978 return null;
1979 }
1980
1981 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1982 int flags, List<ResolveInfo> query, int priority) {
1983 synchronized (mPackages) {
1984 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1985 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001986 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001987 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1988 if (prefs != null && prefs.size() > 0) {
1989 // First figure out how good the original match set is.
1990 // We will only allow preferred activities that came
1991 // from the same match quality.
1992 int match = 0;
1993 final int N = query.size();
1994 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1995 for (int j=0; j<N; j++) {
1996 ResolveInfo ri = query.get(j);
1997 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
1998 + ": 0x" + Integer.toHexString(match));
1999 if (ri.match > match) match = ri.match;
2000 }
2001 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2002 + Integer.toHexString(match));
2003 match &= IntentFilter.MATCH_CATEGORY_MASK;
2004 final int M = prefs.size();
2005 for (int i=0; i<M; i++) {
2006 PreferredActivity pa = prefs.get(i);
2007 if (pa.mMatch != match) {
2008 continue;
2009 }
2010 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2011 if (DEBUG_PREFERRED) {
2012 Log.v(TAG, "Got preferred activity:");
2013 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2014 }
2015 if (ai != null) {
2016 for (int j=0; j<N; j++) {
2017 ResolveInfo ri = query.get(j);
2018 if (!ri.activityInfo.applicationInfo.packageName
2019 .equals(ai.applicationInfo.packageName)) {
2020 continue;
2021 }
2022 if (!ri.activityInfo.name.equals(ai.name)) {
2023 continue;
2024 }
2025
2026 // Okay we found a previously set preferred app.
2027 // If the result set is different from when this
2028 // was created, we need to clear it and re-ask the
2029 // user their preference.
2030 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002031 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 + intent + " type " + resolvedType);
2033 mSettings.mPreferredActivities.removeFilter(pa);
2034 return null;
2035 }
2036
2037 // Yay!
2038 return ri;
2039 }
2040 }
2041 }
2042 }
2043 }
2044 return null;
2045 }
2046
2047 public List<ResolveInfo> queryIntentActivities(Intent intent,
2048 String resolvedType, int flags) {
2049 ComponentName comp = intent.getComponent();
2050 if (comp != null) {
2051 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2052 ActivityInfo ai = getActivityInfo(comp, flags);
2053 if (ai != null) {
2054 ResolveInfo ri = new ResolveInfo();
2055 ri.activityInfo = ai;
2056 list.add(ri);
2057 }
2058 return list;
2059 }
2060
2061 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002062 String pkgName = intent.getPackage();
2063 if (pkgName == null) {
2064 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2065 resolvedType, flags);
2066 }
2067 PackageParser.Package pkg = mPackages.get(pkgName);
2068 if (pkg != null) {
2069 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2070 resolvedType, flags, pkg.activities);
2071 }
2072 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 }
2074 }
2075
2076 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2077 Intent[] specifics, String[] specificTypes, Intent intent,
2078 String resolvedType, int flags) {
2079 final String resultsAction = intent.getAction();
2080
2081 List<ResolveInfo> results = queryIntentActivities(
2082 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2083 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2084
2085 int specificsPos = 0;
2086 int N;
2087
2088 // todo: note that the algorithm used here is O(N^2). This
2089 // isn't a problem in our current environment, but if we start running
2090 // into situations where we have more than 5 or 10 matches then this
2091 // should probably be changed to something smarter...
2092
2093 // First we go through and resolve each of the specific items
2094 // that were supplied, taking care of removing any corresponding
2095 // duplicate items in the generic resolve list.
2096 if (specifics != null) {
2097 for (int i=0; i<specifics.length; i++) {
2098 final Intent sintent = specifics[i];
2099 if (sintent == null) {
2100 continue;
2101 }
2102
2103 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2104 String action = sintent.getAction();
2105 if (resultsAction != null && resultsAction.equals(action)) {
2106 // If this action was explicitly requested, then don't
2107 // remove things that have it.
2108 action = null;
2109 }
2110 ComponentName comp = sintent.getComponent();
2111 ResolveInfo ri = null;
2112 ActivityInfo ai = null;
2113 if (comp == null) {
2114 ri = resolveIntent(
2115 sintent,
2116 specificTypes != null ? specificTypes[i] : null,
2117 flags);
2118 if (ri == null) {
2119 continue;
2120 }
2121 if (ri == mResolveInfo) {
2122 // ACK! Must do something better with this.
2123 }
2124 ai = ri.activityInfo;
2125 comp = new ComponentName(ai.applicationInfo.packageName,
2126 ai.name);
2127 } else {
2128 ai = getActivityInfo(comp, flags);
2129 if (ai == null) {
2130 continue;
2131 }
2132 }
2133
2134 // Look for any generic query activities that are duplicates
2135 // of this specific one, and remove them from the results.
2136 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2137 N = results.size();
2138 int j;
2139 for (j=specificsPos; j<N; j++) {
2140 ResolveInfo sri = results.get(j);
2141 if ((sri.activityInfo.name.equals(comp.getClassName())
2142 && sri.activityInfo.applicationInfo.packageName.equals(
2143 comp.getPackageName()))
2144 || (action != null && sri.filter.matchAction(action))) {
2145 results.remove(j);
2146 if (Config.LOGV) Log.v(
2147 TAG, "Removing duplicate item from " + j
2148 + " due to specific " + specificsPos);
2149 if (ri == null) {
2150 ri = sri;
2151 }
2152 j--;
2153 N--;
2154 }
2155 }
2156
2157 // Add this specific item to its proper place.
2158 if (ri == null) {
2159 ri = new ResolveInfo();
2160 ri.activityInfo = ai;
2161 }
2162 results.add(specificsPos, ri);
2163 ri.specificIndex = i;
2164 specificsPos++;
2165 }
2166 }
2167
2168 // Now we go through the remaining generic results and remove any
2169 // duplicate actions that are found here.
2170 N = results.size();
2171 for (int i=specificsPos; i<N-1; i++) {
2172 final ResolveInfo rii = results.get(i);
2173 if (rii.filter == null) {
2174 continue;
2175 }
2176
2177 // Iterate over all of the actions of this result's intent
2178 // filter... typically this should be just one.
2179 final Iterator<String> it = rii.filter.actionsIterator();
2180 if (it == null) {
2181 continue;
2182 }
2183 while (it.hasNext()) {
2184 final String action = it.next();
2185 if (resultsAction != null && resultsAction.equals(action)) {
2186 // If this action was explicitly requested, then don't
2187 // remove things that have it.
2188 continue;
2189 }
2190 for (int j=i+1; j<N; j++) {
2191 final ResolveInfo rij = results.get(j);
2192 if (rij.filter != null && rij.filter.hasAction(action)) {
2193 results.remove(j);
2194 if (Config.LOGV) Log.v(
2195 TAG, "Removing duplicate item from " + j
2196 + " due to action " + action + " at " + i);
2197 j--;
2198 N--;
2199 }
2200 }
2201 }
2202
2203 // If the caller didn't request filter information, drop it now
2204 // so we don't have to marshall/unmarshall it.
2205 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2206 rii.filter = null;
2207 }
2208 }
2209
2210 // Filter out the caller activity if so requested.
2211 if (caller != null) {
2212 N = results.size();
2213 for (int i=0; i<N; i++) {
2214 ActivityInfo ainfo = results.get(i).activityInfo;
2215 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2216 && caller.getClassName().equals(ainfo.name)) {
2217 results.remove(i);
2218 break;
2219 }
2220 }
2221 }
2222
2223 // If the caller didn't request filter information,
2224 // drop them now so we don't have to
2225 // marshall/unmarshall it.
2226 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2227 N = results.size();
2228 for (int i=0; i<N; i++) {
2229 results.get(i).filter = null;
2230 }
2231 }
2232
2233 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2234 return results;
2235 }
2236
2237 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2238 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002239 ComponentName comp = intent.getComponent();
2240 if (comp != null) {
2241 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2242 ActivityInfo ai = getReceiverInfo(comp, flags);
2243 if (ai != null) {
2244 ResolveInfo ri = new ResolveInfo();
2245 ri.activityInfo = ai;
2246 list.add(ri);
2247 }
2248 return list;
2249 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002252 String pkgName = intent.getPackage();
2253 if (pkgName == null) {
2254 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2255 resolvedType, flags);
2256 }
2257 PackageParser.Package pkg = mPackages.get(pkgName);
2258 if (pkg != null) {
2259 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2260 resolvedType, flags, pkg.receivers);
2261 }
2262 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 }
2264 }
2265
2266 public ResolveInfo resolveService(Intent intent, String resolvedType,
2267 int flags) {
2268 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2269 flags);
2270 if (query != null) {
2271 if (query.size() >= 1) {
2272 // If there is more than one service with the same priority,
2273 // just arbitrarily pick the first one.
2274 return query.get(0);
2275 }
2276 }
2277 return null;
2278 }
2279
2280 public List<ResolveInfo> queryIntentServices(Intent intent,
2281 String resolvedType, int flags) {
2282 ComponentName comp = intent.getComponent();
2283 if (comp != null) {
2284 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2285 ServiceInfo si = getServiceInfo(comp, flags);
2286 if (si != null) {
2287 ResolveInfo ri = new ResolveInfo();
2288 ri.serviceInfo = si;
2289 list.add(ri);
2290 }
2291 return list;
2292 }
2293
2294 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002295 String pkgName = intent.getPackage();
2296 if (pkgName == null) {
2297 return (List<ResolveInfo>)mServices.queryIntent(intent,
2298 resolvedType, flags);
2299 }
2300 PackageParser.Package pkg = mPackages.get(pkgName);
2301 if (pkg != null) {
2302 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2303 resolvedType, flags, pkg.services);
2304 }
2305 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306 }
2307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 public List<PackageInfo> getInstalledPackages(int flags) {
2310 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2311
2312 synchronized (mPackages) {
2313 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2314 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2315 while (i.hasNext()) {
2316 final PackageSetting ps = i.next();
2317 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2318 if(psPkg != null) {
2319 finalList.add(psPkg);
2320 }
2321 }
2322 }
2323 else {
2324 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2325 while (i.hasNext()) {
2326 final PackageParser.Package p = i.next();
2327 if (p.applicationInfo != null) {
2328 PackageInfo pi = generatePackageInfo(p, flags);
2329 if(pi != null) {
2330 finalList.add(pi);
2331 }
2332 }
2333 }
2334 }
2335 }
2336 return finalList;
2337 }
2338
2339 public List<ApplicationInfo> getInstalledApplications(int flags) {
2340 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2341 synchronized(mPackages) {
2342 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2343 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2344 while (i.hasNext()) {
2345 final PackageSetting ps = i.next();
2346 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2347 if(ai != null) {
2348 finalList.add(ai);
2349 }
2350 }
2351 }
2352 else {
2353 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2354 while (i.hasNext()) {
2355 final PackageParser.Package p = i.next();
2356 if (p.applicationInfo != null) {
2357 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2358 if(ai != null) {
2359 finalList.add(ai);
2360 }
2361 }
2362 }
2363 }
2364 }
2365 return finalList;
2366 }
2367
2368 public List<ApplicationInfo> getPersistentApplications(int flags) {
2369 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2370
2371 synchronized (mPackages) {
2372 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2373 while (i.hasNext()) {
2374 PackageParser.Package p = i.next();
2375 if (p.applicationInfo != null
2376 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002377 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002378 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 }
2380 }
2381 }
2382
2383 return finalList;
2384 }
2385
2386 public ProviderInfo resolveContentProvider(String name, int flags) {
2387 synchronized (mPackages) {
2388 final PackageParser.Provider provider = mProviders.get(name);
2389 return provider != null
2390 && mSettings.isEnabledLP(provider.info, flags)
2391 && (!mSafeMode || (provider.info.applicationInfo.flags
2392 &ApplicationInfo.FLAG_SYSTEM) != 0)
2393 ? PackageParser.generateProviderInfo(provider, flags)
2394 : null;
2395 }
2396 }
2397
Fred Quintana718d8a22009-04-29 17:53:20 -07002398 /**
2399 * @deprecated
2400 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 public void querySyncProviders(List outNames, List outInfo) {
2402 synchronized (mPackages) {
2403 Iterator<Map.Entry<String, PackageParser.Provider>> i
2404 = mProviders.entrySet().iterator();
2405
2406 while (i.hasNext()) {
2407 Map.Entry<String, PackageParser.Provider> entry = i.next();
2408 PackageParser.Provider p = entry.getValue();
2409
2410 if (p.syncable
2411 && (!mSafeMode || (p.info.applicationInfo.flags
2412 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2413 outNames.add(entry.getKey());
2414 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2415 }
2416 }
2417 }
2418 }
2419
2420 public List<ProviderInfo> queryContentProviders(String processName,
2421 int uid, int flags) {
2422 ArrayList<ProviderInfo> finalList = null;
2423
2424 synchronized (mPackages) {
2425 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2426 while (i.hasNext()) {
2427 PackageParser.Provider p = i.next();
2428 if (p.info.authority != null
2429 && (processName == null ||
2430 (p.info.processName.equals(processName)
2431 && p.info.applicationInfo.uid == uid))
2432 && mSettings.isEnabledLP(p.info, flags)
2433 && (!mSafeMode || (p.info.applicationInfo.flags
2434 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2435 if (finalList == null) {
2436 finalList = new ArrayList<ProviderInfo>(3);
2437 }
2438 finalList.add(PackageParser.generateProviderInfo(p,
2439 flags));
2440 }
2441 }
2442 }
2443
2444 if (finalList != null) {
2445 Collections.sort(finalList, mProviderInitOrderSorter);
2446 }
2447
2448 return finalList;
2449 }
2450
2451 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2452 int flags) {
2453 synchronized (mPackages) {
2454 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2455 return PackageParser.generateInstrumentationInfo(i, flags);
2456 }
2457 }
2458
2459 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2460 int flags) {
2461 ArrayList<InstrumentationInfo> finalList =
2462 new ArrayList<InstrumentationInfo>();
2463
2464 synchronized (mPackages) {
2465 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2466 while (i.hasNext()) {
2467 PackageParser.Instrumentation p = i.next();
2468 if (targetPackage == null
2469 || targetPackage.equals(p.info.targetPackage)) {
2470 finalList.add(PackageParser.generateInstrumentationInfo(p,
2471 flags));
2472 }
2473 }
2474 }
2475
2476 return finalList;
2477 }
2478
2479 private void scanDirLI(File dir, int flags, int scanMode) {
2480 Log.d(TAG, "Scanning app dir " + dir);
2481
2482 String[] files = dir.list();
2483
2484 int i;
2485 for (i=0; i<files.length; i++) {
2486 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002487 if (!isPackageFilename(files[i])) {
2488 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002489 continue;
2490 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002491 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002493 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002494 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2495 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002496 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002497 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002498 file.delete();
2499 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 }
2501 }
2502
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002503 private static File getSettingsProblemFile() {
2504 File dataDir = Environment.getDataDirectory();
2505 File systemDir = new File(dataDir, "system");
2506 File fname = new File(systemDir, "uiderrors.txt");
2507 return fname;
2508 }
2509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 private static void reportSettingsProblem(int priority, String msg) {
2511 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002512 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 FileOutputStream out = new FileOutputStream(fname, true);
2514 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002515 SimpleDateFormat formatter = new SimpleDateFormat();
2516 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2517 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 pw.close();
2519 FileUtils.setPermissions(
2520 fname.toString(),
2521 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2522 -1, -1);
2523 } catch (java.io.IOException e) {
2524 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002525 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
2527
2528 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2529 PackageParser.Package pkg, File srcFile, int parseFlags) {
2530 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002531 if (ps != null
2532 && ps.codePath.equals(srcFile)
2533 && ps.getTimeStamp() == srcFile.lastModified()) {
2534 if (ps.signatures.mSignatures != null
2535 && ps.signatures.mSignatures.length != 0) {
2536 // Optimization: reuse the existing cached certificates
2537 // if the package appears to be unchanged.
2538 pkg.mSignatures = ps.signatures.mSignatures;
2539 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 }
Jeff Browne7600722010-04-07 18:28:23 -07002541
2542 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002543 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002544 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2545 }
2546
2547 if (!pp.collectCertificates(pkg, parseFlags)) {
2548 mLastScanError = pp.getParseError();
2549 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 }
2551 }
2552 return true;
2553 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002555 /*
2556 * Scan a package and return the newly parsed package.
2557 * Returns null in case of errors and the error code is stored in mLastScanError
2558 */
2559 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002560 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002562 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002563 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002564 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002567 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 if (pkg == null) {
2569 mLastScanError = pp.getParseError();
2570 return null;
2571 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002572 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 PackageSetting updatedPkg;
2574 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002575 // Look to see if we already know about this package.
2576 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002577 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002578 // This package has been renamed to its original name. Let's
2579 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002580 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002581 }
2582 // If there was no original package, see one for the real package name.
2583 if (ps == null) {
2584 ps = mSettings.peekPackageLP(pkg.packageName);
2585 }
2586 // Check to see if this package could be hiding/updating a system
2587 // package. Must look for it either under the original or real
2588 // package name depending on our state.
2589 updatedPkg = mSettings.mDisabledSysPackages.get(
2590 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002592 // First check if this is a system package that may involve an update
2593 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2594 if (!ps.codePath.equals(scanFile)) {
2595 // The path has changed from what was last scanned... check the
2596 // version of the new path against what we have stored to determine
2597 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002598 if (pkg.mVersionCode < ps.versionCode) {
2599 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002600 // Ignore entry. Skip it.
2601 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2602 + "ignored: updated version " + ps.versionCode
2603 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002604 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2605 return null;
2606 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002607 // The current app on the system partion is better than
2608 // what we have updated to on the data partition; switch
2609 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002610 // At this point, its safely assumed that package installation for
2611 // apps in system partition will go through. If not there won't be a working
2612 // version of the app
2613 synchronized (mPackages) {
2614 // Just remove the loaded entries from package lists.
2615 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002616 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002617 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002618 + "reverting from " + ps.codePathString
2619 + ": new version " + pkg.mVersionCode
2620 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002621 InstallArgs args = new FileInstallArgs(ps.codePathString,
2622 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002623 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002624 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002625 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002626 }
2627 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002628 if (updatedPkg != null) {
2629 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2630 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2631 }
2632 // Verify certificates against what was last scanned
2633 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002634 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002635 return null;
2636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 // The apk is forward locked (not public) if its code and resources
2638 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002639 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002641 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002642 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002643
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002644 String codePath = null;
2645 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002646 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2647 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002648 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002649 } else {
2650 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002651 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002652 }
2653 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002654 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002655 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002656 codePath = pkg.mScanPath;
2657 // Set application objects path explicitly.
2658 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002660 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 }
2662
Kenny Root85387d72010-08-26 10:13:11 -07002663 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2664 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002665 pkg.mPath = pkg.mScanPath = destCodePath;
2666 pkg.applicationInfo.sourceDir = destCodePath;
2667 pkg.applicationInfo.publicSourceDir = destResPath;
2668 }
2669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002670 private static String fixProcessName(String defProcessName,
2671 String processName, int uid) {
2672 if (processName == null) {
2673 return defProcessName;
2674 }
2675 return processName;
2676 }
2677
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002678 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002679 PackageParser.Package pkg) {
2680 if (pkgSetting.signatures.mSignatures != null) {
2681 // Already existing package. Make sure signatures match
2682 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2683 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002684 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002685 + " signatures do not match the previously installed version; ignoring!");
2686 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 return false;
2688 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002689 }
2690 // Check for shared user signatures
2691 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2692 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2693 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2694 Slog.e(TAG, "Package " + pkg.packageName
2695 + " has no signatures that match those in shared user "
2696 + pkgSetting.sharedUser.name + "; ignoring!");
2697 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2698 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 }
2701 return true;
2702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002703
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002704 public boolean performDexOpt(String packageName) {
2705 if (!mNoDexOpt) {
2706 return false;
2707 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002708
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002709 PackageParser.Package p;
2710 synchronized (mPackages) {
2711 p = mPackages.get(packageName);
2712 if (p == null || p.mDidDexOpt) {
2713 return false;
2714 }
2715 }
2716 synchronized (mInstallLock) {
2717 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2718 }
2719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002720
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002721 static final int DEX_OPT_SKIPPED = 0;
2722 static final int DEX_OPT_PERFORMED = 1;
2723 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002724
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002725 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2726 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002727 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002728 String path = pkg.mScanPath;
2729 int ret = 0;
2730 try {
2731 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002733 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002734 pkg.mDidDexOpt = true;
2735 performed = true;
2736 }
2737 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002738 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002739 ret = -1;
2740 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002741 Slog.w(TAG, "IOException reading apk: " + path, e);
2742 ret = -1;
2743 } catch (dalvik.system.StaleDexCacheError e) {
2744 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2745 ret = -1;
2746 } catch (Exception e) {
2747 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002748 ret = -1;
2749 }
2750 if (ret < 0) {
2751 //error from installer
2752 return DEX_OPT_FAILED;
2753 }
2754 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002755
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002756 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2757 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002758
2759 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2760 return Environment.isEncryptedFilesystemEnabled() &&
2761 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2762 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002763
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002764 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2765 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002766 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002767 + " to " + newPkg.packageName
2768 + ": old package not in system partition");
2769 return false;
2770 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002771 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002772 + " to " + newPkg.packageName
2773 + ": old package still exists");
2774 return false;
2775 }
2776 return true;
2777 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002778
2779 private File getDataPathForPackage(PackageParser.Package pkg) {
2780 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2781 File dataPath;
2782 if (useEncryptedFSDir) {
2783 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2784 } else {
2785 dataPath = new File(mAppDataDir, pkg.packageName);
2786 }
2787 return dataPath;
2788 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002789
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002790 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2791 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002792 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002793 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2794 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002795 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002796 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002797 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2798 return null;
2799 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 mScanningPath = scanFile;
2801 if (pkg == null) {
2802 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2803 return null;
2804 }
2805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2807 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2808 }
2809
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002810 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 synchronized (mPackages) {
2812 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002813 Slog.w(TAG, "*************************************************");
2814 Slog.w(TAG, "Core android package being redefined. Skipping.");
2815 Slog.w(TAG, " file=" + mScanningPath);
2816 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2818 return null;
2819 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 // Set up information for our fall-back user intent resolution
2822 // activity.
2823 mPlatformPackage = pkg;
2824 pkg.mVersionCode = mSdkVersion;
2825 mAndroidApplication = pkg.applicationInfo;
2826 mResolveActivity.applicationInfo = mAndroidApplication;
2827 mResolveActivity.name = ResolverActivity.class.getName();
2828 mResolveActivity.packageName = mAndroidApplication.packageName;
2829 mResolveActivity.processName = mAndroidApplication.processName;
2830 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2831 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2832 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2833 mResolveActivity.exported = true;
2834 mResolveActivity.enabled = true;
2835 mResolveInfo.activityInfo = mResolveActivity;
2836 mResolveInfo.priority = 0;
2837 mResolveInfo.preferredOrder = 0;
2838 mResolveInfo.match = 0;
2839 mResolveComponentName = new ComponentName(
2840 mAndroidApplication.packageName, mResolveActivity.name);
2841 }
2842 }
2843
2844 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002845 TAG, "Scanning package " + pkg.packageName);
2846 if (mPackages.containsKey(pkg.packageName)
2847 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002848 Slog.w(TAG, "*************************************************");
2849 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002851 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2853 return null;
2854 }
2855
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002856 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002857 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2858 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 SharedUserSetting suid = null;
2861 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002862
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002863 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2864 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002865 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002866 pkg.mRealPackage = null;
2867 pkg.mAdoptPermissions = null;
2868 }
2869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 synchronized (mPackages) {
2871 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002872 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2873 if (mTmpSharedLibraries == null ||
2874 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2875 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2876 }
2877 int num = 0;
2878 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2879 for (int i=0; i<N; i++) {
2880 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002882 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002883 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002884 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002885 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2886 return null;
2887 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002888 mTmpSharedLibraries[num] = file;
2889 num++;
2890 }
2891 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2892 for (int i=0; i<N; i++) {
2893 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2894 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002895 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002896 + " desires unavailable shared library "
2897 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2898 } else {
2899 mTmpSharedLibraries[num] = file;
2900 num++;
2901 }
2902 }
2903 if (num > 0) {
2904 pkg.usesLibraryFiles = new String[num];
2905 System.arraycopy(mTmpSharedLibraries, 0,
2906 pkg.usesLibraryFiles, 0, num);
2907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002908
Dianne Hackborn49237342009-08-27 20:08:01 -07002909 if (pkg.reqFeatures != null) {
2910 N = pkg.reqFeatures.size();
2911 for (int i=0; i<N; i++) {
2912 FeatureInfo fi = pkg.reqFeatures.get(i);
2913 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2914 // Don't care.
2915 continue;
2916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002917
Dianne Hackborn49237342009-08-27 20:08:01 -07002918 if (fi.name != null) {
2919 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002920 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002921 + " requires unavailable feature "
2922 + fi.name + "; failing!");
2923 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2924 return null;
2925 }
2926 }
2927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002928 }
2929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 if (pkg.mSharedUserId != null) {
2932 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2933 pkg.applicationInfo.flags, true);
2934 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002935 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 + " for shared user failed");
2937 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2938 return null;
2939 }
2940 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2941 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2942 + suid.userId + "): packages=" + suid.packages);
2943 }
2944 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002945
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002946 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002947 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002948 Log.w(TAG, "WAITING FOR DEBUGGER");
2949 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002950 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2951 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002952 }
2953 }
2954
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002955 // Check if we are renaming from an original package name.
2956 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002957 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002958 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002959 // This package may need to be renamed to a previously
2960 // installed name. Let's check on that...
2961 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002962 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002963 // This package had originally been installed as the
2964 // original name, and we have already taken care of
2965 // transitioning to the new one. Just update the new
2966 // one to continue using the old name.
2967 realName = pkg.mRealPackage;
2968 if (!pkg.packageName.equals(renamed)) {
2969 // Callers into this function may have already taken
2970 // care of renaming the package; only do it here if
2971 // it is not already done.
2972 pkg.setPackageName(renamed);
2973 }
2974
Dianne Hackbornc1552392010-03-03 16:19:01 -08002975 } else {
2976 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2977 if ((origPackage=mSettings.peekPackageLP(
2978 pkg.mOriginalPackages.get(i))) != null) {
2979 // We do have the package already installed under its
2980 // original name... should we use it?
2981 if (!verifyPackageUpdate(origPackage, pkg)) {
2982 // New package is not compatible with original.
2983 origPackage = null;
2984 continue;
2985 } else if (origPackage.sharedUser != null) {
2986 // Make sure uid is compatible between packages.
2987 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002988 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002989 + " to " + pkg.packageName + ": old uid "
2990 + origPackage.sharedUser.name
2991 + " differs from " + pkg.mSharedUserId);
2992 origPackage = null;
2993 continue;
2994 }
2995 } else {
2996 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
2997 + pkg.packageName + " to old name " + origPackage.name);
2998 }
2999 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003000 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003001 }
3002 }
3003 }
3004
3005 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003006 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003007 + " was transferred to another, but its .apk remains");
3008 }
3009
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003010 // Just create the setting, don't add it yet. For already existing packages
3011 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003012 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 destResourceFile, pkg.applicationInfo.flags, true, false);
3014 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003015 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3017 return null;
3018 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003019
3020 if (pkgSetting.origPackage != null) {
3021 // If we are first transitioning from an original package,
3022 // fix up the new package's name now. We need to do this after
3023 // looking up the package under its new name, so getPackageLP
3024 // can take care of fiddling things correctly.
3025 pkg.setPackageName(origPackage.name);
3026
3027 // File a report about this.
3028 String msg = "New package " + pkgSetting.realName
3029 + " renamed to replace old package " + pkgSetting.name;
3030 reportSettingsProblem(Log.WARN, msg);
3031
3032 // Make a note of it.
3033 mTransferedPackages.add(origPackage.name);
3034
3035 // No longer need to retain this.
3036 pkgSetting.origPackage = null;
3037 }
3038
3039 if (realName != null) {
3040 // Make a note of it.
3041 mTransferedPackages.add(pkg.packageName);
3042 }
3043
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003044 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3046 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 pkg.applicationInfo.uid = pkgSetting.userId;
3049 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003050
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003051 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003052 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003053 return null;
3054 }
3055 // The signature has changed, but this package is in the system
3056 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003057 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 // However... if this package is part of a shared user, but it
3059 // doesn't match the signature of the shared user, let's fail.
3060 // What this means is that you can't change the signatures
3061 // associated with an overall shared user, which doesn't seem all
3062 // that unreasonable.
3063 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003064 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3065 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3066 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3068 return null;
3069 }
3070 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003071 // File a report about this.
3072 String msg = "System package " + pkg.packageName
3073 + " signature changed; retaining data.";
3074 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003076
The Android Open Source Project10592532009-03-18 17:39:46 -07003077 // Verify that this new package doesn't have any content providers
3078 // that conflict with existing packages. Only do this if the
3079 // package isn't already installed, since we don't want to break
3080 // things that are installed.
3081 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3082 int N = pkg.providers.size();
3083 int i;
3084 for (i=0; i<N; i++) {
3085 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003086 if (p.info.authority != null) {
3087 String names[] = p.info.authority.split(";");
3088 for (int j = 0; j < names.length; j++) {
3089 if (mProviders.containsKey(names[j])) {
3090 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003091 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003092 " (in package " + pkg.applicationInfo.packageName +
3093 ") is already used by "
3094 + ((other != null && other.getComponentName() != null)
3095 ? other.getComponentName().getPackageName() : "?"));
3096 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3097 return null;
3098 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003099 }
3100 }
3101 }
3102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003103 }
3104
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003105 final String pkgName = pkg.packageName;
3106
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003107 if (pkg.mAdoptPermissions != null) {
3108 // This package wants to adopt ownership of permissions from
3109 // another package.
3110 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3111 String origName = pkg.mAdoptPermissions.get(i);
3112 PackageSetting orig = mSettings.peekPackageLP(origName);
3113 if (orig != null) {
3114 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003115 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003116 + origName + " to " + pkg.packageName);
3117 mSettings.transferPermissions(origName, pkg.packageName);
3118 }
3119 }
3120 }
3121 }
3122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 long scanFileTime = scanFile.lastModified();
3124 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3125 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3126 pkg.applicationInfo.processName = fixProcessName(
3127 pkg.applicationInfo.packageName,
3128 pkg.applicationInfo.processName,
3129 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130
3131 File dataPath;
3132 if (mPlatformPackage == pkg) {
3133 // The system package is special.
3134 dataPath = new File (Environment.getDataDirectory(), "system");
3135 pkg.applicationInfo.dataDir = dataPath.getPath();
3136 } else {
3137 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003138 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003139 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003140
3141 boolean uidError = false;
3142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 if (dataPath.exists()) {
3144 mOutPermissions[1] = 0;
3145 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003146
3147 // If we have mismatched owners for the data path, we have a
3148 // problem (unless we're running in the simulator.)
3149 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150 boolean recovered = false;
3151 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3152 // If this is a system app, we can at least delete its
3153 // current data so the application will still work.
3154 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003155 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003156 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 // Old data gone!
3158 String msg = "System package " + pkg.packageName
3159 + " has changed from uid: "
3160 + mOutPermissions[1] + " to "
3161 + pkg.applicationInfo.uid + "; old data erased";
3162 reportSettingsProblem(Log.WARN, msg);
3163 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003166 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 pkg.applicationInfo.uid);
3168 if (ret == -1) {
3169 // Ack should not happen!
3170 msg = "System package " + pkg.packageName
3171 + " could not have data directory re-created after delete.";
3172 reportSettingsProblem(Log.WARN, msg);
3173 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3174 return null;
3175 }
3176 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003177 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 if (!recovered) {
3179 mHasSystemUidErrors = true;
3180 }
3181 }
3182 if (!recovered) {
3183 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3184 + pkg.applicationInfo.uid + "/fs_"
3185 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003186 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 String msg = "Package " + pkg.packageName
3188 + " has mismatched uid: "
3189 + mOutPermissions[1] + " on disk, "
3190 + pkg.applicationInfo.uid + " in settings";
3191 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003192 mSettings.mReadMessages.append(msg);
3193 mSettings.mReadMessages.append('\n');
3194 uidError = true;
3195 if (!pkgSetting.uidError) {
3196 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
3199 }
3200 }
3201 pkg.applicationInfo.dataDir = dataPath.getPath();
3202 } else {
3203 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3204 Log.v(TAG, "Want this data dir: " + dataPath);
3205 //invoke installer to do the actual installation
3206 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003207 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 pkg.applicationInfo.uid);
3209 if(ret < 0) {
3210 // Error from installer
3211 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3212 return null;
3213 }
3214 } else {
3215 dataPath.mkdirs();
3216 if (dataPath.exists()) {
3217 FileUtils.setPermissions(
3218 dataPath.toString(),
3219 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3220 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3221 }
3222 }
3223 if (dataPath.exists()) {
3224 pkg.applicationInfo.dataDir = dataPath.getPath();
3225 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003226 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003227 pkg.applicationInfo.dataDir = null;
3228 }
3229 }
Kenny Root85387d72010-08-26 10:13:11 -07003230
3231 /*
3232 * Set the data dir to the default "/data/data/<package name>/lib"
3233 * if we got here without anyone telling us different (e.g., apps
3234 * stored on SD card have their native libraries stored in the ASEC
3235 * container with the APK).
3236 */
3237 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3238 pkg.applicationInfo.nativeLibraryDir = new File(dataPath, LIB_DIR_NAME).getPath();
3239 }
3240
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003241 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003242 }
3243
Kenny Root85387d72010-08-26 10:13:11 -07003244 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003245 if (mInstaller != null) {
3246 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003247 /* Note: We don't want to unpack the native binaries for
3248 * system applications, unless they have been updated
3249 * (the binaries are already under /system/lib).
3250 * Also, don't unpack libs for apps on the external card
3251 * since they should have their libraries in the ASEC
3252 * container already.
3253 *
3254 * In other words, we're going to unpack the binaries
3255 * only for non-system apps and system app upgrades.
3256 */
3257 if ((!isSystemApp(pkg) || isUpdatedSystemApp(pkg)) && !isExternal(pkg)) {
3258 Log.i(TAG, path + " changed; unpacking");
3259 File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3260 sharedLibraryDir.mkdir();
3261 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003262 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003263 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003264
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003265 if ((scanMode&SCAN_NO_DEX) == 0) {
3266 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3268 return null;
3269 }
3270 }
3271 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 if (mFactoryTest && pkg.requestedPermissions.contains(
3274 android.Manifest.permission.FACTORY_TEST)) {
3275 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3276 }
3277
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003278 // Request the ActivityManager to kill the process(only for existing packages)
3279 // so that we do not end up in a confused state while the user is still using the older
3280 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003281 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003282 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003283 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003284 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003286 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003287 // We don't expect installation to fail beyond this point,
3288 if ((scanMode&SCAN_MONITOR) != 0) {
3289 mAppDirs.put(pkg.mPath, pkg);
3290 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003292 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003293 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003294 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003295 // Make sure we don't accidentally delete its data.
3296 mSettings.mPackagesToBeCleaned.remove(pkgName);
3297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 int N = pkg.providers.size();
3299 StringBuilder r = null;
3300 int i;
3301 for (i=0; i<N; i++) {
3302 PackageParser.Provider p = pkg.providers.get(i);
3303 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3304 p.info.processName, pkg.applicationInfo.uid);
3305 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3306 p.info.name), p);
3307 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003308 if (p.info.authority != null) {
3309 String names[] = p.info.authority.split(";");
3310 p.info.authority = null;
3311 for (int j = 0; j < names.length; j++) {
3312 if (j == 1 && p.syncable) {
3313 // We only want the first authority for a provider to possibly be
3314 // syncable, so if we already added this provider using a different
3315 // authority clear the syncable flag. We copy the provider before
3316 // changing it because the mProviders object contains a reference
3317 // to a provider that we don't want to change.
3318 // Only do this for the second authority since the resulting provider
3319 // object can be the same for all future authorities for this provider.
3320 p = new PackageParser.Provider(p);
3321 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003323 if (!mProviders.containsKey(names[j])) {
3324 mProviders.put(names[j], p);
3325 if (p.info.authority == null) {
3326 p.info.authority = names[j];
3327 } else {
3328 p.info.authority = p.info.authority + ";" + names[j];
3329 }
3330 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3331 Log.d(TAG, "Registered content provider: " + names[j] +
3332 ", className = " + p.info.name +
3333 ", isSyncable = " + p.info.isSyncable);
3334 } else {
3335 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003336 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003337 " (in package " + pkg.applicationInfo.packageName +
3338 "): name already used by "
3339 + ((other != null && other.getComponentName() != null)
3340 ? other.getComponentName().getPackageName() : "?"));
3341 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 }
3343 }
3344 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3345 if (r == null) {
3346 r = new StringBuilder(256);
3347 } else {
3348 r.append(' ');
3349 }
3350 r.append(p.info.name);
3351 }
3352 }
3353 if (r != null) {
3354 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3355 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003357 N = pkg.services.size();
3358 r = null;
3359 for (i=0; i<N; i++) {
3360 PackageParser.Service s = pkg.services.get(i);
3361 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3362 s.info.processName, pkg.applicationInfo.uid);
3363 mServices.addService(s);
3364 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3365 if (r == null) {
3366 r = new StringBuilder(256);
3367 } else {
3368 r.append(' ');
3369 }
3370 r.append(s.info.name);
3371 }
3372 }
3373 if (r != null) {
3374 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3375 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 N = pkg.receivers.size();
3378 r = null;
3379 for (i=0; i<N; i++) {
3380 PackageParser.Activity a = pkg.receivers.get(i);
3381 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3382 a.info.processName, pkg.applicationInfo.uid);
3383 mReceivers.addActivity(a, "receiver");
3384 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3385 if (r == null) {
3386 r = new StringBuilder(256);
3387 } else {
3388 r.append(' ');
3389 }
3390 r.append(a.info.name);
3391 }
3392 }
3393 if (r != null) {
3394 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3395 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 N = pkg.activities.size();
3398 r = null;
3399 for (i=0; i<N; i++) {
3400 PackageParser.Activity a = pkg.activities.get(i);
3401 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3402 a.info.processName, pkg.applicationInfo.uid);
3403 mActivities.addActivity(a, "activity");
3404 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3405 if (r == null) {
3406 r = new StringBuilder(256);
3407 } else {
3408 r.append(' ');
3409 }
3410 r.append(a.info.name);
3411 }
3412 }
3413 if (r != null) {
3414 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3415 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 N = pkg.permissionGroups.size();
3418 r = null;
3419 for (i=0; i<N; i++) {
3420 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3421 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3422 if (cur == null) {
3423 mPermissionGroups.put(pg.info.name, pg);
3424 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3425 if (r == null) {
3426 r = new StringBuilder(256);
3427 } else {
3428 r.append(' ');
3429 }
3430 r.append(pg.info.name);
3431 }
3432 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003433 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 + pg.info.packageName + " ignored: original from "
3435 + cur.info.packageName);
3436 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3437 if (r == null) {
3438 r = new StringBuilder(256);
3439 } else {
3440 r.append(' ');
3441 }
3442 r.append("DUP:");
3443 r.append(pg.info.name);
3444 }
3445 }
3446 }
3447 if (r != null) {
3448 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3449 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 N = pkg.permissions.size();
3452 r = null;
3453 for (i=0; i<N; i++) {
3454 PackageParser.Permission p = pkg.permissions.get(i);
3455 HashMap<String, BasePermission> permissionMap =
3456 p.tree ? mSettings.mPermissionTrees
3457 : mSettings.mPermissions;
3458 p.group = mPermissionGroups.get(p.info.group);
3459 if (p.info.group == null || p.group != null) {
3460 BasePermission bp = permissionMap.get(p.info.name);
3461 if (bp == null) {
3462 bp = new BasePermission(p.info.name, p.info.packageName,
3463 BasePermission.TYPE_NORMAL);
3464 permissionMap.put(p.info.name, bp);
3465 }
3466 if (bp.perm == null) {
3467 if (bp.sourcePackage == null
3468 || bp.sourcePackage.equals(p.info.packageName)) {
3469 BasePermission tree = findPermissionTreeLP(p.info.name);
3470 if (tree == null
3471 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003472 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 bp.perm = p;
3474 bp.uid = pkg.applicationInfo.uid;
3475 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3476 if (r == null) {
3477 r = new StringBuilder(256);
3478 } else {
3479 r.append(' ');
3480 }
3481 r.append(p.info.name);
3482 }
3483 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003484 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 + p.info.packageName + " ignored: base tree "
3486 + tree.name + " is from package "
3487 + tree.sourcePackage);
3488 }
3489 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003490 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 + p.info.packageName + " ignored: original from "
3492 + bp.sourcePackage);
3493 }
3494 } else 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(p.info.name);
3502 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003503 if (bp.perm == p) {
3504 bp.protectionLevel = p.info.protectionLevel;
3505 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003506 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003507 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 + p.info.packageName + " ignored: no group "
3509 + p.group);
3510 }
3511 }
3512 if (r != null) {
3513 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3514 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 N = pkg.instrumentation.size();
3517 r = null;
3518 for (i=0; i<N; i++) {
3519 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3520 a.info.packageName = pkg.applicationInfo.packageName;
3521 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3522 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3523 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003524 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003525 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3527 if (r == null) {
3528 r = new StringBuilder(256);
3529 } else {
3530 r.append(' ');
3531 }
3532 r.append(a.info.name);
3533 }
3534 }
3535 if (r != null) {
3536 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003538
Dianne Hackborn854060af2009-07-09 18:14:31 -07003539 if (pkg.protectedBroadcasts != null) {
3540 N = pkg.protectedBroadcasts.size();
3541 for (i=0; i<N; i++) {
3542 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3543 }
3544 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 pkgSetting.setTimeStamp(scanFileTime);
3547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 return pkg;
3550 }
3551
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003552 private void killApplication(String pkgName, int uid) {
3553 // Request the ActivityManager to kill the process(only for existing packages)
3554 // so that we do not end up in a confused state while the user is still using the older
3555 // version of the application while the new one gets installed.
3556 IActivityManager am = ActivityManagerNative.getDefault();
3557 if (am != null) {
3558 try {
3559 am.killApplicationWithUid(pkgName, uid);
3560 } catch (RemoteException e) {
3561 }
3562 }
3563 }
3564
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003565 // Return the path of the directory that will contain the native binaries
3566 // of a given installed package. This is relative to the data path.
3567 //
Kenny Root85387d72010-08-26 10:13:11 -07003568 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3569 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3570 if (nativeLibraryDir != null) {
3571 return new File(nativeLibraryDir);
3572 } else {
3573 // Fall back for old packages
3574 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3575 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003576 }
3577
Kenny Root85387d72010-08-26 10:13:11 -07003578 // Convenience call for removeNativeBinariesLI(File)
3579 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3580 File nativeLibraryDir = getNativeBinaryDirForPackage(pkg);
3581 removeNativeBinariesLI(nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 }
3583
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003584 // Remove the native binaries of a given package. This simply
3585 // gets rid of the files in the 'lib' sub-directory.
Kenny Root85387d72010-08-26 10:13:11 -07003586 public void removeNativeBinariesLI(File binaryDir) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003587 if (DEBUG_NATIVE) {
Kenny Root85387d72010-08-26 10:13:11 -07003588 Slog.w(TAG, "Deleting native binaries from: " + binaryDir.getPath());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003589 }
3590
3591 // Just remove any file in the directory. Since the directory
3592 // is owned by the 'system' UID, the application is not supposed
3593 // to have written anything there.
3594 //
3595 if (binaryDir.exists()) {
Kenny Root85387d72010-08-26 10:13:11 -07003596 File[] binaries = binaryDir.listFiles();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003597 if (binaries != null) {
Kenny Root85387d72010-08-26 10:13:11 -07003598 for (int nn = 0; nn < binaries.length; nn++) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003599 if (DEBUG_NATIVE) {
Kenny Root85387d72010-08-26 10:13:11 -07003600 Slog.d(TAG, " Deleting " + binaries[nn].getName());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003601 }
3602 if (!binaries[nn].delete()) {
Kenny Root85387d72010-08-26 10:13:11 -07003603 Slog.w(TAG, "Could not delete native binary: " + binaries[nn].getPath());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003604 }
3605 }
3606 }
3607 // Do not delete 'lib' directory itself, or this will prevent
3608 // installation of future updates.
3609 }
3610 }
3611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3613 if (chatty && Config.LOGD) Log.d(
3614 TAG, "Removing package " + pkg.applicationInfo.packageName );
3615
3616 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003619 mPackages.remove(pkg.applicationInfo.packageName);
3620 if (pkg.mPath != null) {
3621 mAppDirs.remove(pkg.mPath);
3622 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 PackageSetting ps = (PackageSetting)pkg.mExtras;
3625 if (ps != null && ps.sharedUser != null) {
3626 // XXX don't do this until the data is removed.
3627 if (false) {
3628 ps.sharedUser.packages.remove(ps);
3629 if (ps.sharedUser.packages.size() == 0) {
3630 // Remove.
3631 }
3632 }
3633 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 int N = pkg.providers.size();
3636 StringBuilder r = null;
3637 int i;
3638 for (i=0; i<N; i++) {
3639 PackageParser.Provider p = pkg.providers.get(i);
3640 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3641 p.info.name));
3642 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003644 /* The is another ContentProvider with this authority when
3645 * this app was installed so this authority is null,
3646 * Ignore it as we don't have to unregister the provider.
3647 */
3648 continue;
3649 }
3650 String names[] = p.info.authority.split(";");
3651 for (int j = 0; j < names.length; j++) {
3652 if (mProviders.get(names[j]) == p) {
3653 mProviders.remove(names[j]);
3654 if (chatty && Config.LOGD) Log.d(
3655 TAG, "Unregistered content provider: " + names[j] +
3656 ", className = " + p.info.name +
3657 ", isSyncable = " + p.info.isSyncable);
3658 }
3659 }
3660 if (chatty) {
3661 if (r == null) {
3662 r = new StringBuilder(256);
3663 } else {
3664 r.append(' ');
3665 }
3666 r.append(p.info.name);
3667 }
3668 }
3669 if (r != null) {
3670 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3671 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 N = pkg.services.size();
3674 r = null;
3675 for (i=0; i<N; i++) {
3676 PackageParser.Service s = pkg.services.get(i);
3677 mServices.removeService(s);
3678 if (chatty) {
3679 if (r == null) {
3680 r = new StringBuilder(256);
3681 } else {
3682 r.append(' ');
3683 }
3684 r.append(s.info.name);
3685 }
3686 }
3687 if (r != null) {
3688 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3689 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691 N = pkg.receivers.size();
3692 r = null;
3693 for (i=0; i<N; i++) {
3694 PackageParser.Activity a = pkg.receivers.get(i);
3695 mReceivers.removeActivity(a, "receiver");
3696 if (chatty) {
3697 if (r == null) {
3698 r = new StringBuilder(256);
3699 } else {
3700 r.append(' ');
3701 }
3702 r.append(a.info.name);
3703 }
3704 }
3705 if (r != null) {
3706 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3707 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 N = pkg.activities.size();
3710 r = null;
3711 for (i=0; i<N; i++) {
3712 PackageParser.Activity a = pkg.activities.get(i);
3713 mActivities.removeActivity(a, "activity");
3714 if (chatty) {
3715 if (r == null) {
3716 r = new StringBuilder(256);
3717 } else {
3718 r.append(' ');
3719 }
3720 r.append(a.info.name);
3721 }
3722 }
3723 if (r != null) {
3724 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3725 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 N = pkg.permissions.size();
3728 r = null;
3729 for (i=0; i<N; i++) {
3730 PackageParser.Permission p = pkg.permissions.get(i);
3731 boolean tree = false;
3732 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3733 if (bp == null) {
3734 tree = true;
3735 bp = mSettings.mPermissionTrees.get(p.info.name);
3736 }
3737 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003738 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 if (chatty) {
3740 if (r == null) {
3741 r = new StringBuilder(256);
3742 } else {
3743 r.append(' ');
3744 }
3745 r.append(p.info.name);
3746 }
3747 }
3748 }
3749 if (r != null) {
3750 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 N = pkg.instrumentation.size();
3754 r = null;
3755 for (i=0; i<N; i++) {
3756 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003757 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 if (chatty) {
3759 if (r == null) {
3760 r = new StringBuilder(256);
3761 } else {
3762 r.append(' ');
3763 }
3764 r.append(a.info.name);
3765 }
3766 }
3767 if (r != null) {
3768 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3769 }
3770 }
3771 }
3772
3773 private static final boolean isPackageFilename(String name) {
3774 return name != null && name.endsWith(".apk");
3775 }
3776
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003777 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3778 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3779 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3780 return true;
3781 }
3782 }
3783 return false;
3784 }
3785
3786 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003787 PackageParser.Package pkgInfo, boolean grantPermissions,
3788 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 // Make sure there are no dangling permission trees.
3790 Iterator<BasePermission> it = mSettings.mPermissionTrees
3791 .values().iterator();
3792 while (it.hasNext()) {
3793 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003794 if (bp.packageSetting == null) {
3795 // We may not yet have parsed the package, so just see if
3796 // we still know about its settings.
3797 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3798 }
3799 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003800 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 + " from package " + bp.sourcePackage);
3802 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003803 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3804 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3805 Slog.i(TAG, "Removing old permission tree: " + bp.name
3806 + " from package " + bp.sourcePackage);
3807 grantPermissions = true;
3808 it.remove();
3809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003810 }
3811 }
3812
3813 // Make sure all dynamic permissions have been assigned to a package,
3814 // and make sure there are no dangling permissions.
3815 it = mSettings.mPermissions.values().iterator();
3816 while (it.hasNext()) {
3817 BasePermission bp = it.next();
3818 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3819 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3820 + bp.name + " pkg=" + bp.sourcePackage
3821 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003822 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 BasePermission tree = findPermissionTreeLP(bp.name);
3824 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003825 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 bp.perm = new PackageParser.Permission(tree.perm.owner,
3827 new PermissionInfo(bp.pendingInfo));
3828 bp.perm.info.packageName = tree.perm.info.packageName;
3829 bp.perm.info.name = bp.name;
3830 bp.uid = tree.uid;
3831 }
3832 }
3833 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003834 if (bp.packageSetting == null) {
3835 // We may not yet have parsed the package, so just see if
3836 // we still know about its settings.
3837 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3838 }
3839 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003840 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 + " from package " + bp.sourcePackage);
3842 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003843 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3844 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3845 Slog.i(TAG, "Removing old permission: " + bp.name
3846 + " from package " + bp.sourcePackage);
3847 grantPermissions = true;
3848 it.remove();
3849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 }
3851 }
3852
3853 // Now update the permissions for all packages, in particular
3854 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003855 if (grantPermissions) {
3856 for (PackageParser.Package pkg : mPackages.values()) {
3857 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003858 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003859 }
3860 }
3861 }
3862
3863 if (pkgInfo != null) {
3864 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 }
3866 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3869 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3870 if (ps == null) {
3871 return;
3872 }
3873 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003874 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 if (replace) {
3877 ps.permissionsFixed = false;
3878 if (gp == ps) {
3879 gp.grantedPermissions.clear();
3880 gp.gids = mGlobalGids;
3881 }
3882 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 if (gp.gids == null) {
3885 gp.gids = mGlobalGids;
3886 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 final int N = pkg.requestedPermissions.size();
3889 for (int i=0; i<N; i++) {
3890 String name = pkg.requestedPermissions.get(i);
3891 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 if (false) {
3893 if (gp != ps) {
3894 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003895 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 }
3897 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003898 if (bp != null && bp.packageSetting != null) {
3899 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003901 boolean allowedSig = false;
3902 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3903 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003905 } else if (bp.packageSetting == null) {
3906 // This permission is invalid; skip it.
3907 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003908 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3909 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3910 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003911 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003912 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003914 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003915 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 // For updated system applications, the signatureOrSystem permission
3917 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003918 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3920 if(sysPs.grantedPermissions.contains(perm)) {
3921 allowed = true;
3922 } else {
3923 allowed = false;
3924 }
3925 } else {
3926 allowed = true;
3927 }
3928 }
3929 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003930 if (allowed) {
3931 allowedSig = true;
3932 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003933 } else {
3934 allowed = false;
3935 }
3936 if (false) {
3937 if (gp != ps) {
3938 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3939 }
3940 }
3941 if (allowed) {
3942 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3943 && ps.permissionsFixed) {
3944 // If this is an existing, non-system package, then
3945 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003946 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003948 // Except... if this is a permission that was added
3949 // to the platform (note: need to only do this when
3950 // updating the platform).
3951 final int NP = PackageParser.NEW_PERMISSIONS.length;
3952 for (int ip=0; ip<NP; ip++) {
3953 final PackageParser.NewPermissionInfo npi
3954 = PackageParser.NEW_PERMISSIONS[ip];
3955 if (npi.name.equals(perm)
3956 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3957 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003958 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003959 + pkg.packageName);
3960 break;
3961 }
3962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 }
3964 }
3965 if (allowed) {
3966 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003967 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 gp.grantedPermissions.add(perm);
3969 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003970 } else if (!ps.haveGids) {
3971 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003972 }
3973 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003974 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 + " to package " + pkg.packageName
3976 + " because it was previously installed without");
3977 }
3978 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003979 if (gp.grantedPermissions.remove(perm)) {
3980 changedPermission = true;
3981 gp.gids = removeInts(gp.gids, bp.gids);
3982 Slog.i(TAG, "Un-granting permission " + perm
3983 + " from package " + pkg.packageName
3984 + " (protectionLevel=" + bp.protectionLevel
3985 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3986 + ")");
3987 } else {
3988 Slog.w(TAG, "Not granting permission " + perm
3989 + " to package " + pkg.packageName
3990 + " (protectionLevel=" + bp.protectionLevel
3991 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3992 + ")");
3993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 }
3995 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003996 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 + " in package " + pkg.packageName);
3998 }
3999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004000
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004001 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004002 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4003 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 // This is the first that we have heard about this package, so the
4005 // permissions we have now selected are fixed until explicitly
4006 // changed.
4007 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004009 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 private final class ActivityIntentResolver
4013 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004014 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004016 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 }
4018
Mihai Preda074edef2009-05-18 17:13:31 +02004019 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004021 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4023 }
4024
Mihai Predaeae850c2009-05-13 10:13:48 +02004025 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4026 ArrayList<PackageParser.Activity> packageActivities) {
4027 if (packageActivities == null) {
4028 return null;
4029 }
4030 mFlags = flags;
4031 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4032 int N = packageActivities.size();
4033 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4034 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004035
4036 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004037 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004038 intentFilters = packageActivities.get(i).intents;
4039 if (intentFilters != null && intentFilters.size() > 0) {
4040 listCut.add(intentFilters);
4041 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004042 }
4043 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4044 }
4045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004047 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 if (SHOW_INFO || Config.LOGV) Log.v(
4049 TAG, " " + type + " " +
4050 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4051 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4052 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004053 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004054 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4055 if (SHOW_INFO || Config.LOGV) {
4056 Log.v(TAG, " IntentFilter:");
4057 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4058 }
4059 if (!intent.debugCheck()) {
4060 Log.w(TAG, "==> For Activity " + a.info.name);
4061 }
4062 addFilter(intent);
4063 }
4064 }
4065
4066 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004067 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 if (SHOW_INFO || Config.LOGV) Log.v(
4069 TAG, " " + type + " " +
4070 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4071 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4072 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004073 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4075 if (SHOW_INFO || Config.LOGV) {
4076 Log.v(TAG, " IntentFilter:");
4077 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4078 }
4079 removeFilter(intent);
4080 }
4081 }
4082
4083 @Override
4084 protected boolean allowFilterResult(
4085 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4086 ActivityInfo filterAi = filter.activity.info;
4087 for (int i=dest.size()-1; i>=0; i--) {
4088 ActivityInfo destAi = dest.get(i).activityInfo;
4089 if (destAi.name == filterAi.name
4090 && destAi.packageName == filterAi.packageName) {
4091 return false;
4092 }
4093 }
4094 return true;
4095 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004098 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4099 return info.activity.owner.packageName;
4100 }
4101
4102 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4104 int match) {
4105 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4106 return null;
4107 }
4108 final PackageParser.Activity activity = info.activity;
4109 if (mSafeMode && (activity.info.applicationInfo.flags
4110 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4111 return null;
4112 }
4113 final ResolveInfo res = new ResolveInfo();
4114 res.activityInfo = PackageParser.generateActivityInfo(activity,
4115 mFlags);
4116 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4117 res.filter = info;
4118 }
4119 res.priority = info.getPriority();
4120 res.preferredOrder = activity.owner.mPreferredOrder;
4121 //System.out.println("Result: " + res.activityInfo.className +
4122 // " = " + res.priority);
4123 res.match = match;
4124 res.isDefault = info.hasDefault;
4125 res.labelRes = info.labelRes;
4126 res.nonLocalizedLabel = info.nonLocalizedLabel;
4127 res.icon = info.icon;
4128 return res;
4129 }
4130
4131 @Override
4132 protected void sortResults(List<ResolveInfo> results) {
4133 Collections.sort(results, mResolvePrioritySorter);
4134 }
4135
4136 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004137 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004139 out.print(prefix); out.print(
4140 Integer.toHexString(System.identityHashCode(filter.activity)));
4141 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004142 out.print(filter.activity.getComponentShortName());
4143 out.print(" filter ");
4144 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 }
4146
4147// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4148// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4149// final List<ResolveInfo> retList = Lists.newArrayList();
4150// while (i.hasNext()) {
4151// final ResolveInfo resolveInfo = i.next();
4152// if (isEnabledLP(resolveInfo.activityInfo)) {
4153// retList.add(resolveInfo);
4154// }
4155// }
4156// return retList;
4157// }
4158
4159 // Keys are String (activity class name), values are Activity.
4160 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4161 = new HashMap<ComponentName, PackageParser.Activity>();
4162 private int mFlags;
4163 }
4164
4165 private final class ServiceIntentResolver
4166 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004167 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004168 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004169 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 }
4171
Mihai Preda074edef2009-05-18 17:13:31 +02004172 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004173 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004174 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4176 }
4177
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004178 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4179 ArrayList<PackageParser.Service> packageServices) {
4180 if (packageServices == null) {
4181 return null;
4182 }
4183 mFlags = flags;
4184 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4185 int N = packageServices.size();
4186 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4187 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4188
4189 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4190 for (int i = 0; i < N; ++i) {
4191 intentFilters = packageServices.get(i).intents;
4192 if (intentFilters != null && intentFilters.size() > 0) {
4193 listCut.add(intentFilters);
4194 }
4195 }
4196 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4197 }
4198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004200 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 if (SHOW_INFO || Config.LOGV) Log.v(
4202 TAG, " " + (s.info.nonLocalizedLabel != null
4203 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4204 if (SHOW_INFO || Config.LOGV) Log.v(
4205 TAG, " Class=" + s.info.name);
4206 int NI = s.intents.size();
4207 int j;
4208 for (j=0; j<NI; j++) {
4209 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4210 if (SHOW_INFO || Config.LOGV) {
4211 Log.v(TAG, " IntentFilter:");
4212 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4213 }
4214 if (!intent.debugCheck()) {
4215 Log.w(TAG, "==> For Service " + s.info.name);
4216 }
4217 addFilter(intent);
4218 }
4219 }
4220
4221 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004222 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 if (SHOW_INFO || Config.LOGV) Log.v(
4224 TAG, " " + (s.info.nonLocalizedLabel != null
4225 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4226 if (SHOW_INFO || Config.LOGV) Log.v(
4227 TAG, " Class=" + s.info.name);
4228 int NI = s.intents.size();
4229 int j;
4230 for (j=0; j<NI; j++) {
4231 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4232 if (SHOW_INFO || Config.LOGV) {
4233 Log.v(TAG, " IntentFilter:");
4234 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4235 }
4236 removeFilter(intent);
4237 }
4238 }
4239
4240 @Override
4241 protected boolean allowFilterResult(
4242 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4243 ServiceInfo filterSi = filter.service.info;
4244 for (int i=dest.size()-1; i>=0; i--) {
4245 ServiceInfo destAi = dest.get(i).serviceInfo;
4246 if (destAi.name == filterSi.name
4247 && destAi.packageName == filterSi.packageName) {
4248 return false;
4249 }
4250 }
4251 return true;
4252 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004255 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4256 return info.service.owner.packageName;
4257 }
4258
4259 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004260 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4261 int match) {
4262 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4263 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4264 return null;
4265 }
4266 final PackageParser.Service service = info.service;
4267 if (mSafeMode && (service.info.applicationInfo.flags
4268 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4269 return null;
4270 }
4271 final ResolveInfo res = new ResolveInfo();
4272 res.serviceInfo = PackageParser.generateServiceInfo(service,
4273 mFlags);
4274 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4275 res.filter = filter;
4276 }
4277 res.priority = info.getPriority();
4278 res.preferredOrder = service.owner.mPreferredOrder;
4279 //System.out.println("Result: " + res.activityInfo.className +
4280 // " = " + res.priority);
4281 res.match = match;
4282 res.isDefault = info.hasDefault;
4283 res.labelRes = info.labelRes;
4284 res.nonLocalizedLabel = info.nonLocalizedLabel;
4285 res.icon = info.icon;
4286 return res;
4287 }
4288
4289 @Override
4290 protected void sortResults(List<ResolveInfo> results) {
4291 Collections.sort(results, mResolvePrioritySorter);
4292 }
4293
4294 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004295 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004297 out.print(prefix); out.print(
4298 Integer.toHexString(System.identityHashCode(filter.service)));
4299 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004300 out.print(filter.service.getComponentShortName());
4301 out.print(" filter ");
4302 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004303 }
4304
4305// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4306// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4307// final List<ResolveInfo> retList = Lists.newArrayList();
4308// while (i.hasNext()) {
4309// final ResolveInfo resolveInfo = (ResolveInfo) i;
4310// if (isEnabledLP(resolveInfo.serviceInfo)) {
4311// retList.add(resolveInfo);
4312// }
4313// }
4314// return retList;
4315// }
4316
4317 // Keys are String (activity class name), values are Activity.
4318 private final HashMap<ComponentName, PackageParser.Service> mServices
4319 = new HashMap<ComponentName, PackageParser.Service>();
4320 private int mFlags;
4321 };
4322
4323 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4324 new Comparator<ResolveInfo>() {
4325 public int compare(ResolveInfo r1, ResolveInfo r2) {
4326 int v1 = r1.priority;
4327 int v2 = r2.priority;
4328 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4329 if (v1 != v2) {
4330 return (v1 > v2) ? -1 : 1;
4331 }
4332 v1 = r1.preferredOrder;
4333 v2 = r2.preferredOrder;
4334 if (v1 != v2) {
4335 return (v1 > v2) ? -1 : 1;
4336 }
4337 if (r1.isDefault != r2.isDefault) {
4338 return r1.isDefault ? -1 : 1;
4339 }
4340 v1 = r1.match;
4341 v2 = r2.match;
4342 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4343 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4344 }
4345 };
4346
4347 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4348 new Comparator<ProviderInfo>() {
4349 public int compare(ProviderInfo p1, ProviderInfo p2) {
4350 final int v1 = p1.initOrder;
4351 final int v2 = p2.initOrder;
4352 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4353 }
4354 };
4355
Kenny Root93565c4b2010-06-18 15:46:06 -07004356 private static final boolean DEBUG_OBB = false;
4357
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004358 private static final void sendPackageBroadcast(String action, String pkg,
4359 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 IActivityManager am = ActivityManagerNative.getDefault();
4361 if (am != null) {
4362 try {
4363 final Intent intent = new Intent(action,
4364 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4365 if (extras != null) {
4366 intent.putExtras(extras);
4367 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004368 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004369 am.broadcastIntent(null, intent, null, finishedReceiver,
4370 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 } catch (RemoteException ex) {
4372 }
4373 }
4374 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004375
4376 public String nextPackageToClean(String lastPackage) {
4377 synchronized (mPackages) {
4378 if (!mMediaMounted) {
4379 // If the external storage is no longer mounted at this point,
4380 // the caller may not have been able to delete all of this
4381 // packages files and can not delete any more. Bail.
4382 return null;
4383 }
4384 if (lastPackage != null) {
4385 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4386 }
4387 return mSettings.mPackagesToBeCleaned.size() > 0
4388 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4389 }
4390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004392 void schedulePackageCleaning(String packageName) {
4393 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4394 }
4395
4396 void startCleaningPackages() {
4397 synchronized (mPackages) {
4398 if (!mMediaMounted) {
4399 return;
4400 }
4401 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4402 return;
4403 }
4404 }
4405 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4406 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4407 IActivityManager am = ActivityManagerNative.getDefault();
4408 if (am != null) {
4409 try {
4410 am.startService(null, intent, null);
4411 } catch (RemoteException e) {
4412 }
4413 }
4414 }
4415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004416 private final class AppDirObserver extends FileObserver {
4417 public AppDirObserver(String path, int mask, boolean isrom) {
4418 super(path, mask);
4419 mRootDir = path;
4420 mIsRom = isrom;
4421 }
4422
4423 public void onEvent(int event, String path) {
4424 String removedPackage = null;
4425 int removedUid = -1;
4426 String addedPackage = null;
4427 int addedUid = -1;
4428
4429 synchronized (mInstallLock) {
4430 String fullPathStr = null;
4431 File fullPath = null;
4432 if (path != null) {
4433 fullPath = new File(mRootDir, path);
4434 fullPathStr = fullPath.getPath();
4435 }
4436
4437 if (Config.LOGV) Log.v(
4438 TAG, "File " + fullPathStr + " changed: "
4439 + Integer.toHexString(event));
4440
4441 if (!isPackageFilename(path)) {
4442 if (Config.LOGV) Log.v(
4443 TAG, "Ignoring change of non-package file: " + fullPathStr);
4444 return;
4445 }
4446
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004447 // Ignore packages that are being installed or
4448 // have just been installed.
4449 if (ignoreCodePath(fullPathStr)) {
4450 return;
4451 }
4452 PackageParser.Package p = null;
4453 synchronized (mPackages) {
4454 p = mAppDirs.get(fullPathStr);
4455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004457 if (p != null) {
4458 removePackageLI(p, true);
4459 removedPackage = p.applicationInfo.packageName;
4460 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 }
4462 }
4463
4464 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004466 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004467 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4468 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004469 PackageParser.PARSE_CHATTY |
4470 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004471 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 if (p != null) {
4473 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004474 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004475 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004476 }
4477 addedPackage = p.applicationInfo.packageName;
4478 addedUid = p.applicationInfo.uid;
4479 }
4480 }
4481 }
4482
4483 synchronized (mPackages) {
4484 mSettings.writeLP();
4485 }
4486 }
4487
4488 if (removedPackage != null) {
4489 Bundle extras = new Bundle(1);
4490 extras.putInt(Intent.EXTRA_UID, removedUid);
4491 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004492 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4493 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004494 }
4495 if (addedPackage != null) {
4496 Bundle extras = new Bundle(1);
4497 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004498 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4499 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 }
4501 }
4502
4503 private final String mRootDir;
4504 private final boolean mIsRom;
4505 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004507 /* Called when a downloaded package installation has been confirmed by the user */
4508 public void installPackage(
4509 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004510 installPackage(packageURI, observer, flags, null);
4511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004512
Jacek Surazski65e13172009-04-28 15:26:38 +02004513 /* Called when a downloaded package installation has been confirmed by the user */
4514 public void installPackage(
4515 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4516 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004517 mContext.enforceCallingOrSelfPermission(
4518 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004519
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004520 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004521 msg.obj = new InstallParams(packageURI, observer, flags,
4522 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004523 mHandler.sendMessage(msg);
4524 }
4525
Christopher Tate1bb69062010-02-19 17:02:12 -08004526 public void finishPackageInstall(int token) {
4527 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4528 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4529 mHandler.sendMessage(msg);
4530 }
4531
Kenny Root93565c4b2010-06-18 15:46:06 -07004532 public void setPackageObbPath(String packageName, String path) {
4533 if (DEBUG_OBB)
4534 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4535 PackageSetting pkgSetting;
4536 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004537 final int permission = mContext.checkCallingPermission(
4538 android.Manifest.permission.INSTALL_PACKAGES);
4539 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004540 synchronized (mPackages) {
4541 pkgSetting = mSettings.mPackages.get(packageName);
4542 if (pkgSetting == null) {
4543 throw new IllegalArgumentException("Unknown package: " + packageName);
4544 }
4545 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4546 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4547 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4548 + pkgSetting.userId);
4549 }
4550 pkgSetting.obbPathString = path;
4551 mSettings.writeLP();
4552 }
4553 }
4554
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004555 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004556 // Queue up an async operation since the package installation may take a little while.
4557 mHandler.post(new Runnable() {
4558 public void run() {
4559 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004560 // Result object to be returned
4561 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004562 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004563 res.uid = -1;
4564 res.pkg = null;
4565 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004566 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004567 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004568 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004569 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004570 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004571 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004573
4574 // A restore should be performed at this point if (a) the install
4575 // succeeded, (b) the operation is not an update, and (c) the new
4576 // package has a backupAgent defined.
4577 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004578 boolean doRestore = (!update
4579 && res.pkg != null
4580 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004581
4582 // Set up the post-install work request bookkeeping. This will be used
4583 // and cleaned up by the post-install event handling regardless of whether
4584 // there's a restore pass performed. Token values are >= 1.
4585 int token;
4586 if (mNextInstallToken < 0) mNextInstallToken = 1;
4587 token = mNextInstallToken++;
4588
4589 PostInstallData data = new PostInstallData(args, res);
4590 mRunningInstalls.put(token, data);
4591 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4592
4593 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4594 // Pass responsibility to the Backup Manager. It will perform a
4595 // restore if appropriate, then pass responsibility back to the
4596 // Package Manager to run the post-install observer callbacks
4597 // and broadcasts.
4598 IBackupManager bm = IBackupManager.Stub.asInterface(
4599 ServiceManager.getService(Context.BACKUP_SERVICE));
4600 if (bm != null) {
4601 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4602 + " to BM for possible restore");
4603 try {
4604 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4605 } catch (RemoteException e) {
4606 // can't happen; the backup manager is local
4607 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004608 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004609 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004610 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004611 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004612 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004613 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004615 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004616
4617 if (!doRestore) {
4618 // No restore possible, or the Backup Manager was mysteriously not
4619 // available -- just fire the post-install work request directly.
4620 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4621 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4622 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624 }
4625 });
4626 }
4627
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004628 abstract class HandlerParams {
4629 final static int MAX_RETRIES = 4;
4630 int retry = 0;
4631 final void startCopy() {
4632 try {
4633 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4634 retry++;
4635 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004636 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004637 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4638 handleServiceError();
4639 return;
4640 } else {
4641 handleStartCopy();
4642 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4643 mHandler.sendEmptyMessage(MCS_UNBIND);
4644 }
4645 } catch (RemoteException e) {
4646 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4647 mHandler.sendEmptyMessage(MCS_RECONNECT);
4648 }
4649 handleReturnCode();
4650 }
4651
4652 final void serviceError() {
4653 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4654 handleServiceError();
4655 handleReturnCode();
4656 }
4657 abstract void handleStartCopy() throws RemoteException;
4658 abstract void handleServiceError();
4659 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004660 }
4661
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004662 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004663 final IPackageInstallObserver observer;
4664 int flags;
4665 final Uri packageURI;
4666 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004667 private InstallArgs mArgs;
4668 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004669 InstallParams(Uri packageURI,
4670 IPackageInstallObserver observer, int flags,
4671 String installerPackageName) {
4672 this.packageURI = packageURI;
4673 this.flags = flags;
4674 this.observer = observer;
4675 this.installerPackageName = installerPackageName;
4676 }
4677
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004678 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4679 String packageName = pkgLite.packageName;
4680 int installLocation = pkgLite.installLocation;
4681 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4682 synchronized (mPackages) {
4683 PackageParser.Package pkg = mPackages.get(packageName);
4684 if (pkg != null) {
4685 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4686 // Check for updated system application.
4687 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4688 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004689 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004690 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4691 }
4692 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4693 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004694 if (onSd) {
4695 // Install flag overrides everything.
4696 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4697 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004698 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004699 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4700 // Application explicitly specified internal.
4701 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4702 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4703 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004704 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004705 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004706 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004707 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4708 }
4709 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004710 }
4711 }
4712 } else {
4713 // Invalid install. Return error code
4714 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4715 }
4716 }
4717 }
4718 // All the special cases have been taken care of.
4719 // Return result based on recommended install location.
4720 if (onSd) {
4721 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4722 }
4723 return pkgLite.recommendedInstallLocation;
4724 }
4725
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004726 /*
4727 * Invoke remote method to get package information and install
4728 * location values. Override install location based on default
4729 * policy if needed and then create install arguments based
4730 * on the install location.
4731 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004732 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004733 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004734 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4735 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004736 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4737 if (onInt && onSd) {
4738 // Check if both bits are set.
4739 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4740 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4741 } else if (fwdLocked && onSd) {
4742 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004743 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004744 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004745 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004746 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004747 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004748 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004749 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4750 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4751 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4752 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4753 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004754 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4755 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4756 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004757 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4758 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004759 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004760 // Override with defaults if needed.
4761 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004762 if (!onSd && !onInt) {
4763 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004764 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4765 // Set the flag to install on external media.
4766 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004767 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004768 } else {
4769 // Make sure the flag for installing on external
4770 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004771 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004772 flags &= ~PackageManager.INSTALL_EXTERNAL;
4773 }
4774 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004775 }
4776 }
4777 // Create the file args now.
4778 mArgs = createInstallArgs(this);
4779 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4780 // Create copy only if we are not in an erroneous state.
4781 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004782 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004783 }
4784 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004785 }
4786
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004787 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004788 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004789 // If mArgs is null, then MCS couldn't be reached. When it
4790 // reconnects, it will try again to install. At that point, this
4791 // will succeed.
4792 if (mArgs != null) {
4793 processPendingInstall(mArgs, mRet);
4794 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004795 }
4796
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004797 @Override
4798 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004799 mArgs = createInstallArgs(this);
4800 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004801 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004802 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004803
4804 /*
4805 * Utility class used in movePackage api.
4806 * srcArgs and targetArgs are not set for invalid flags and make
4807 * sure to do null checks when invoking methods on them.
4808 * We probably want to return ErrorPrams for both failed installs
4809 * and moves.
4810 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004811 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004812 final IPackageMoveObserver observer;
4813 final int flags;
4814 final String packageName;
4815 final InstallArgs srcArgs;
4816 final InstallArgs targetArgs;
4817 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004818
4819 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4820 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004821 this.srcArgs = srcArgs;
4822 this.observer = observer;
4823 this.flags = flags;
4824 this.packageName = packageName;
4825 if (srcArgs != null) {
4826 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004827 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004828 } else {
4829 targetArgs = null;
4830 }
4831 }
4832
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004833 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004834 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4835 // Check for storage space on target medium
4836 if (!targetArgs.checkFreeStorage(mContainerService)) {
4837 Log.w(TAG, "Insufficient storage to install");
4838 return;
4839 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004840 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004841 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004842 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004843 if (DEBUG_SD_INSTALL) {
4844 StringBuilder builder = new StringBuilder();
4845 if (srcArgs != null) {
4846 builder.append("src: ");
4847 builder.append(srcArgs.getCodePath());
4848 }
4849 if (targetArgs != null) {
4850 builder.append(" target : ");
4851 builder.append(targetArgs.getCodePath());
4852 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004853 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004854 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004855 }
4856
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004857 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 void handleReturnCode() {
4859 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004860 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4861 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4862 currentStatus = PackageManager.MOVE_SUCCEEDED;
4863 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4864 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4865 }
4866 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004867 }
4868
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004869 @Override
4870 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004871 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004872 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004873 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004874
4875 private InstallArgs createInstallArgs(InstallParams params) {
4876 if (installOnSd(params.flags)) {
4877 return new SdInstallArgs(params);
4878 } else {
4879 return new FileInstallArgs(params);
4880 }
4881 }
4882
Kenny Root85387d72010-08-26 10:13:11 -07004883 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4884 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004885 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004886 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004887 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004888 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004889 }
4890 }
4891
Kenny Root85387d72010-08-26 10:13:11 -07004892 // Used by package mover
4893 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004894 if (installOnSd(flags)) {
4895 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4896 return new SdInstallArgs(packageURI, cid);
4897 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004898 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004899 }
4900 }
4901
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004902 static abstract class InstallArgs {
4903 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004904 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004905 final int flags;
4906 final Uri packageURI;
4907 final String installerPackageName;
4908
4909 InstallArgs(Uri packageURI,
4910 IPackageInstallObserver observer, int flags,
4911 String installerPackageName) {
4912 this.packageURI = packageURI;
4913 this.flags = flags;
4914 this.observer = observer;
4915 this.installerPackageName = installerPackageName;
4916 }
4917
4918 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004919 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004920 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004921 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004922 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004923 abstract String getCodePath();
4924 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004925 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004926 // Need installer lock especially for dex file removal.
4927 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004928 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004929 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004930 }
4931
4932 class FileInstallArgs extends InstallArgs {
4933 File installDir;
4934 String codeFileName;
4935 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004936 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004937 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004938
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004939 FileInstallArgs(InstallParams params) {
4940 super(params.packageURI, params.observer,
4941 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004942 }
4943
Kenny Root85387d72010-08-26 10:13:11 -07004944 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004945 super(null, null, 0, null);
4946 File codeFile = new File(fullCodePath);
4947 installDir = codeFile.getParentFile();
4948 codeFileName = fullCodePath;
4949 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004950 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004951 }
4952
Kenny Root85387d72010-08-26 10:13:11 -07004953 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004954 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004955 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004956 String apkName = getNextCodePath(null, pkgName, ".apk");
4957 codeFileName = new File(installDir, apkName + ".apk").getPath();
4958 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004959 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004960 }
4961
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004962 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4963 return imcs.checkFreeStorage(false, packageURI);
4964 }
4965
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004966 String getCodePath() {
4967 return codeFileName;
4968 }
4969
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004970 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004971 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004972 codeFileName = createTempPackageFile(installDir).getPath();
4973 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004974 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004975 }
4976
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004977 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004978 if (temp) {
4979 // Generate temp file name
4980 createCopyFile();
4981 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004982 // Get a ParcelFileDescriptor to write to the output file
4983 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004984 if (!created) {
4985 try {
4986 codeFile.createNewFile();
4987 // Set permissions
4988 if (!setPermissions()) {
4989 // Failed setting permissions.
4990 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4991 }
4992 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004993 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004994 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4995 }
4996 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004997 ParcelFileDescriptor out = null;
4998 try {
Kenny Root85387d72010-08-26 10:13:11 -07004999 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005000 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005001 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005002 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5003 }
5004 // Copy the resource now
5005 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5006 try {
5007 if (imcs.copyResource(packageURI, out)) {
5008 ret = PackageManager.INSTALL_SUCCEEDED;
5009 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005010 } finally {
5011 try { if (out != null) out.close(); } catch (IOException e) {}
5012 }
Kenny Root85387d72010-08-26 10:13:11 -07005013
5014 if (!temp) {
5015 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5016 }
5017
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005018 return ret;
5019 }
5020
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005021 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005022 if (status != PackageManager.INSTALL_SUCCEEDED) {
5023 cleanUp();
5024 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005025 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005026 }
5027
5028 boolean doRename(int status, final String pkgName, String oldCodePath) {
5029 if (status != PackageManager.INSTALL_SUCCEEDED) {
5030 cleanUp();
5031 return false;
5032 } else {
5033 // Rename based on packageName
5034 File codeFile = new File(getCodePath());
5035 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5036 File desFile = new File(installDir, apkName + ".apk");
5037 if (!codeFile.renameTo(desFile)) {
5038 return false;
5039 }
5040 // Reset paths since the file has been renamed.
5041 codeFileName = desFile.getPath();
5042 resourceFileName = getResourcePathFromCodePath();
5043 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005044 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005045 // Failed setting permissions.
5046 return false;
5047 }
5048 return true;
5049 }
5050 }
5051
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005052 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005053 if (status != PackageManager.INSTALL_SUCCEEDED) {
5054 cleanUp();
5055 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005056 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005057 }
5058
5059 String getResourcePath() {
5060 return resourceFileName;
5061 }
5062
5063 String getResourcePathFromCodePath() {
5064 String codePath = getCodePath();
5065 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5066 String apkNameOnly = getApkName(codePath);
5067 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5068 } else {
5069 return codePath;
5070 }
5071 }
5072
Kenny Root85387d72010-08-26 10:13:11 -07005073 @Override
5074 String getNativeLibraryPath() {
5075 return libraryPath;
5076 }
5077
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005078 private boolean cleanUp() {
5079 boolean ret = true;
5080 String sourceDir = getCodePath();
5081 String publicSourceDir = getResourcePath();
5082 if (sourceDir != null) {
5083 File sourceFile = new File(sourceDir);
5084 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005085 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005086 ret = false;
5087 }
5088 // Delete application's code and resources
5089 sourceFile.delete();
5090 }
5091 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5092 final File publicSourceFile = new File(publicSourceDir);
5093 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005094 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005095 }
5096 if (publicSourceFile.exists()) {
5097 publicSourceFile.delete();
5098 }
5099 }
5100 return ret;
5101 }
5102
5103 void cleanUpResourcesLI() {
5104 String sourceDir = getCodePath();
5105 if (cleanUp() && mInstaller != null) {
5106 int retCode = mInstaller.rmdex(sourceDir);
5107 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005108 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005109 + " at location "
5110 + sourceDir + ", retcode=" + retCode);
5111 // we don't consider this to be a failure of the core package deletion
5112 }
5113 }
Kenny Root85387d72010-08-26 10:13:11 -07005114 if (libraryPath != null) {
5115 removeNativeBinariesLI(new File(libraryPath));
5116 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005117 }
5118
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005119 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005120 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005121 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005122 final int filePermissions =
5123 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5124 |FileUtils.S_IROTH;
5125 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5126 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005127 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005128 getCodePath()
5129 + ". The return code was: " + retCode);
5130 // TODO Define new internal error
5131 return false;
5132 }
5133 return true;
5134 }
5135 return true;
5136 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005137
5138 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005139 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005140 cleanUpResourcesLI();
5141 return true;
5142 }
Kenny Root85387d72010-08-26 10:13:11 -07005143
5144 private boolean isFwdLocked() {
5145 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5146 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005147 }
5148
5149 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005150 static final String RES_FILE_NAME = "pkg.apk";
5151
Kenny Root85387d72010-08-26 10:13:11 -07005152 String cid;
5153 String packagePath;
5154 String libraryPath;
5155
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005156 SdInstallArgs(InstallParams params) {
5157 super(params.packageURI, params.observer,
5158 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005159 }
5160
Kenny Root85387d72010-08-26 10:13:11 -07005161 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005162 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005163 // Extract cid from fullCodePath
5164 int eidx = fullCodePath.lastIndexOf("/");
5165 String subStr1 = fullCodePath.substring(0, eidx);
5166 int sidx = subStr1.lastIndexOf("/");
5167 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005168 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005169 }
5170
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005171 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005172 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5173 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005174 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005175 }
5176
5177 SdInstallArgs(Uri packageURI, String cid) {
5178 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005179 this.cid = cid;
5180 }
5181
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005182 void createCopyFile() {
5183 cid = getTempContainerId();
5184 }
5185
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005186 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5187 return imcs.checkFreeStorage(true, packageURI);
5188 }
5189
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005190 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005191 if (temp) {
5192 createCopyFile();
5193 }
Kenny Root85387d72010-08-26 10:13:11 -07005194 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005195 packageURI, cid,
5196 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005197 if (newCachePath != null) {
5198 setCachePath(newCachePath);
5199 return PackageManager.INSTALL_SUCCEEDED;
5200 } else {
5201 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5202 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005203 }
5204
5205 @Override
5206 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005207 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005208 }
5209
5210 @Override
5211 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005212 return packagePath;
5213 }
5214
5215 @Override
5216 String getNativeLibraryPath() {
5217 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005218 }
5219
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005220 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005221 if (status != PackageManager.INSTALL_SUCCEEDED) {
5222 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005223 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005224 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005225 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005226 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005227 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5228 Process.SYSTEM_UID);
5229 if (newCachePath != null) {
5230 setCachePath(newCachePath);
5231 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005232 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5233 }
5234 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005235 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005236 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005237 }
5238
5239 boolean doRename(int status, final String pkgName,
5240 String oldCodePath) {
5241 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005242 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005243 if (PackageHelper.isContainerMounted(cid)) {
5244 // Unmount the container
5245 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005246 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005247 return false;
5248 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005249 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005250 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005251 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5252 " which might be stale. Will try to clean up.");
5253 // Clean up the stale container and proceed to recreate.
5254 if (!PackageHelper.destroySdDir(newCacheId)) {
5255 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5256 return false;
5257 }
5258 // Successfully cleaned up stale container. Try to rename again.
5259 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5260 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5261 + " inspite of cleaning it up.");
5262 return false;
5263 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005264 }
5265 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005266 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005267 newCachePath = PackageHelper.mountSdDir(newCacheId,
5268 getEncryptKey(), Process.SYSTEM_UID);
5269 } else {
5270 newCachePath = PackageHelper.getSdDir(newCacheId);
5271 }
5272 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005273 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005274 return false;
5275 }
5276 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005277 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005278 " at new path: " + newCachePath);
5279 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005280 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005281 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005282 }
5283
Kenny Root85387d72010-08-26 10:13:11 -07005284 private void setCachePath(String newCachePath) {
5285 File cachePath = new File(newCachePath);
5286 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5287 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5288 }
5289
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005290 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005291 if (status != PackageManager.INSTALL_SUCCEEDED) {
5292 cleanUp();
5293 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005294 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005295 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005296 PackageHelper.mountSdDir(cid,
5297 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005298 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005299 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005300 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005301 }
5302
5303 private void cleanUp() {
5304 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005305 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005306 }
5307
5308 void cleanUpResourcesLI() {
5309 String sourceFile = getCodePath();
5310 // Remove dex file
5311 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005312 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005313 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005314 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005315 + " at location "
5316 + sourceFile.toString() + ", retcode=" + retCode);
5317 // we don't consider this to be a failure of the core package deletion
5318 }
5319 }
5320 cleanUp();
5321 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005322
5323 boolean matchContainer(String app) {
5324 if (cid.startsWith(app)) {
5325 return true;
5326 }
5327 return false;
5328 }
5329
5330 String getPackageName() {
5331 int idx = cid.lastIndexOf("-");
5332 if (idx == -1) {
5333 return cid;
5334 }
5335 return cid.substring(0, idx);
5336 }
5337
5338 boolean doPostDeleteLI(boolean delete) {
5339 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005340 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005341 if (mounted) {
5342 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005343 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005344 }
5345 if (ret && delete) {
5346 cleanUpResourcesLI();
5347 }
5348 return ret;
5349 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005350 };
5351
5352 // Utility method used to create code paths based on package name and available index.
5353 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5354 String idxStr = "";
5355 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005356 // Fall back to default value of idx=1 if prefix is not
5357 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005358 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005359 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005360 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005361 if (subStr.endsWith(suffix)) {
5362 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005363 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005364 // If oldCodePath already contains prefix find out the
5365 // ending index to either increment or decrement.
5366 int sidx = subStr.lastIndexOf(prefix);
5367 if (sidx != -1) {
5368 subStr = subStr.substring(sidx + prefix.length());
5369 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005370 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5371 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005372 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005373 try {
5374 idx = Integer.parseInt(subStr);
5375 if (idx <= 1) {
5376 idx++;
5377 } else {
5378 idx--;
5379 }
5380 } catch(NumberFormatException e) {
5381 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005382 }
5383 }
5384 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005385 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005386 return prefix + idxStr;
5387 }
5388
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005389 // Utility method used to ignore ADD/REMOVE events
5390 // by directory observer.
5391 private static boolean ignoreCodePath(String fullPathStr) {
5392 String apkName = getApkName(fullPathStr);
5393 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5394 if (idx != -1 && ((idx+1) < apkName.length())) {
5395 // Make sure the package ends with a numeral
5396 String version = apkName.substring(idx+1);
5397 try {
5398 Integer.parseInt(version);
5399 return true;
5400 } catch (NumberFormatException e) {}
5401 }
5402 return false;
5403 }
5404
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005405 // Utility method that returns the relative package path with respect
5406 // to the installation directory. Like say for /data/data/com.test-1.apk
5407 // string com.test-1 is returned.
5408 static String getApkName(String codePath) {
5409 if (codePath == null) {
5410 return null;
5411 }
5412 int sidx = codePath.lastIndexOf("/");
5413 int eidx = codePath.lastIndexOf(".");
5414 if (eidx == -1) {
5415 eidx = codePath.length();
5416 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005417 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005418 return null;
5419 }
5420 return codePath.substring(sidx+1, eidx);
5421 }
5422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005423 class PackageInstalledInfo {
5424 String name;
5425 int uid;
5426 PackageParser.Package pkg;
5427 int returnCode;
5428 PackageRemovedInfo removedInfo;
5429 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 /*
5432 * Install a non-existing package.
5433 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005434 private void installNewPackageLI(PackageParser.Package pkg,
5435 int parseFlags,
5436 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005437 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005438 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005439 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005440
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005441 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005442 res.name = pkgName;
5443 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005444 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5445 // A package with the same name is already installed, though
5446 // it has been renamed to an older name. The package we
5447 // are trying to install should be installed as an update to
5448 // the existing one, but that has not been requested, so bail.
5449 Slog.w(TAG, "Attempt to re-install " + pkgName
5450 + " without first uninstalling package running as "
5451 + mSettings.mRenamedPackages.get(pkgName));
5452 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5453 return;
5454 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005455 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005457 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 + " without first uninstalling.");
5459 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5460 return;
5461 }
5462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005464 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005465 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005466 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005467 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5468 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5469 }
5470 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005471 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005472 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005473 res);
5474 // delete the partially installed application. the data directory will have to be
5475 // restored if it was already existing
5476 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5477 // remove package from internal structures. Note that we want deletePackageX to
5478 // delete the package data and cache directories that it created in
5479 // scanPackageLocked, unless those directories existed before we even tried to
5480 // install.
5481 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005482 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5484 res.removedInfo);
5485 }
5486 }
5487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005488
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005489 private void replacePackageLI(PackageParser.Package pkg,
5490 int parseFlags,
5491 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005492 String installerPackageName, PackageInstalledInfo res) {
5493
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005494 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005495 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005496 // First find the old package info and check signatures
5497 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005498 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005499 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005500 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5502 return;
5503 }
5504 }
Kenny Root85387d72010-08-26 10:13:11 -07005505 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005506 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005507 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005509 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005510 }
5511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005513 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005514 PackageParser.Package pkg,
5515 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005516 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 PackageParser.Package newPackage = null;
5518 String pkgName = deletedPackage.packageName;
5519 boolean deletedPkg = true;
5520 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005521
Jacek Surazski65e13172009-04-28 15:26:38 +02005522 String oldInstallerPackageName = null;
5523 synchronized (mPackages) {
5524 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005528 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 res.removedInfo)) {
5530 // If the existing package was'nt successfully deleted
5531 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5532 deletedPkg = false;
5533 } else {
5534 // Successfully deleted the old package. Now proceed with re-installation
5535 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005536 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005537 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005538 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5540 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005541 }
5542 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005543 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005544 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 res);
5546 updatedSettings = true;
5547 }
5548 }
5549
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005550 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 // remove package from internal structures. Note that we want deletePackageX to
5552 // delete the package data and cache directories that it created in
5553 // scanPackageLocked, unless those directories existed before we even tried to
5554 // install.
5555 if(updatedSettings) {
5556 deletePackageLI(
5557 pkgName, true,
5558 PackageManager.DONT_DELETE_DATA,
5559 res.removedInfo);
5560 }
5561 // Since we failed to install the new package we need to restore the old
5562 // package that we deleted.
5563 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005564 File restoreFile = new File(deletedPackage.mPath);
5565 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005566 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005567 return;
5568 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005569 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005570 boolean oldOnSd = isExternal(deletedPackage);
5571 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5572 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5573 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5574 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5575 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5576 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5577 return;
5578 }
5579 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005580 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005581 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005582 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005583 mSettings.writeLP();
5584 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005585 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 }
5587 }
5588 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005590 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005591 PackageParser.Package pkg,
5592 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005593 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 PackageParser.Package newPackage = null;
5595 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005596 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005597 PackageParser.PARSE_IS_SYSTEM;
5598 String packageName = deletedPackage.packageName;
5599 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5600 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005601 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 return;
5603 }
5604 PackageParser.Package oldPkg;
5605 PackageSetting oldPkgSetting;
5606 synchronized (mPackages) {
5607 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005608 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5610 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005611 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005612 return;
5613 }
5614 }
5615 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5616 res.removedInfo.removedPackage = packageName;
5617 // Remove existing system package
5618 removePackageLI(oldPkg, true);
5619 synchronized (mPackages) {
5620 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5621 }
5622
5623 // Successfully disabled the old package. Now proceed with re-installation
5624 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5625 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005626 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005628 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005629 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5630 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5631 }
5632 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005633 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 updatedSettings = true;
5635 }
5636
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005637 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005638 // Re installation failed. Restore old information
5639 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005640 if (newPackage != null) {
5641 removePackageLI(newPackage, true);
5642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005644 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005645 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005646 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005647 // Restore the old system information in Settings
5648 synchronized(mPackages) {
5649 if(updatedSettings) {
5650 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005651 mSettings.setInstallerPackageName(packageName,
5652 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 }
5654 mSettings.writeLP();
5655 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005656 } else {
5657 // If this is an update to an existing update, setup
5658 // to remove the existing update.
5659 synchronized (mPackages) {
5660 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5661 if (ps != null && ps.codePathString != null &&
5662 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5663 int installFlags = 0;
5664 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005665 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005666 }
5667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005668 }
5669 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005670
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005671 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005672 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005673 int retCode;
5674 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5675 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5676 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005677 if (mNoDexOpt) {
5678 /*
5679 * If we're in an engineering build, programs are lazily run
5680 * through dexopt. If the .dex file doesn't exist yet, it
5681 * will be created when the program is run next.
5682 */
5683 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5684 } else {
5685 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5686 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5687 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005688 }
5689 }
5690 return PackageManager.INSTALL_SUCCEEDED;
5691 }
5692
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005693 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005694 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005695 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 synchronized (mPackages) {
5697 //write settings. the installStatus will be incomplete at this stage.
5698 //note that the new package setting would have already been
5699 //added to mPackages. It hasn't been persisted yet.
5700 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5701 mSettings.writeLP();
5702 }
5703
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005704 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005705 != PackageManager.INSTALL_SUCCEEDED) {
5706 // Discontinue if moving dex files failed.
5707 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005709 if((res.returnCode = setPermissionsLI(newPackage))
5710 != PackageManager.INSTALL_SUCCEEDED) {
5711 if (mInstaller != null) {
5712 mInstaller.rmdex(newPackage.mScanPath);
5713 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005714 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005716 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005718 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005719 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005720 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005721 res.name = pkgName;
5722 res.uid = newPackage.applicationInfo.uid;
5723 res.pkg = newPackage;
5724 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005725 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5727 //to update install status
5728 mSettings.writeLP();
5729 }
5730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005731
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005732 private void installPackageLI(InstallArgs args,
5733 boolean newInstall, PackageInstalledInfo res) {
5734 int pFlags = args.flags;
5735 String installerPackageName = args.installerPackageName;
5736 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005737 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005738 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005739 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005740 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005741 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005742 // Result object to be returned
5743 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5744
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005745 // Retrieve PackageSettings and parse package
5746 int parseFlags = PackageParser.PARSE_CHATTY |
5747 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5748 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5749 parseFlags |= mDefParseFlags;
5750 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5751 pp.setSeparateProcesses(mSeparateProcesses);
5752 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5753 null, mMetrics, parseFlags);
5754 if (pkg == null) {
5755 res.returnCode = pp.getParseError();
5756 return;
5757 }
5758 String pkgName = res.name = pkg.packageName;
5759 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5760 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5761 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5762 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005763 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005764 }
5765 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5766 res.returnCode = pp.getParseError();
5767 return;
5768 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005769 // Get rid of all references to package scan path via parser.
5770 pp = null;
5771 String oldCodePath = null;
5772 boolean systemApp = false;
5773 synchronized (mPackages) {
5774 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005775 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5776 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005777 if (pkg.mOriginalPackages != null
5778 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005779 && mPackages.containsKey(oldName)) {
5780 // This package is derived from an original package,
5781 // and this device has been updating from that original
5782 // name. We must continue using the original name, so
5783 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005784 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005785 pkgName = pkg.packageName;
5786 replace = true;
5787 } else if (mPackages.containsKey(pkgName)) {
5788 // This package, under its official name, already exists
5789 // on the device; we should replace it.
5790 replace = true;
5791 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005792 }
5793 PackageSetting ps = mSettings.mPackages.get(pkgName);
5794 if (ps != null) {
5795 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5796 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5797 systemApp = (ps.pkg.applicationInfo.flags &
5798 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005799 }
5800 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005801 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005802
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005803 if (systemApp && onSd) {
5804 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005805 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005806 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5807 return;
5808 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005809
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005810 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5811 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5812 return;
5813 }
5814 // Set application objects path explicitly after the rename
5815 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005816 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005817 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005818 replacePackageLI(pkg, parseFlags, scanMode,
5819 installerPackageName, res);
5820 } else {
5821 installNewPackageLI(pkg, parseFlags, scanMode,
5822 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005823 }
5824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005825
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005826 private int setPermissionsLI(PackageParser.Package newPackage) {
5827 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005828 int retCode = 0;
5829 // TODO Gross hack but fix later. Ideally move this to be a post installation
5830 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005831 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005832 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 try {
5834 extractPublicFiles(newPackage, destResourceFile);
5835 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005836 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 -08005837 " forward-locked app.");
5838 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5839 } finally {
5840 //TODO clean up the extracted public files
5841 }
5842 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005843 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005844 newPackage.applicationInfo.uid);
5845 } else {
5846 final int filePermissions =
5847 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005848 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 newPackage.applicationInfo.uid);
5850 }
5851 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005852 // The permissions on the resource file was set when it was copied for
5853 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005857 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005858 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005860 // TODO Define new internal error
5861 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005862 }
5863 return PackageManager.INSTALL_SUCCEEDED;
5864 }
5865
Kenny Root85387d72010-08-26 10:13:11 -07005866 private static boolean isForwardLocked(PackageParser.Package pkg) {
5867 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 }
5869
Kenny Root85387d72010-08-26 10:13:11 -07005870 private static boolean isExternal(PackageParser.Package pkg) {
5871 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5872 }
5873
5874 private static boolean isSystemApp(PackageParser.Package pkg) {
5875 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5876 }
5877
5878 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5879 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005880 }
5881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005882 private void extractPublicFiles(PackageParser.Package newPackage,
5883 File publicZipFile) throws IOException {
5884 final ZipOutputStream publicZipOutStream =
5885 new ZipOutputStream(new FileOutputStream(publicZipFile));
5886 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5887
5888 // Copy manifest, resources.arsc and res directory to public zip
5889
5890 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5891 while (privateZipEntries.hasMoreElements()) {
5892 final ZipEntry zipEntry = privateZipEntries.nextElement();
5893 final String zipEntryName = zipEntry.getName();
5894 if ("AndroidManifest.xml".equals(zipEntryName)
5895 || "resources.arsc".equals(zipEntryName)
5896 || zipEntryName.startsWith("res/")) {
5897 try {
5898 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5899 } catch (IOException e) {
5900 try {
5901 publicZipOutStream.close();
5902 throw e;
5903 } finally {
5904 publicZipFile.delete();
5905 }
5906 }
5907 }
5908 }
5909
5910 publicZipOutStream.close();
5911 FileUtils.setPermissions(
5912 publicZipFile.getAbsolutePath(),
5913 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5914 -1, -1);
5915 }
5916
5917 private static void copyZipEntry(ZipEntry zipEntry,
5918 ZipFile inZipFile,
5919 ZipOutputStream outZipStream) throws IOException {
5920 byte[] buffer = new byte[4096];
5921 int num;
5922
5923 ZipEntry newEntry;
5924 if (zipEntry.getMethod() == ZipEntry.STORED) {
5925 // Preserve the STORED method of the input entry.
5926 newEntry = new ZipEntry(zipEntry);
5927 } else {
5928 // Create a new entry so that the compressed len is recomputed.
5929 newEntry = new ZipEntry(zipEntry.getName());
5930 }
5931 outZipStream.putNextEntry(newEntry);
5932
5933 InputStream data = inZipFile.getInputStream(zipEntry);
5934 while ((num = data.read(buffer)) > 0) {
5935 outZipStream.write(buffer, 0, num);
5936 }
5937 outZipStream.flush();
5938 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 private void deleteTempPackageFiles() {
5941 FilenameFilter filter = new FilenameFilter() {
5942 public boolean accept(File dir, String name) {
5943 return name.startsWith("vmdl") && name.endsWith(".tmp");
5944 }
5945 };
5946 String tmpFilesList[] = mAppInstallDir.list(filter);
5947 if(tmpFilesList == null) {
5948 return;
5949 }
5950 for(int i = 0; i < tmpFilesList.length; i++) {
5951 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5952 tmpFile.delete();
5953 }
5954 }
5955
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005956 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005957 File tmpPackageFile;
5958 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005959 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005960 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005961 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 return null;
5963 }
5964 try {
5965 FileUtils.setPermissions(
5966 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5967 -1, -1);
5968 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005969 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005970 return null;
5971 }
5972 return tmpPackageFile;
5973 }
5974
5975 public void deletePackage(final String packageName,
5976 final IPackageDeleteObserver observer,
5977 final int flags) {
5978 mContext.enforceCallingOrSelfPermission(
5979 android.Manifest.permission.DELETE_PACKAGES, null);
5980 // Queue up an async operation since the package deletion may take a little while.
5981 mHandler.post(new Runnable() {
5982 public void run() {
5983 mHandler.removeCallbacks(this);
5984 final boolean succeded = deletePackageX(packageName, true, true, flags);
5985 if (observer != null) {
5986 try {
5987 observer.packageDeleted(succeded);
5988 } catch (RemoteException e) {
5989 Log.i(TAG, "Observer no longer exists.");
5990 } //end catch
5991 } //end if
5992 } //end run
5993 });
5994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005996 /**
5997 * This method is an internal method that could be get invoked either
5998 * to delete an installed package or to clean up a failed installation.
5999 * After deleting an installed package, a broadcast is sent to notify any
6000 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006001 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006002 * installation wouldn't have sent the initial broadcast either
6003 * The key steps in deleting a package are
6004 * deleting the package information in internal structures like mPackages,
6005 * deleting the packages base directories through installd
6006 * updating mSettings to reflect current status
6007 * persisting settings for later use
6008 * sending a broadcast if necessary
6009 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6011 boolean deleteCodeAndResources, int flags) {
6012 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006013 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006015 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6016 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6017 try {
6018 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006019 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006020 return false;
6021 }
6022 } catch (RemoteException e) {
6023 }
6024
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006025 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006026 res = deletePackageLI(packageName, deleteCodeAndResources,
6027 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006031 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006032 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006033
6034 // If the removed package was a system update, the old system packaged
6035 // was re-enabled; we need to broadcast this information
6036 if (systemUpdate) {
6037 Bundle extras = new Bundle(1);
6038 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6039 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6040
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006041 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6042 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006043 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006045 // Force a gc here.
6046 Runtime.getRuntime().gc();
6047 // Delete the resources here after sending the broadcast to let
6048 // other processes clean up before deleting resources.
6049 if (info.args != null) {
6050 synchronized (mInstallLock) {
6051 info.args.doPostDeleteLI(deleteCodeAndResources);
6052 }
6053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006054 return res;
6055 }
6056
6057 static class PackageRemovedInfo {
6058 String removedPackage;
6059 int uid = -1;
6060 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006061 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006062 // Clean up resources deleted packages.
6063 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006064
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006065 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 Bundle extras = new Bundle(1);
6067 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6068 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6069 if (replacing) {
6070 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6071 }
6072 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006073 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 }
6075 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006076 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 }
6078 }
6079 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006081 /*
6082 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6083 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006084 * 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 -08006085 * delete a partially installed application.
6086 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006087 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006088 int flags) {
6089 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006090 if (outInfo != null) {
6091 outInfo.removedPackage = packageName;
6092 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006093 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 // Retrieve object to delete permissions for shared user later on
6095 PackageSetting deletedPs;
6096 synchronized (mPackages) {
6097 deletedPs = mSettings.mPackages.get(packageName);
6098 }
6099 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006100 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006101 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006102 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006103 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006104 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006105 + packageName + ", retcode=" + retCode);
6106 // we don't consider this to be a failure of the core package deletion
6107 }
6108 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006109 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110 PackageParser.Package pkg = mPackages.get(packageName);
6111 File dataDir = new File(pkg.applicationInfo.dataDir);
6112 dataDir.delete();
6113 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006114 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 }
6116 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006117 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006118 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6119 if (outInfo != null) {
6120 outInfo.removedUid = mSettings.removePackageLP(packageName);
6121 }
6122 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006123 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006124 if (deletedPs.sharedUser != null) {
6125 // remove permissions associated with package
6126 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6127 }
6128 }
6129 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006130 // remove from preferred activities.
6131 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6132 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6133 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6134 removed.add(pa);
6135 }
6136 }
6137 for (PreferredActivity pa : removed) {
6138 mSettings.mPreferredActivities.removeFilter(pa);
6139 }
6140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006142 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 }
6144 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 /*
6147 * Tries to delete system package.
6148 */
6149 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006150 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 ApplicationInfo applicationInfo = p.applicationInfo;
6152 //applicable for non-partially installed applications only
6153 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006154 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 return false;
6156 }
6157 PackageSetting ps = null;
6158 // Confirm if the system package has been updated
6159 // An updated system app can be deleted. This will also have to restore
6160 // the system pkg from system partition
6161 synchronized (mPackages) {
6162 ps = mSettings.getDisabledSystemPkg(p.packageName);
6163 }
6164 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006165 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 return false;
6167 } else {
6168 Log.i(TAG, "Deleting system pkg from data partition");
6169 }
6170 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006171 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006172 boolean deleteCodeAndResources = false;
6173 if (ps.versionCode < p.mVersionCode) {
6174 // Delete code and resources for downgrades
6175 deleteCodeAndResources = true;
6176 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6177 flags &= ~PackageManager.DONT_DELETE_DATA;
6178 }
6179 } else {
6180 // Preserve data by setting flag
6181 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6182 flags |= PackageManager.DONT_DELETE_DATA;
6183 }
6184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6186 if (!ret) {
6187 return false;
6188 }
6189 synchronized (mPackages) {
6190 // Reinstate the old system package
6191 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07006192 // Remove any native libraries. XXX needed?
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006193 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 }
6195 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006196 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006198 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006200 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006201 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 return false;
6203 }
6204 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006205 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 mSettings.writeLP();
6207 }
6208 return true;
6209 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6212 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6213 ApplicationInfo applicationInfo = p.applicationInfo;
6214 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006215 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006216 return false;
6217 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006218 if (outInfo != null) {
6219 outInfo.uid = applicationInfo.uid;
6220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006221
6222 // Delete package data from internal structures and also remove data if flag is set
6223 removePackageDataLI(p, outInfo, flags);
6224
6225 // Delete application code and resources
6226 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006227 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006228 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6229 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6230 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6231 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006232 }
6233 return true;
6234 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006235
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006236 /*
6237 * This method handles package deletion in general
6238 */
6239 private boolean deletePackageLI(String packageName,
6240 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6241 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006242 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 return false;
6244 }
6245 PackageParser.Package p;
6246 boolean dataOnly = false;
6247 synchronized (mPackages) {
6248 p = mPackages.get(packageName);
6249 if (p == null) {
6250 //this retrieves partially installed apps
6251 dataOnly = true;
6252 PackageSetting ps = mSettings.mPackages.get(packageName);
6253 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006254 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 return false;
6256 }
6257 p = ps.pkg;
6258 }
6259 }
6260 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006261 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006262 return false;
6263 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 if (dataOnly) {
6266 // Delete application data first
6267 removePackageDataLI(p, outInfo, flags);
6268 return true;
6269 }
6270 // At this point the package should have ApplicationInfo associated with it
6271 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006272 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006273 return false;
6274 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006275 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006276 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 Log.i(TAG, "Removing system package:"+p.packageName);
6278 // When an updated system application is deleted we delete the existing resources as well and
6279 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006280 ret = deleteSystemPackageLI(p, flags, outInfo);
6281 } else {
6282 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006283 // Kill application pre-emptively especially for apps on sd.
6284 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006285 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006287 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 public void clearApplicationUserData(final String packageName,
6291 final IPackageDataObserver observer) {
6292 mContext.enforceCallingOrSelfPermission(
6293 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6294 // Queue up an async operation since the package deletion may take a little while.
6295 mHandler.post(new Runnable() {
6296 public void run() {
6297 mHandler.removeCallbacks(this);
6298 final boolean succeeded;
6299 synchronized (mInstallLock) {
6300 succeeded = clearApplicationUserDataLI(packageName);
6301 }
6302 if (succeeded) {
6303 // invoke DeviceStorageMonitor's update method to clear any notifications
6304 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6305 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6306 if (dsm != null) {
6307 dsm.updateMemory();
6308 }
6309 }
6310 if(observer != null) {
6311 try {
6312 observer.onRemoveCompleted(packageName, succeeded);
6313 } catch (RemoteException e) {
6314 Log.i(TAG, "Observer no longer exists.");
6315 }
6316 } //end if observer
6317 } //end run
6318 });
6319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 private boolean clearApplicationUserDataLI(String packageName) {
6322 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006323 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006324 return false;
6325 }
6326 PackageParser.Package p;
6327 boolean dataOnly = false;
6328 synchronized (mPackages) {
6329 p = mPackages.get(packageName);
6330 if(p == null) {
6331 dataOnly = true;
6332 PackageSetting ps = mSettings.mPackages.get(packageName);
6333 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006334 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 return false;
6336 }
6337 p = ps.pkg;
6338 }
6339 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006340 boolean useEncryptedFSDir = false;
6341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006342 if(!dataOnly) {
6343 //need to check this only for fully installed applications
6344 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006345 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 return false;
6347 }
6348 final ApplicationInfo applicationInfo = p.applicationInfo;
6349 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006350 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 return false;
6352 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006353 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 }
6355 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006356 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006358 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 + packageName);
6360 return false;
6361 }
6362 }
6363 return true;
6364 }
6365
6366 public void deleteApplicationCacheFiles(final String packageName,
6367 final IPackageDataObserver observer) {
6368 mContext.enforceCallingOrSelfPermission(
6369 android.Manifest.permission.DELETE_CACHE_FILES, null);
6370 // Queue up an async operation since the package deletion may take a little while.
6371 mHandler.post(new Runnable() {
6372 public void run() {
6373 mHandler.removeCallbacks(this);
6374 final boolean succeded;
6375 synchronized (mInstallLock) {
6376 succeded = deleteApplicationCacheFilesLI(packageName);
6377 }
6378 if(observer != null) {
6379 try {
6380 observer.onRemoveCompleted(packageName, succeded);
6381 } catch (RemoteException e) {
6382 Log.i(TAG, "Observer no longer exists.");
6383 }
6384 } //end if observer
6385 } //end run
6386 });
6387 }
6388
6389 private boolean deleteApplicationCacheFilesLI(String packageName) {
6390 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006391 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006392 return false;
6393 }
6394 PackageParser.Package p;
6395 synchronized (mPackages) {
6396 p = mPackages.get(packageName);
6397 }
6398 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006399 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006400 return false;
6401 }
6402 final ApplicationInfo applicationInfo = p.applicationInfo;
6403 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006404 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 return false;
6406 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006407 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006408 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006409 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006411 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 + packageName);
6413 return false;
6414 }
6415 }
6416 return true;
6417 }
6418
6419 public void getPackageSizeInfo(final String packageName,
6420 final IPackageStatsObserver observer) {
6421 mContext.enforceCallingOrSelfPermission(
6422 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6423 // Queue up an async operation since the package deletion may take a little while.
6424 mHandler.post(new Runnable() {
6425 public void run() {
6426 mHandler.removeCallbacks(this);
6427 PackageStats lStats = new PackageStats(packageName);
6428 final boolean succeded;
6429 synchronized (mInstallLock) {
6430 succeded = getPackageSizeInfoLI(packageName, lStats);
6431 }
6432 if(observer != null) {
6433 try {
6434 observer.onGetStatsCompleted(lStats, succeded);
6435 } catch (RemoteException e) {
6436 Log.i(TAG, "Observer no longer exists.");
6437 }
6438 } //end if observer
6439 } //end run
6440 });
6441 }
6442
6443 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6444 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006445 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 return false;
6447 }
6448 PackageParser.Package p;
6449 boolean dataOnly = false;
6450 synchronized (mPackages) {
6451 p = mPackages.get(packageName);
6452 if(p == null) {
6453 dataOnly = true;
6454 PackageSetting ps = mSettings.mPackages.get(packageName);
6455 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006456 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006457 return false;
6458 }
6459 p = ps.pkg;
6460 }
6461 }
6462 String publicSrcDir = null;
6463 if(!dataOnly) {
6464 final ApplicationInfo applicationInfo = p.applicationInfo;
6465 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006466 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006467 return false;
6468 }
6469 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6470 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006471 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006472 if (mInstaller != null) {
6473 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006474 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006475 if (res < 0) {
6476 return false;
6477 } else {
6478 return true;
6479 }
6480 }
6481 return true;
6482 }
6483
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006486 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 }
6488
6489 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006490 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 }
6492
6493 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006494 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 }
6496
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006497 int getUidTargetSdkVersionLockedLP(int uid) {
6498 Object obj = mSettings.getUserIdLP(uid);
6499 if (obj instanceof SharedUserSetting) {
6500 SharedUserSetting sus = (SharedUserSetting)obj;
6501 final int N = sus.packages.size();
6502 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6503 Iterator<PackageSetting> it = sus.packages.iterator();
6504 int i=0;
6505 while (it.hasNext()) {
6506 PackageSetting ps = it.next();
6507 if (ps.pkg != null) {
6508 int v = ps.pkg.applicationInfo.targetSdkVersion;
6509 if (v < vers) vers = v;
6510 }
6511 }
6512 return vers;
6513 } else if (obj instanceof PackageSetting) {
6514 PackageSetting ps = (PackageSetting)obj;
6515 if (ps.pkg != null) {
6516 return ps.pkg.applicationInfo.targetSdkVersion;
6517 }
6518 }
6519 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6520 }
6521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006522 public void addPreferredActivity(IntentFilter filter, int match,
6523 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006525 if (mContext.checkCallingOrSelfPermission(
6526 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6527 != PackageManager.PERMISSION_GRANTED) {
6528 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6529 < Build.VERSION_CODES.FROYO) {
6530 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6531 + Binder.getCallingUid());
6532 return;
6533 }
6534 mContext.enforceCallingOrSelfPermission(
6535 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6536 }
6537
6538 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006539 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6540 mSettings.mPreferredActivities.addFilter(
6541 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006542 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006543 }
6544 }
6545
Satish Sampath8dbe6122009-06-02 23:35:54 +01006546 public void replacePreferredActivity(IntentFilter filter, int match,
6547 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006548 if (filter.countActions() != 1) {
6549 throw new IllegalArgumentException(
6550 "replacePreferredActivity expects filter to have only 1 action.");
6551 }
6552 if (filter.countCategories() != 1) {
6553 throw new IllegalArgumentException(
6554 "replacePreferredActivity expects filter to have only 1 category.");
6555 }
6556 if (filter.countDataAuthorities() != 0
6557 || filter.countDataPaths() != 0
6558 || filter.countDataSchemes() != 0
6559 || filter.countDataTypes() != 0) {
6560 throw new IllegalArgumentException(
6561 "replacePreferredActivity expects filter to have no data authorities, " +
6562 "paths, schemes or types.");
6563 }
6564 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006565 if (mContext.checkCallingOrSelfPermission(
6566 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6567 != PackageManager.PERMISSION_GRANTED) {
6568 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6569 < Build.VERSION_CODES.FROYO) {
6570 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6571 + Binder.getCallingUid());
6572 return;
6573 }
6574 mContext.enforceCallingOrSelfPermission(
6575 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6576 }
6577
Satish Sampath8dbe6122009-06-02 23:35:54 +01006578 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6579 String action = filter.getAction(0);
6580 String category = filter.getCategory(0);
6581 while (it.hasNext()) {
6582 PreferredActivity pa = it.next();
6583 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6584 it.remove();
6585 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6586 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6587 }
6588 }
6589 addPreferredActivity(filter, match, set, activity);
6590 }
6591 }
6592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006593 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006594 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006595 int uid = Binder.getCallingUid();
6596 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006597 if (pkg == null || pkg.applicationInfo.uid != uid) {
6598 if (mContext.checkCallingOrSelfPermission(
6599 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6600 != PackageManager.PERMISSION_GRANTED) {
6601 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6602 < Build.VERSION_CODES.FROYO) {
6603 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6604 + Binder.getCallingUid());
6605 return;
6606 }
6607 mContext.enforceCallingOrSelfPermission(
6608 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6609 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006610 }
6611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006612 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006613 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 }
6615 }
6616 }
6617
6618 boolean clearPackagePreferredActivitiesLP(String packageName) {
6619 boolean changed = false;
6620 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6621 while (it.hasNext()) {
6622 PreferredActivity pa = it.next();
6623 if (pa.mActivity.getPackageName().equals(packageName)) {
6624 it.remove();
6625 changed = true;
6626 }
6627 }
6628 return changed;
6629 }
6630
6631 public int getPreferredActivities(List<IntentFilter> outFilters,
6632 List<ComponentName> outActivities, String packageName) {
6633
6634 int num = 0;
6635 synchronized (mPackages) {
6636 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6637 while (it.hasNext()) {
6638 PreferredActivity pa = it.next();
6639 if (packageName == null
6640 || pa.mActivity.getPackageName().equals(packageName)) {
6641 if (outFilters != null) {
6642 outFilters.add(new IntentFilter(pa));
6643 }
6644 if (outActivities != null) {
6645 outActivities.add(pa.mActivity);
6646 }
6647 }
6648 }
6649 }
6650
6651 return num;
6652 }
6653
6654 public void setApplicationEnabledSetting(String appPackageName,
6655 int newState, int flags) {
6656 setEnabledSetting(appPackageName, null, newState, flags);
6657 }
6658
6659 public void setComponentEnabledSetting(ComponentName componentName,
6660 int newState, int flags) {
6661 setEnabledSetting(componentName.getPackageName(),
6662 componentName.getClassName(), newState, flags);
6663 }
6664
6665 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006666 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6668 || newState == COMPONENT_ENABLED_STATE_ENABLED
6669 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6670 throw new IllegalArgumentException("Invalid new component state: "
6671 + newState);
6672 }
6673 PackageSetting pkgSetting;
6674 final int uid = Binder.getCallingUid();
6675 final int permission = mContext.checkCallingPermission(
6676 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6677 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006678 boolean sendNow = false;
6679 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006680 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006681 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006682 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006684 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006686 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006688 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 }
6690 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006691 "Unknown component: " + packageName
6692 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 }
6694 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6695 throw new SecurityException(
6696 "Permission Denial: attempt to change component state from pid="
6697 + Binder.getCallingPid()
6698 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6699 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006700 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006702 if (pkgSetting.enabled == newState) {
6703 // Nothing to do
6704 return;
6705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006707 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 } else {
6709 // We're dealing with a component level state change
6710 switch (newState) {
6711 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006712 if (!pkgSetting.enableComponentLP(className)) {
6713 return;
6714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 break;
6716 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006717 if (!pkgSetting.disableComponentLP(className)) {
6718 return;
6719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 break;
6721 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006722 if (!pkgSetting.restoreComponentLP(className)) {
6723 return;
6724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006725 break;
6726 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006727 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006728 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 }
6730 }
6731 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006732 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006733 components = mPendingBroadcasts.get(packageName);
6734 boolean newPackage = components == null;
6735 if (newPackage) {
6736 components = new ArrayList<String>();
6737 }
6738 if (!components.contains(componentName)) {
6739 components.add(componentName);
6740 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006741 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6742 sendNow = true;
6743 // Purge entry from pending broadcast list if another one exists already
6744 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006745 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006746 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006747 if (newPackage) {
6748 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006749 }
6750 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6751 // Schedule a message
6752 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6753 }
6754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757 long callingId = Binder.clearCallingIdentity();
6758 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006759 if (sendNow) {
6760 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006761 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006762 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 } finally {
6764 Binder.restoreCallingIdentity(callingId);
6765 }
6766 }
6767
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006768 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006769 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6770 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6771 + " components=" + componentNames);
6772 Bundle extras = new Bundle(4);
6773 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6774 String nameList[] = new String[componentNames.size()];
6775 componentNames.toArray(nameList);
6776 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006777 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6778 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006779 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006780 }
6781
Jacek Surazski65e13172009-04-28 15:26:38 +02006782 public String getInstallerPackageName(String packageName) {
6783 synchronized (mPackages) {
6784 PackageSetting pkg = mSettings.mPackages.get(packageName);
6785 if (pkg == null) {
6786 throw new IllegalArgumentException("Unknown package: " + packageName);
6787 }
6788 return pkg.installerPackageName;
6789 }
6790 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006792 public int getApplicationEnabledSetting(String appPackageName) {
6793 synchronized (mPackages) {
6794 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6795 if (pkg == null) {
6796 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6797 }
6798 return pkg.enabled;
6799 }
6800 }
6801
6802 public int getComponentEnabledSetting(ComponentName componentName) {
6803 synchronized (mPackages) {
6804 final String packageNameStr = componentName.getPackageName();
6805 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6806 if (pkg == null) {
6807 throw new IllegalArgumentException("Unknown component: " + componentName);
6808 }
6809 final String classNameStr = componentName.getClassName();
6810 return pkg.currentEnabledStateLP(classNameStr);
6811 }
6812 }
6813
6814 public void enterSafeMode() {
6815 if (!mSystemReady) {
6816 mSafeMode = true;
6817 }
6818 }
6819
6820 public void systemReady() {
6821 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006822
6823 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006824 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006825 mContext.getContentResolver(),
6826 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006827 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006828 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006829 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006831 }
6832
6833 public boolean isSafeMode() {
6834 return mSafeMode;
6835 }
6836
6837 public boolean hasSystemUidErrors() {
6838 return mHasSystemUidErrors;
6839 }
6840
6841 static String arrayToString(int[] array) {
6842 StringBuffer buf = new StringBuffer(128);
6843 buf.append('[');
6844 if (array != null) {
6845 for (int i=0; i<array.length; i++) {
6846 if (i > 0) buf.append(", ");
6847 buf.append(array[i]);
6848 }
6849 }
6850 buf.append(']');
6851 return buf.toString();
6852 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006854 @Override
6855 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6856 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6857 != PackageManager.PERMISSION_GRANTED) {
6858 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6859 + Binder.getCallingPid()
6860 + ", uid=" + Binder.getCallingUid()
6861 + " without permission "
6862 + android.Manifest.permission.DUMP);
6863 return;
6864 }
6865
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006866 String packageName = null;
6867
6868 int opti = 0;
6869 while (opti < args.length) {
6870 String opt = args[opti];
6871 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6872 break;
6873 }
6874 opti++;
6875 if ("-a".equals(opt)) {
6876 // Right now we only know how to print all.
6877 } else if ("-h".equals(opt)) {
6878 pw.println("Package manager dump options:");
6879 pw.println(" [-h] [cmd] ...");
6880 pw.println(" cmd may be one of:");
6881 pw.println(" [package.name]: info about given package");
6882 return;
6883 } else {
6884 pw.println("Unknown argument: " + opt + "; use -h for help");
6885 }
6886 }
6887
6888 // Is the caller requesting to dump a particular piece of data?
6889 if (opti < args.length) {
6890 String cmd = args[opti];
6891 opti++;
6892 // Is this a package name?
6893 if ("android".equals(cmd) || cmd.contains(".")) {
6894 packageName = cmd;
6895 }
6896 }
6897
6898 boolean printedTitle = false;
6899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006900 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006901 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6902 printedTitle = true;
6903 }
6904 if (mReceivers.dump(pw, printedTitle
6905 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6906 " ", packageName)) {
6907 printedTitle = true;
6908 }
6909 if (mServices.dump(pw, printedTitle
6910 ? "\nService Resolver Table:" : "Service Resolver Table:",
6911 " ", packageName)) {
6912 printedTitle = true;
6913 }
6914 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6915 ? "\nPreferred Activities:" : "Preferred Activities:",
6916 " ", packageName)) {
6917 printedTitle = true;
6918 }
6919 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006920 {
6921 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006922 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6923 continue;
6924 }
6925 if (!printedSomething) {
6926 if (printedTitle) pw.println(" ");
6927 pw.println("Permissions:");
6928 printedSomething = true;
6929 printedTitle = true;
6930 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006931 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6932 pw.print(Integer.toHexString(System.identityHashCode(p)));
6933 pw.println("):");
6934 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6935 pw.print(" uid="); pw.print(p.uid);
6936 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006937 pw.print(" type="); pw.print(p.type);
6938 pw.print(" prot="); pw.println(p.protectionLevel);
6939 if (p.packageSetting != null) {
6940 pw.print(" packageSetting="); pw.println(p.packageSetting);
6941 }
6942 if (p.perm != null) {
6943 pw.print(" perm="); pw.println(p.perm);
6944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006945 }
6946 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006947 printedSomething = false;
6948 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006949 {
6950 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006951 if (packageName != null && !packageName.equals(ps.realName)
6952 && !packageName.equals(ps.name)) {
6953 continue;
6954 }
6955 if (!printedSomething) {
6956 if (printedTitle) pw.println(" ");
6957 pw.println("Packages:");
6958 printedSomething = true;
6959 printedTitle = true;
6960 }
6961 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006962 pw.print(" Package [");
6963 pw.print(ps.realName != null ? ps.realName : ps.name);
6964 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006965 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6966 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006967 if (ps.realName != null) {
6968 pw.print(" compat name="); pw.println(ps.name);
6969 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006970 pw.print(" userId="); pw.print(ps.userId);
6971 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6972 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6973 pw.print(" pkg="); pw.println(ps.pkg);
6974 pw.print(" codePath="); pw.println(ps.codePathString);
6975 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07006976 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07006977 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006978 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006979 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006980 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07006981 if (ps.pkg.mOperationPending) {
6982 pw.println(" mOperationPending=true");
6983 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006984 pw.print(" supportsScreens=[");
6985 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006986 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07006987 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
6988 if (!first) pw.print(", ");
6989 first = false;
6990 pw.print("small");
6991 }
6992 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006993 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006994 if (!first) pw.print(", ");
6995 first = false;
6996 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006997 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006998 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006999 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007000 if (!first) pw.print(", ");
7001 first = false;
7002 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007003 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007004 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007005 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007006 if (!first) pw.print(", ");
7007 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007008 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007009 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007010 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007011 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007012 if (!first) pw.print(", ");
7013 first = false;
7014 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007016 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007017 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7018 if (!first) pw.print(", ");
7019 first = false;
7020 pw.print("anyDensity");
7021 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007022 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007023 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007024 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7025 pw.print(" signatures="); pw.println(ps.signatures);
7026 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007027 pw.print(" haveGids="); pw.println(ps.haveGids);
7028 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007029 pw.print(" installStatus="); pw.print(ps.installStatus);
7030 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 if (ps.disabledComponents.size() > 0) {
7032 pw.println(" disabledComponents:");
7033 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007034 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 }
7036 }
7037 if (ps.enabledComponents.size() > 0) {
7038 pw.println(" enabledComponents:");
7039 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007040 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007041 }
7042 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007043 if (ps.grantedPermissions.size() > 0) {
7044 pw.println(" grantedPermissions:");
7045 for (String s : ps.grantedPermissions) {
7046 pw.print(" "); pw.println(s);
7047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007049 }
7050 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007051 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007052 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007053 for (HashMap.Entry<String, String> e
7054 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007055 if (packageName != null && !packageName.equals(e.getKey())
7056 && !packageName.equals(e.getValue())) {
7057 continue;
7058 }
7059 if (!printedSomething) {
7060 if (printedTitle) pw.println(" ");
7061 pw.println("Renamed packages:");
7062 printedSomething = true;
7063 printedTitle = true;
7064 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007065 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7066 pw.println(e.getValue());
7067 }
7068 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007069 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007070 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007071 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007072 if (packageName != null && !packageName.equals(ps.realName)
7073 && !packageName.equals(ps.name)) {
7074 continue;
7075 }
7076 if (!printedSomething) {
7077 if (printedTitle) pw.println(" ");
7078 pw.println("Hidden system packages:");
7079 printedSomething = true;
7080 printedTitle = true;
7081 }
7082 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007083 pw.print(ps.realName != null ? ps.realName : ps.name);
7084 pw.print("] (");
7085 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7086 pw.println("):");
7087 if (ps.realName != null) {
7088 pw.print(" compat name="); pw.println(ps.name);
7089 }
7090 pw.print(" userId="); pw.println(ps.userId);
7091 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7092 pw.print(" codePath="); pw.println(ps.codePathString);
7093 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7094 }
7095 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007096 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 {
7098 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007099 if (packageName != null && su != packageSharedUser) {
7100 continue;
7101 }
7102 if (!printedSomething) {
7103 if (printedTitle) pw.println(" ");
7104 pw.println("Shared users:");
7105 printedSomething = true;
7106 printedTitle = true;
7107 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007108 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7109 pw.print(Integer.toHexString(System.identityHashCode(su)));
7110 pw.println("):");
7111 pw.print(" userId="); pw.print(su.userId);
7112 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007113 pw.println(" grantedPermissions:");
7114 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007115 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007117 }
7118 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007119
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007120 if (packageName == null) {
7121 if (printedTitle) pw.println(" ");
7122 printedTitle = true;
7123 pw.println("Settings parse messages:");
7124 pw.println(mSettings.mReadMessages.toString());
7125
7126 pw.println(" ");
7127 pw.println("Package warning messages:");
7128 File fname = getSettingsProblemFile();
7129 FileInputStream in;
7130 try {
7131 in = new FileInputStream(fname);
7132 int avail = in.available();
7133 byte[] data = new byte[avail];
7134 in.read(data);
7135 pw.println(new String(data));
7136 } catch (FileNotFoundException e) {
7137 } catch (IOException e) {
7138 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007140 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007141
7142 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007143 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007144 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007145 if (packageName != null && !packageName.equals(p.info.packageName)) {
7146 continue;
7147 }
7148 if (!printedSomething) {
7149 if (printedTitle) pw.println(" ");
7150 pw.println("Registered ContentProviders:");
7151 printedSomething = true;
7152 printedTitle = true;
7153 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007154 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007155 pw.println(p.toString());
7156 }
7157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007158 }
7159
7160 static final class BasePermission {
7161 final static int TYPE_NORMAL = 0;
7162 final static int TYPE_BUILTIN = 1;
7163 final static int TYPE_DYNAMIC = 2;
7164
7165 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007166 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007167 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007168 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007169 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007170 PackageParser.Permission perm;
7171 PermissionInfo pendingInfo;
7172 int uid;
7173 int[] gids;
7174
7175 BasePermission(String _name, String _sourcePackage, int _type) {
7176 name = _name;
7177 sourcePackage = _sourcePackage;
7178 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007179 // Default to most conservative protection level.
7180 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7181 }
7182
7183 public String toString() {
7184 return "BasePermission{"
7185 + Integer.toHexString(System.identityHashCode(this))
7186 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007187 }
7188 }
7189
7190 static class PackageSignatures {
7191 private Signature[] mSignatures;
7192
7193 PackageSignatures(Signature[] sigs) {
7194 assignSignatures(sigs);
7195 }
7196
7197 PackageSignatures() {
7198 }
7199
7200 void writeXml(XmlSerializer serializer, String tagName,
7201 ArrayList<Signature> pastSignatures) throws IOException {
7202 if (mSignatures == null) {
7203 return;
7204 }
7205 serializer.startTag(null, tagName);
7206 serializer.attribute(null, "count",
7207 Integer.toString(mSignatures.length));
7208 for (int i=0; i<mSignatures.length; i++) {
7209 serializer.startTag(null, "cert");
7210 final Signature sig = mSignatures[i];
7211 final int sigHash = sig.hashCode();
7212 final int numPast = pastSignatures.size();
7213 int j;
7214 for (j=0; j<numPast; j++) {
7215 Signature pastSig = pastSignatures.get(j);
7216 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7217 serializer.attribute(null, "index", Integer.toString(j));
7218 break;
7219 }
7220 }
7221 if (j >= numPast) {
7222 pastSignatures.add(sig);
7223 serializer.attribute(null, "index", Integer.toString(numPast));
7224 serializer.attribute(null, "key", sig.toCharsString());
7225 }
7226 serializer.endTag(null, "cert");
7227 }
7228 serializer.endTag(null, tagName);
7229 }
7230
7231 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7232 throws IOException, XmlPullParserException {
7233 String countStr = parser.getAttributeValue(null, "count");
7234 if (countStr == null) {
7235 reportSettingsProblem(Log.WARN,
7236 "Error in package manager settings: <signatures> has"
7237 + " no count at " + parser.getPositionDescription());
7238 XmlUtils.skipCurrentTag(parser);
7239 }
7240 final int count = Integer.parseInt(countStr);
7241 mSignatures = new Signature[count];
7242 int pos = 0;
7243
7244 int outerDepth = parser.getDepth();
7245 int type;
7246 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7247 && (type != XmlPullParser.END_TAG
7248 || parser.getDepth() > outerDepth)) {
7249 if (type == XmlPullParser.END_TAG
7250 || type == XmlPullParser.TEXT) {
7251 continue;
7252 }
7253
7254 String tagName = parser.getName();
7255 if (tagName.equals("cert")) {
7256 if (pos < count) {
7257 String index = parser.getAttributeValue(null, "index");
7258 if (index != null) {
7259 try {
7260 int idx = Integer.parseInt(index);
7261 String key = parser.getAttributeValue(null, "key");
7262 if (key == null) {
7263 if (idx >= 0 && idx < pastSignatures.size()) {
7264 Signature sig = pastSignatures.get(idx);
7265 if (sig != null) {
7266 mSignatures[pos] = pastSignatures.get(idx);
7267 pos++;
7268 } else {
7269 reportSettingsProblem(Log.WARN,
7270 "Error in package manager settings: <cert> "
7271 + "index " + index + " is not defined at "
7272 + parser.getPositionDescription());
7273 }
7274 } else {
7275 reportSettingsProblem(Log.WARN,
7276 "Error in package manager settings: <cert> "
7277 + "index " + index + " is out of bounds at "
7278 + parser.getPositionDescription());
7279 }
7280 } else {
7281 while (pastSignatures.size() <= idx) {
7282 pastSignatures.add(null);
7283 }
7284 Signature sig = new Signature(key);
7285 pastSignatures.set(idx, sig);
7286 mSignatures[pos] = sig;
7287 pos++;
7288 }
7289 } catch (NumberFormatException e) {
7290 reportSettingsProblem(Log.WARN,
7291 "Error in package manager settings: <cert> "
7292 + "index " + index + " is not a number at "
7293 + parser.getPositionDescription());
7294 }
7295 } else {
7296 reportSettingsProblem(Log.WARN,
7297 "Error in package manager settings: <cert> has"
7298 + " no index at " + parser.getPositionDescription());
7299 }
7300 } else {
7301 reportSettingsProblem(Log.WARN,
7302 "Error in package manager settings: too "
7303 + "many <cert> tags, expected " + count
7304 + " at " + parser.getPositionDescription());
7305 }
7306 } else {
7307 reportSettingsProblem(Log.WARN,
7308 "Unknown element under <cert>: "
7309 + parser.getName());
7310 }
7311 XmlUtils.skipCurrentTag(parser);
7312 }
7313
7314 if (pos < count) {
7315 // Should never happen -- there is an error in the written
7316 // settings -- but if it does we don't want to generate
7317 // a bad array.
7318 Signature[] newSigs = new Signature[pos];
7319 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7320 mSignatures = newSigs;
7321 }
7322 }
7323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007324 private void assignSignatures(Signature[] sigs) {
7325 if (sigs == null) {
7326 mSignatures = null;
7327 return;
7328 }
7329 mSignatures = new Signature[sigs.length];
7330 for (int i=0; i<sigs.length; i++) {
7331 mSignatures[i] = sigs[i];
7332 }
7333 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007335 @Override
7336 public String toString() {
7337 StringBuffer buf = new StringBuffer(128);
7338 buf.append("PackageSignatures{");
7339 buf.append(Integer.toHexString(System.identityHashCode(this)));
7340 buf.append(" [");
7341 if (mSignatures != null) {
7342 for (int i=0; i<mSignatures.length; i++) {
7343 if (i > 0) buf.append(", ");
7344 buf.append(Integer.toHexString(
7345 System.identityHashCode(mSignatures[i])));
7346 }
7347 }
7348 buf.append("]}");
7349 return buf.toString();
7350 }
7351 }
7352
7353 static class PreferredActivity extends IntentFilter {
7354 final int mMatch;
7355 final String[] mSetPackages;
7356 final String[] mSetClasses;
7357 final String[] mSetComponents;
7358 final ComponentName mActivity;
7359 final String mShortActivity;
7360 String mParseError;
7361
7362 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7363 ComponentName activity) {
7364 super(filter);
7365 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7366 mActivity = activity;
7367 mShortActivity = activity.flattenToShortString();
7368 mParseError = null;
7369 if (set != null) {
7370 final int N = set.length;
7371 String[] myPackages = new String[N];
7372 String[] myClasses = new String[N];
7373 String[] myComponents = new String[N];
7374 for (int i=0; i<N; i++) {
7375 ComponentName cn = set[i];
7376 if (cn == null) {
7377 mSetPackages = null;
7378 mSetClasses = null;
7379 mSetComponents = null;
7380 return;
7381 }
7382 myPackages[i] = cn.getPackageName().intern();
7383 myClasses[i] = cn.getClassName().intern();
7384 myComponents[i] = cn.flattenToShortString().intern();
7385 }
7386 mSetPackages = myPackages;
7387 mSetClasses = myClasses;
7388 mSetComponents = myComponents;
7389 } else {
7390 mSetPackages = null;
7391 mSetClasses = null;
7392 mSetComponents = null;
7393 }
7394 }
7395
7396 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7397 IOException {
7398 mShortActivity = parser.getAttributeValue(null, "name");
7399 mActivity = ComponentName.unflattenFromString(mShortActivity);
7400 if (mActivity == null) {
7401 mParseError = "Bad activity name " + mShortActivity;
7402 }
7403 String matchStr = parser.getAttributeValue(null, "match");
7404 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7405 String setCountStr = parser.getAttributeValue(null, "set");
7406 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7407
7408 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7409 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7410 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7411
7412 int setPos = 0;
7413
7414 int outerDepth = parser.getDepth();
7415 int type;
7416 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7417 && (type != XmlPullParser.END_TAG
7418 || parser.getDepth() > outerDepth)) {
7419 if (type == XmlPullParser.END_TAG
7420 || type == XmlPullParser.TEXT) {
7421 continue;
7422 }
7423
7424 String tagName = parser.getName();
7425 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7426 // + parser.getDepth() + " tag=" + tagName);
7427 if (tagName.equals("set")) {
7428 String name = parser.getAttributeValue(null, "name");
7429 if (name == null) {
7430 if (mParseError == null) {
7431 mParseError = "No name in set tag in preferred activity "
7432 + mShortActivity;
7433 }
7434 } else if (setPos >= setCount) {
7435 if (mParseError == null) {
7436 mParseError = "Too many set tags in preferred activity "
7437 + mShortActivity;
7438 }
7439 } else {
7440 ComponentName cn = ComponentName.unflattenFromString(name);
7441 if (cn == null) {
7442 if (mParseError == null) {
7443 mParseError = "Bad set name " + name + " in preferred activity "
7444 + mShortActivity;
7445 }
7446 } else {
7447 myPackages[setPos] = cn.getPackageName();
7448 myClasses[setPos] = cn.getClassName();
7449 myComponents[setPos] = name;
7450 setPos++;
7451 }
7452 }
7453 XmlUtils.skipCurrentTag(parser);
7454 } else if (tagName.equals("filter")) {
7455 //Log.i(TAG, "Starting to parse filter...");
7456 readFromXml(parser);
7457 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7458 // + parser.getDepth() + " tag=" + parser.getName());
7459 } else {
7460 reportSettingsProblem(Log.WARN,
7461 "Unknown element under <preferred-activities>: "
7462 + parser.getName());
7463 XmlUtils.skipCurrentTag(parser);
7464 }
7465 }
7466
7467 if (setPos != setCount) {
7468 if (mParseError == null) {
7469 mParseError = "Not enough set tags (expected " + setCount
7470 + " but found " + setPos + ") in " + mShortActivity;
7471 }
7472 }
7473
7474 mSetPackages = myPackages;
7475 mSetClasses = myClasses;
7476 mSetComponents = myComponents;
7477 }
7478
7479 public void writeToXml(XmlSerializer serializer) throws IOException {
7480 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7481 serializer.attribute(null, "name", mShortActivity);
7482 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7483 serializer.attribute(null, "set", Integer.toString(NS));
7484 for (int s=0; s<NS; s++) {
7485 serializer.startTag(null, "set");
7486 serializer.attribute(null, "name", mSetComponents[s]);
7487 serializer.endTag(null, "set");
7488 }
7489 serializer.startTag(null, "filter");
7490 super.writeToXml(serializer);
7491 serializer.endTag(null, "filter");
7492 }
7493
7494 boolean sameSet(List<ResolveInfo> query, int priority) {
7495 if (mSetPackages == null) return false;
7496 final int NQ = query.size();
7497 final int NS = mSetPackages.length;
7498 int numMatch = 0;
7499 for (int i=0; i<NQ; i++) {
7500 ResolveInfo ri = query.get(i);
7501 if (ri.priority != priority) continue;
7502 ActivityInfo ai = ri.activityInfo;
7503 boolean good = false;
7504 for (int j=0; j<NS; j++) {
7505 if (mSetPackages[j].equals(ai.packageName)
7506 && mSetClasses[j].equals(ai.name)) {
7507 numMatch++;
7508 good = true;
7509 break;
7510 }
7511 }
7512 if (!good) return false;
7513 }
7514 return numMatch == NS;
7515 }
7516 }
7517
7518 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007519 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007521 HashSet<String> grantedPermissions = new HashSet<String>();
7522 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007524 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007525 setFlags(pkgFlags);
7526 }
7527
7528 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007529 this.pkgFlags = pkgFlags & (
7530 ApplicationInfo.FLAG_SYSTEM |
7531 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007532 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007533 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 }
7535 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 /**
7538 * Settings base class for pending and resolved classes.
7539 */
7540 static class PackageSettingBase extends GrantedPermissions {
7541 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007542 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007543 File codePath;
7544 String codePathString;
7545 File resourcePath;
7546 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007547 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007548 String obbPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549 private long timeStamp;
7550 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007551 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007552
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007553 boolean uidError;
7554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007555 PackageSignatures signatures = new PackageSignatures();
7556
7557 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007558 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 /* Explicitly disabled components */
7561 HashSet<String> disabledComponents = new HashSet<String>(0);
7562 /* Explicitly enabled components */
7563 HashSet<String> enabledComponents = new HashSet<String>(0);
7564 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7565 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007566
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007567 PackageSettingBase origPackage;
7568
Jacek Surazski65e13172009-04-28 15:26:38 +02007569 /* package name of the app that installed this package */
7570 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007571
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007572 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007573 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 super(pkgFlags);
7575 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007576 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007577 init(codePath, resourcePath, pVersionCode);
7578 }
7579
7580 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007581 this.codePath = codePath;
7582 this.codePathString = codePath.toString();
7583 this.resourcePath = resourcePath;
7584 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007585 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586 }
Kenny Root85387d72010-08-26 10:13:11 -07007587
Jacek Surazski65e13172009-04-28 15:26:38 +02007588 public void setInstallerPackageName(String packageName) {
7589 installerPackageName = packageName;
7590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007591
Jacek Surazski65e13172009-04-28 15:26:38 +02007592 String getInstallerPackageName() {
7593 return installerPackageName;
7594 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007596 public void setInstallStatus(int newStatus) {
7597 installStatus = newStatus;
7598 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007600 public int getInstallStatus() {
7601 return installStatus;
7602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 public void setTimeStamp(long newStamp) {
7605 if (newStamp != timeStamp) {
7606 timeStamp = newStamp;
7607 timeStampString = Long.toString(newStamp);
7608 }
7609 }
7610
7611 public void setTimeStamp(long newStamp, String newStampStr) {
7612 timeStamp = newStamp;
7613 timeStampString = newStampStr;
7614 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 public long getTimeStamp() {
7617 return timeStamp;
7618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007620 public String getTimeStampStr() {
7621 return timeStampString;
7622 }
7623
7624 public void copyFrom(PackageSettingBase base) {
7625 grantedPermissions = base.grantedPermissions;
7626 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 timeStamp = base.timeStamp;
7629 timeStampString = base.timeStampString;
7630 signatures = base.signatures;
7631 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007632 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 disabledComponents = base.disabledComponents;
7634 enabledComponents = base.enabledComponents;
7635 enabled = base.enabled;
7636 installStatus = base.installStatus;
7637 }
7638
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007639 boolean enableComponentLP(String componentClassName) {
7640 boolean changed = disabledComponents.remove(componentClassName);
7641 changed |= enabledComponents.add(componentClassName);
7642 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643 }
7644
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007645 boolean disableComponentLP(String componentClassName) {
7646 boolean changed = enabledComponents.remove(componentClassName);
7647 changed |= disabledComponents.add(componentClassName);
7648 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007649 }
7650
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007651 boolean restoreComponentLP(String componentClassName) {
7652 boolean changed = enabledComponents.remove(componentClassName);
7653 changed |= disabledComponents.remove(componentClassName);
7654 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 }
7656
7657 int currentEnabledStateLP(String componentName) {
7658 if (enabledComponents.contains(componentName)) {
7659 return COMPONENT_ENABLED_STATE_ENABLED;
7660 } else if (disabledComponents.contains(componentName)) {
7661 return COMPONENT_ENABLED_STATE_DISABLED;
7662 } else {
7663 return COMPONENT_ENABLED_STATE_DEFAULT;
7664 }
7665 }
7666 }
7667
7668 /**
7669 * Settings data for a particular package we know about.
7670 */
7671 static final class PackageSetting extends PackageSettingBase {
7672 int userId;
7673 PackageParser.Package pkg;
7674 SharedUserSetting sharedUser;
7675
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007676 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007677 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007678 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007679 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007680
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007681 @Override
7682 public String toString() {
7683 return "PackageSetting{"
7684 + Integer.toHexString(System.identityHashCode(this))
7685 + " " + name + "/" + userId + "}";
7686 }
7687 }
7688
7689 /**
7690 * Settings data for a particular shared user ID we know about.
7691 */
7692 static final class SharedUserSetting extends GrantedPermissions {
7693 final String name;
7694 int userId;
7695 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7696 final PackageSignatures signatures = new PackageSignatures();
7697
7698 SharedUserSetting(String _name, int _pkgFlags) {
7699 super(_pkgFlags);
7700 name = _name;
7701 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007703 @Override
7704 public String toString() {
7705 return "SharedUserSetting{"
7706 + Integer.toHexString(System.identityHashCode(this))
7707 + " " + name + "/" + userId + "}";
7708 }
7709 }
7710
7711 /**
7712 * Holds information about dynamic settings.
7713 */
7714 private static final class Settings {
7715 private final File mSettingsFilename;
7716 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007717 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 private final HashMap<String, PackageSetting> mPackages =
7719 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007720 // List of replaced system applications
7721 final HashMap<String, PackageSetting> mDisabledSysPackages =
7722 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007723
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007724 // These are the last platform API version we were using for
7725 // the apps installed on internal and external storage. It is
7726 // used to grant newer permissions one time during a system upgrade.
7727 int mInternalSdkPlatform;
7728 int mExternalSdkPlatform;
7729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 // The user's preferred activities associated with particular intent
7731 // filters.
7732 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7733 new IntentResolver<PreferredActivity, PreferredActivity>() {
7734 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007735 protected String packageForFilter(PreferredActivity filter) {
7736 return filter.mActivity.getPackageName();
7737 }
7738 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007739 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007741 out.print(prefix); out.print(
7742 Integer.toHexString(System.identityHashCode(filter)));
7743 out.print(' ');
7744 out.print(filter.mActivity.flattenToShortString());
7745 out.print(" match=0x");
7746 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007748 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007750 out.print(prefix); out.print(" ");
7751 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752 }
7753 }
7754 }
7755 };
7756 private final HashMap<String, SharedUserSetting> mSharedUsers =
7757 new HashMap<String, SharedUserSetting>();
7758 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7759 private final SparseArray<Object> mOtherUserIds =
7760 new SparseArray<Object>();
7761
7762 // For reading/writing settings file.
7763 private final ArrayList<Signature> mPastSignatures =
7764 new ArrayList<Signature>();
7765
7766 // Mapping from permission names to info about them.
7767 final HashMap<String, BasePermission> mPermissions =
7768 new HashMap<String, BasePermission>();
7769
7770 // Mapping from permission tree names to info about them.
7771 final HashMap<String, BasePermission> mPermissionTrees =
7772 new HashMap<String, BasePermission>();
7773
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007774 // Packages that have been uninstalled and still need their external
7775 // storage data deleted.
7776 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7777
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007778 // Packages that have been renamed since they were first installed.
7779 // Keys are the new names of the packages, values are the original
7780 // names. The packages appear everwhere else under their original
7781 // names.
7782 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007784 private final StringBuilder mReadMessages = new StringBuilder();
7785
7786 private static final class PendingPackage extends PackageSettingBase {
7787 final int sharedId;
7788
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007789 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007790 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007791 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007792 this.sharedId = sharedId;
7793 }
7794 }
7795 private final ArrayList<PendingPackage> mPendingPackages
7796 = new ArrayList<PendingPackage>();
7797
7798 Settings() {
7799 File dataDir = Environment.getDataDirectory();
7800 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007801 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7802 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007804 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 FileUtils.setPermissions(systemDir.toString(),
7806 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7807 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7808 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007809 FileUtils.setPermissions(systemSecureDir.toString(),
7810 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7811 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7812 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007813 mSettingsFilename = new File(systemDir, "packages.xml");
7814 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007815 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 }
7817
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007818 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007819 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 int pkgFlags, boolean create, boolean add) {
7821 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007822 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007823 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 return p;
7825 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007826
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007827 PackageSetting peekPackageLP(String name) {
7828 return mPackages.get(name);
7829 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007830 PackageSetting p = mPackages.get(name);
7831 if (p != null && p.codePath.getPath().equals(codePath)) {
7832 return p;
7833 }
7834 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007835 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007838 void setInstallStatus(String pkgName, int status) {
7839 PackageSetting p = mPackages.get(pkgName);
7840 if(p != null) {
7841 if(p.getInstallStatus() != status) {
7842 p.setInstallStatus(status);
7843 }
7844 }
7845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007846
Jacek Surazski65e13172009-04-28 15:26:38 +02007847 void setInstallerPackageName(String pkgName,
7848 String installerPkgName) {
7849 PackageSetting p = mPackages.get(pkgName);
7850 if(p != null) {
7851 p.setInstallerPackageName(installerPkgName);
7852 }
7853 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007854
Jacek Surazski65e13172009-04-28 15:26:38 +02007855 String getInstallerPackageName(String pkgName) {
7856 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007857 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007858 }
7859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007860 int getInstallStatus(String pkgName) {
7861 PackageSetting p = mPackages.get(pkgName);
7862 if(p != null) {
7863 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007864 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007865 return -1;
7866 }
7867
7868 SharedUserSetting getSharedUserLP(String name,
7869 int pkgFlags, boolean create) {
7870 SharedUserSetting s = mSharedUsers.get(name);
7871 if (s == null) {
7872 if (!create) {
7873 return null;
7874 }
7875 s = new SharedUserSetting(name, pkgFlags);
7876 if (MULTIPLE_APPLICATION_UIDS) {
7877 s.userId = newUserIdLP(s);
7878 } else {
7879 s.userId = FIRST_APPLICATION_UID;
7880 }
7881 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7882 // < 0 means we couldn't assign a userid; fall out and return
7883 // s, which is currently null
7884 if (s.userId >= 0) {
7885 mSharedUsers.put(name, s);
7886 }
7887 }
7888
7889 return s;
7890 }
7891
7892 int disableSystemPackageLP(String name) {
7893 PackageSetting p = mPackages.get(name);
7894 if(p == null) {
7895 Log.w(TAG, "Package:"+name+" is not an installed package");
7896 return -1;
7897 }
7898 PackageSetting dp = mDisabledSysPackages.get(name);
7899 // always make sure the system package code and resource paths dont change
7900 if(dp == null) {
7901 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7902 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7903 }
7904 mDisabledSysPackages.put(name, p);
7905 }
7906 return removePackageLP(name);
7907 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 PackageSetting enableSystemPackageLP(String name) {
7910 PackageSetting p = mDisabledSysPackages.get(name);
7911 if(p == null) {
7912 Log.w(TAG, "Package:"+name+" is not disabled");
7913 return null;
7914 }
7915 // Reset flag in ApplicationInfo object
7916 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7917 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7918 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007919 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007920 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 mDisabledSysPackages.remove(name);
7922 return ret;
7923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007924
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007925 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007926 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007927 PackageSetting p = mPackages.get(name);
7928 if (p != null) {
7929 if (p.userId == uid) {
7930 return p;
7931 }
7932 reportSettingsProblem(Log.ERROR,
7933 "Adding duplicate package, keeping first: " + name);
7934 return null;
7935 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007936 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 p.userId = uid;
7938 if (addUserIdLP(uid, p, name)) {
7939 mPackages.put(name, p);
7940 return p;
7941 }
7942 return null;
7943 }
7944
7945 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7946 SharedUserSetting s = mSharedUsers.get(name);
7947 if (s != null) {
7948 if (s.userId == uid) {
7949 return s;
7950 }
7951 reportSettingsProblem(Log.ERROR,
7952 "Adding duplicate shared user, keeping first: " + name);
7953 return null;
7954 }
7955 s = new SharedUserSetting(name, pkgFlags);
7956 s.userId = uid;
7957 if (addUserIdLP(uid, s, name)) {
7958 mSharedUsers.put(name, s);
7959 return s;
7960 }
7961 return null;
7962 }
7963
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007964 // Transfer ownership of permissions from one package to another.
7965 private void transferPermissions(String origPkg, String newPkg) {
7966 // Transfer ownership of permissions to the new package.
7967 for (int i=0; i<2; i++) {
7968 HashMap<String, BasePermission> permissions =
7969 i == 0 ? mPermissionTrees : mPermissions;
7970 for (BasePermission bp : permissions.values()) {
7971 if (origPkg.equals(bp.sourcePackage)) {
7972 if (DEBUG_UPGRADE) Log.v(TAG,
7973 "Moving permission " + bp.name
7974 + " from pkg " + bp.sourcePackage
7975 + " to " + newPkg);
7976 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007977 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007978 bp.perm = null;
7979 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007980 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007981 }
7982 bp.uid = 0;
7983 bp.gids = null;
7984 }
7985 }
7986 }
7987 }
7988
7989 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007990 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007991 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 PackageSetting p = mPackages.get(name);
7993 if (p != null) {
7994 if (!p.codePath.equals(codePath)) {
7995 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007996 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007997 // This is an updated system app with versions in both system
7998 // and data partition. Just let the most recent version
7999 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008000 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008001 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008002 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008003 // Just a change in the code path is not an issue, but
8004 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008005 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008006 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008007 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008008 }
8009 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008010 reportSettingsProblem(Log.WARN,
8011 "Package " + name + " shared user changed from "
8012 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8013 + " to "
8014 + (sharedUser != null ? sharedUser.name : "<nothing>")
8015 + "; replacing with new");
8016 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008017 } else {
8018 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8019 // If what we are scanning is a system package, then
8020 // make it so, regardless of whether it was previously
8021 // installed only in the data partition.
8022 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008024 }
8025 }
8026 if (p == null) {
8027 // Create a new PackageSettings entry. this can end up here because
8028 // of code path mismatch or user id mismatch of an updated system partition
8029 if (!create) {
8030 return null;
8031 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008032 if (origPackage != null) {
8033 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008034 p = new PackageSetting(origPackage.name, name, codePath,
8035 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008036 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8037 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008038 // Note that we will retain the new package's signature so
8039 // that we can keep its data.
8040 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008041 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008042 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008043 p.sharedUser = origPackage.sharedUser;
8044 p.userId = origPackage.userId;
8045 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008046 mRenamedPackages.put(name, origPackage.name);
8047 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008048 // Update new package state.
8049 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008050 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008051 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008052 p.setTimeStamp(codePath.lastModified());
8053 p.sharedUser = sharedUser;
8054 if (sharedUser != null) {
8055 p.userId = sharedUser.userId;
8056 } else if (MULTIPLE_APPLICATION_UIDS) {
8057 // Clone the setting here for disabled system packages
8058 PackageSetting dis = mDisabledSysPackages.get(name);
8059 if (dis != null) {
8060 // For disabled packages a new setting is created
8061 // from the existing user id. This still has to be
8062 // added to list of user id's
8063 // Copy signatures from previous setting
8064 if (dis.signatures.mSignatures != null) {
8065 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8066 }
8067 p.userId = dis.userId;
8068 // Clone permissions
8069 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008070 // Clone component info
8071 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8072 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8073 // Add new setting to list of user ids
8074 addUserIdLP(p.userId, p, name);
8075 } else {
8076 // Assign new user id
8077 p.userId = newUserIdLP(p);
8078 }
8079 } else {
8080 p.userId = FIRST_APPLICATION_UID;
8081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 }
8083 if (p.userId < 0) {
8084 reportSettingsProblem(Log.WARN,
8085 "Package " + name + " could not be assigned a valid uid");
8086 return null;
8087 }
8088 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008089 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008090 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008091 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 }
8093 }
8094 return p;
8095 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008096
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008097 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008098 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008099 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008100 final String codePath = pkg.applicationInfo.sourceDir;
8101 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008102 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008103 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008104 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008105 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008106 p.codePath = new File(codePath);
8107 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008108 }
8109 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008110 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008111 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008112 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008113 p.resourcePath = new File(resourcePath);
8114 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008115 }
Kenny Root85387d72010-08-26 10:13:11 -07008116 // Update the native library path if needed
8117 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8118 if (nativeLibraryPath != null
8119 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8120 p.nativeLibraryPathString = nativeLibraryPath;
8121 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008122 // Update version code if needed
8123 if (pkg.mVersionCode != p.versionCode) {
8124 p.versionCode = pkg.mVersionCode;
8125 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008126 // Update signatures if needed.
8127 if (p.signatures.mSignatures == null) {
8128 p.signatures.assignSignatures(pkg.mSignatures);
8129 }
8130 // If this app defines a shared user id initialize
8131 // the shared user signatures as well.
8132 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8133 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8134 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008135 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8136 }
8137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008138 // Utility method that adds a PackageSetting to mPackages and
8139 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008140 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008141 SharedUserSetting sharedUser) {
8142 mPackages.put(name, p);
8143 if (sharedUser != null) {
8144 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8145 reportSettingsProblem(Log.ERROR,
8146 "Package " + p.name + " was user "
8147 + p.sharedUser + " but is now " + sharedUser
8148 + "; I am not changing its files so it will probably fail!");
8149 p.sharedUser.packages.remove(p);
8150 } else if (p.userId != sharedUser.userId) {
8151 reportSettingsProblem(Log.ERROR,
8152 "Package " + p.name + " was user id " + p.userId
8153 + " but is now user " + sharedUser
8154 + " with id " + sharedUser.userId
8155 + "; I am not changing its files so it will probably fail!");
8156 }
8157
8158 sharedUser.packages.add(p);
8159 p.sharedUser = sharedUser;
8160 p.userId = sharedUser.userId;
8161 }
8162 }
8163
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008164 /*
8165 * Update the shared user setting when a package using
8166 * specifying the shared user id is removed. The gids
8167 * associated with each permission of the deleted package
8168 * are removed from the shared user's gid list only if its
8169 * not in use by other permissions of packages in the
8170 * shared user setting.
8171 */
8172 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008174 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008175 return;
8176 }
8177 // No sharedUserId
8178 if (deletedPs.sharedUser == null) {
8179 return;
8180 }
8181 SharedUserSetting sus = deletedPs.sharedUser;
8182 // Update permissions
8183 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8184 boolean used = false;
8185 if (!sus.grantedPermissions.contains (eachPerm)) {
8186 continue;
8187 }
8188 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008189 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008190 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008191 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 used = true;
8193 break;
8194 }
8195 }
8196 if (!used) {
8197 // can safely delete this permission from list
8198 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008199 }
8200 }
8201 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008202 int newGids[] = globalGids;
8203 for (String eachPerm : sus.grantedPermissions) {
8204 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008205 if (bp != null) {
8206 newGids = appendInts(newGids, bp.gids);
8207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008208 }
8209 sus.gids = newGids;
8210 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008212 private int removePackageLP(String name) {
8213 PackageSetting p = mPackages.get(name);
8214 if (p != null) {
8215 mPackages.remove(name);
8216 if (p.sharedUser != null) {
8217 p.sharedUser.packages.remove(p);
8218 if (p.sharedUser.packages.size() == 0) {
8219 mSharedUsers.remove(p.sharedUser.name);
8220 removeUserIdLP(p.sharedUser.userId);
8221 return p.sharedUser.userId;
8222 }
8223 } else {
8224 removeUserIdLP(p.userId);
8225 return p.userId;
8226 }
8227 }
8228 return -1;
8229 }
8230
8231 private boolean addUserIdLP(int uid, Object obj, Object name) {
8232 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8233 return false;
8234 }
8235
8236 if (uid >= FIRST_APPLICATION_UID) {
8237 int N = mUserIds.size();
8238 final int index = uid - FIRST_APPLICATION_UID;
8239 while (index >= N) {
8240 mUserIds.add(null);
8241 N++;
8242 }
8243 if (mUserIds.get(index) != null) {
8244 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008245 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246 + " name=" + name);
8247 return false;
8248 }
8249 mUserIds.set(index, obj);
8250 } else {
8251 if (mOtherUserIds.get(uid) != null) {
8252 reportSettingsProblem(Log.ERROR,
8253 "Adding duplicate shared id: " + uid
8254 + " name=" + name);
8255 return false;
8256 }
8257 mOtherUserIds.put(uid, obj);
8258 }
8259 return true;
8260 }
8261
8262 public Object getUserIdLP(int uid) {
8263 if (uid >= FIRST_APPLICATION_UID) {
8264 int N = mUserIds.size();
8265 final int index = uid - FIRST_APPLICATION_UID;
8266 return index < N ? mUserIds.get(index) : null;
8267 } else {
8268 return mOtherUserIds.get(uid);
8269 }
8270 }
8271
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008272 private Set<String> findPackagesWithFlag(int flag) {
8273 Set<String> ret = new HashSet<String>();
8274 for (PackageSetting ps : mPackages.values()) {
8275 // Has to match atleast all the flag bits set on flag
8276 if ((ps.pkgFlags & flag) == flag) {
8277 ret.add(ps.name);
8278 }
8279 }
8280 return ret;
8281 }
8282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 private void removeUserIdLP(int uid) {
8284 if (uid >= FIRST_APPLICATION_UID) {
8285 int N = mUserIds.size();
8286 final int index = uid - FIRST_APPLICATION_UID;
8287 if (index < N) mUserIds.set(index, null);
8288 } else {
8289 mOtherUserIds.remove(uid);
8290 }
8291 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008293 void writeLP() {
8294 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8295
8296 // Keep the old settings around until we know the new ones have
8297 // been successfully written.
8298 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008299 // Presence of backup settings file indicates that we failed
8300 // to persist settings earlier. So preserve the older
8301 // backup for future reference since the current settings
8302 // might have been corrupted.
8303 if (!mBackupSettingsFilename.exists()) {
8304 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008305 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008306 return;
8307 }
8308 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008309 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008310 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008312 }
8313
8314 mPastSignatures.clear();
8315
8316 try {
8317 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8318
8319 //XmlSerializer serializer = XmlUtils.serializerInstance();
8320 XmlSerializer serializer = new FastXmlSerializer();
8321 serializer.setOutput(str, "utf-8");
8322 serializer.startDocument(null, true);
8323 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8324
8325 serializer.startTag(null, "packages");
8326
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008327 serializer.startTag(null, "last-platform-version");
8328 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8329 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8330 serializer.endTag(null, "last-platform-version");
8331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008332 serializer.startTag(null, "permission-trees");
8333 for (BasePermission bp : mPermissionTrees.values()) {
8334 writePermission(serializer, bp);
8335 }
8336 serializer.endTag(null, "permission-trees");
8337
8338 serializer.startTag(null, "permissions");
8339 for (BasePermission bp : mPermissions.values()) {
8340 writePermission(serializer, bp);
8341 }
8342 serializer.endTag(null, "permissions");
8343
8344 for (PackageSetting pkg : mPackages.values()) {
8345 writePackage(serializer, pkg);
8346 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008348 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8349 writeDisabledSysPackage(serializer, pkg);
8350 }
8351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008352 serializer.startTag(null, "preferred-activities");
8353 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8354 serializer.startTag(null, "item");
8355 pa.writeToXml(serializer);
8356 serializer.endTag(null, "item");
8357 }
8358 serializer.endTag(null, "preferred-activities");
8359
8360 for (SharedUserSetting usr : mSharedUsers.values()) {
8361 serializer.startTag(null, "shared-user");
8362 serializer.attribute(null, "name", usr.name);
8363 serializer.attribute(null, "userId",
8364 Integer.toString(usr.userId));
8365 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8366 serializer.startTag(null, "perms");
8367 for (String name : usr.grantedPermissions) {
8368 serializer.startTag(null, "item");
8369 serializer.attribute(null, "name", name);
8370 serializer.endTag(null, "item");
8371 }
8372 serializer.endTag(null, "perms");
8373 serializer.endTag(null, "shared-user");
8374 }
8375
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008376 if (mPackagesToBeCleaned.size() > 0) {
8377 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8378 serializer.startTag(null, "cleaning-package");
8379 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8380 serializer.endTag(null, "cleaning-package");
8381 }
8382 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008383
8384 if (mRenamedPackages.size() > 0) {
8385 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8386 serializer.startTag(null, "renamed-package");
8387 serializer.attribute(null, "new", e.getKey());
8388 serializer.attribute(null, "old", e.getValue());
8389 serializer.endTag(null, "renamed-package");
8390 }
8391 }
8392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008393 serializer.endTag(null, "packages");
8394
8395 serializer.endDocument();
8396
8397 str.flush();
8398 str.close();
8399
8400 // New settings successfully written, old ones are no longer
8401 // needed.
8402 mBackupSettingsFilename.delete();
8403 FileUtils.setPermissions(mSettingsFilename.toString(),
8404 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8405 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8406 |FileUtils.S_IROTH,
8407 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008408
8409 // Write package list file now, use a JournaledFile.
8410 //
8411 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8412 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8413
8414 str = new FileOutputStream(journal.chooseForWrite());
8415 try {
8416 StringBuilder sb = new StringBuilder();
8417 for (PackageSetting pkg : mPackages.values()) {
8418 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008419 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008420 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8421
8422 // Avoid any application that has a space in its path
8423 // or that is handled by the system.
8424 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8425 continue;
8426
8427 // we store on each line the following information for now:
8428 //
8429 // pkgName - package name
8430 // userId - application-specific user id
8431 // debugFlag - 0 or 1 if the package is debuggable.
8432 // dataPath - path to package's data path
8433 //
8434 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8435 //
8436 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8437 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8438 // system/core/run-as/run-as.c
8439 //
8440 sb.setLength(0);
8441 sb.append(ai.packageName);
8442 sb.append(" ");
8443 sb.append((int)ai.uid);
8444 sb.append(isDebug ? " 1 " : " 0 ");
8445 sb.append(dataPath);
8446 sb.append("\n");
8447 str.write(sb.toString().getBytes());
8448 }
8449 str.flush();
8450 str.close();
8451 journal.commit();
8452 }
8453 catch (Exception e) {
8454 journal.rollback();
8455 }
8456
8457 FileUtils.setPermissions(mPackageListFilename.toString(),
8458 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8459 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8460 |FileUtils.S_IROTH,
8461 -1, -1);
8462
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008463 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008464
8465 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008466 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 -08008467 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008468 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 -08008469 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008470 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008471 if (mSettingsFilename.exists()) {
8472 if (!mSettingsFilename.delete()) {
8473 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8474 }
8475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 //Debug.stopMethodTracing();
8477 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008478
8479 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008480 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 serializer.startTag(null, "updated-package");
8482 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008483 if (pkg.realName != null) {
8484 serializer.attribute(null, "realName", pkg.realName);
8485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008486 serializer.attribute(null, "codePath", pkg.codePathString);
8487 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008488 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8490 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8491 }
Kenny Root85387d72010-08-26 10:13:11 -07008492 if (pkg.nativeLibraryPathString != null) {
8493 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 if (pkg.sharedUser == null) {
8496 serializer.attribute(null, "userId",
8497 Integer.toString(pkg.userId));
8498 } else {
8499 serializer.attribute(null, "sharedUserId",
8500 Integer.toString(pkg.userId));
8501 }
8502 serializer.startTag(null, "perms");
8503 if (pkg.sharedUser == null) {
8504 // If this is a shared user, the permissions will
8505 // be written there. We still need to write an
8506 // empty permissions list so permissionsFixed will
8507 // be set.
8508 for (final String name : pkg.grantedPermissions) {
8509 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008510 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008511 // We only need to write signature or system permissions but this wont
8512 // match the semantics of grantedPermissions. So write all permissions.
8513 serializer.startTag(null, "item");
8514 serializer.attribute(null, "name", name);
8515 serializer.endTag(null, "item");
8516 }
8517 }
8518 }
8519 serializer.endTag(null, "perms");
8520 serializer.endTag(null, "updated-package");
8521 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008522
8523 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008524 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008525 serializer.startTag(null, "package");
8526 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008527 if (pkg.realName != null) {
8528 serializer.attribute(null, "realName", pkg.realName);
8529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008530 serializer.attribute(null, "codePath", pkg.codePathString);
8531 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8532 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8533 }
Kenny Root85387d72010-08-26 10:13:11 -07008534 if (pkg.nativeLibraryPathString != null) {
8535 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8536 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008537 serializer.attribute(null, "flags",
8538 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008540 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 if (pkg.sharedUser == null) {
8542 serializer.attribute(null, "userId",
8543 Integer.toString(pkg.userId));
8544 } else {
8545 serializer.attribute(null, "sharedUserId",
8546 Integer.toString(pkg.userId));
8547 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008548 if (pkg.uidError) {
8549 serializer.attribute(null, "uidError", "true");
8550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008551 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8552 serializer.attribute(null, "enabled",
8553 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8554 ? "true" : "false");
8555 }
8556 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8557 serializer.attribute(null, "installStatus", "false");
8558 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008559 if (pkg.installerPackageName != null) {
8560 serializer.attribute(null, "installer", pkg.installerPackageName);
8561 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008562 if (pkg.obbPathString != null) {
8563 serializer.attribute(null, "obbPath", pkg.obbPathString);
8564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008565 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8566 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8567 serializer.startTag(null, "perms");
8568 if (pkg.sharedUser == null) {
8569 // If this is a shared user, the permissions will
8570 // be written there. We still need to write an
8571 // empty permissions list so permissionsFixed will
8572 // be set.
8573 for (final String name : pkg.grantedPermissions) {
8574 serializer.startTag(null, "item");
8575 serializer.attribute(null, "name", name);
8576 serializer.endTag(null, "item");
8577 }
8578 }
8579 serializer.endTag(null, "perms");
8580 }
8581 if (pkg.disabledComponents.size() > 0) {
8582 serializer.startTag(null, "disabled-components");
8583 for (final String name : pkg.disabledComponents) {
8584 serializer.startTag(null, "item");
8585 serializer.attribute(null, "name", name);
8586 serializer.endTag(null, "item");
8587 }
8588 serializer.endTag(null, "disabled-components");
8589 }
8590 if (pkg.enabledComponents.size() > 0) {
8591 serializer.startTag(null, "enabled-components");
8592 for (final String name : pkg.enabledComponents) {
8593 serializer.startTag(null, "item");
8594 serializer.attribute(null, "name", name);
8595 serializer.endTag(null, "item");
8596 }
8597 serializer.endTag(null, "enabled-components");
8598 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008600 serializer.endTag(null, "package");
8601 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008603 void writePermission(XmlSerializer serializer, BasePermission bp)
8604 throws XmlPullParserException, java.io.IOException {
8605 if (bp.type != BasePermission.TYPE_BUILTIN
8606 && bp.sourcePackage != null) {
8607 serializer.startTag(null, "item");
8608 serializer.attribute(null, "name", bp.name);
8609 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008610 if (bp.protectionLevel !=
8611 PermissionInfo.PROTECTION_NORMAL) {
8612 serializer.attribute(null, "protection",
8613 Integer.toString(bp.protectionLevel));
8614 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 if (DEBUG_SETTINGS) Log.v(TAG,
8616 "Writing perm: name=" + bp.name + " type=" + bp.type);
8617 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8618 PermissionInfo pi = bp.perm != null ? bp.perm.info
8619 : bp.pendingInfo;
8620 if (pi != null) {
8621 serializer.attribute(null, "type", "dynamic");
8622 if (pi.icon != 0) {
8623 serializer.attribute(null, "icon",
8624 Integer.toString(pi.icon));
8625 }
8626 if (pi.nonLocalizedLabel != null) {
8627 serializer.attribute(null, "label",
8628 pi.nonLocalizedLabel.toString());
8629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 }
8631 }
8632 serializer.endTag(null, "item");
8633 }
8634 }
8635
8636 String getReadMessagesLP() {
8637 return mReadMessages.toString();
8638 }
8639
Oscar Montemayora8529f62009-11-18 10:14:20 -08008640 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8642 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008643 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 while(its.hasNext()) {
8645 String key = its.next();
8646 PackageSetting ps = mPackages.get(key);
8647 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008648 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008649 }
8650 }
8651 return ret;
8652 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654 boolean readLP() {
8655 FileInputStream str = null;
8656 if (mBackupSettingsFilename.exists()) {
8657 try {
8658 str = new FileInputStream(mBackupSettingsFilename);
8659 mReadMessages.append("Reading from backup settings file\n");
8660 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008661 if (mSettingsFilename.exists()) {
8662 // If both the backup and settings file exist, we
8663 // ignore the settings since it might have been
8664 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008665 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008666 mSettingsFilename.delete();
8667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008668 } catch (java.io.IOException e) {
8669 // We'll try for the normal settings file.
8670 }
8671 }
8672
8673 mPastSignatures.clear();
8674
8675 try {
8676 if (str == null) {
8677 if (!mSettingsFilename.exists()) {
8678 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008679 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 return false;
8681 }
8682 str = new FileInputStream(mSettingsFilename);
8683 }
8684 XmlPullParser parser = Xml.newPullParser();
8685 parser.setInput(str, null);
8686
8687 int type;
8688 while ((type=parser.next()) != XmlPullParser.START_TAG
8689 && type != XmlPullParser.END_DOCUMENT) {
8690 ;
8691 }
8692
8693 if (type != XmlPullParser.START_TAG) {
8694 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008695 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 return false;
8697 }
8698
8699 int outerDepth = parser.getDepth();
8700 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8701 && (type != XmlPullParser.END_TAG
8702 || parser.getDepth() > outerDepth)) {
8703 if (type == XmlPullParser.END_TAG
8704 || type == XmlPullParser.TEXT) {
8705 continue;
8706 }
8707
8708 String tagName = parser.getName();
8709 if (tagName.equals("package")) {
8710 readPackageLP(parser);
8711 } else if (tagName.equals("permissions")) {
8712 readPermissionsLP(mPermissions, parser);
8713 } else if (tagName.equals("permission-trees")) {
8714 readPermissionsLP(mPermissionTrees, parser);
8715 } else if (tagName.equals("shared-user")) {
8716 readSharedUserLP(parser);
8717 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008718 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 } else if (tagName.equals("preferred-activities")) {
8720 readPreferredActivitiesLP(parser);
8721 } else if(tagName.equals("updated-package")) {
8722 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008723 } else if (tagName.equals("cleaning-package")) {
8724 String name = parser.getAttributeValue(null, "name");
8725 if (name != null) {
8726 mPackagesToBeCleaned.add(name);
8727 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008728 } else if (tagName.equals("renamed-package")) {
8729 String nname = parser.getAttributeValue(null, "new");
8730 String oname = parser.getAttributeValue(null, "old");
8731 if (nname != null && oname != null) {
8732 mRenamedPackages.put(nname, oname);
8733 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008734 } else if (tagName.equals("last-platform-version")) {
8735 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8736 try {
8737 String internal = parser.getAttributeValue(null, "internal");
8738 if (internal != null) {
8739 mInternalSdkPlatform = Integer.parseInt(internal);
8740 }
8741 String external = parser.getAttributeValue(null, "external");
8742 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008743 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008744 }
8745 } catch (NumberFormatException e) {
8746 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008747 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008748 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749 + parser.getName());
8750 XmlUtils.skipCurrentTag(parser);
8751 }
8752 }
8753
8754 str.close();
8755
8756 } catch(XmlPullParserException e) {
8757 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008758 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759
8760 } catch(java.io.IOException e) {
8761 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008762 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008763
8764 }
8765
8766 int N = mPendingPackages.size();
8767 for (int i=0; i<N; i++) {
8768 final PendingPackage pp = mPendingPackages.get(i);
8769 Object idObj = getUserIdLP(pp.sharedId);
8770 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008771 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008773 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008774 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008775 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 + pp.name);
8777 continue;
8778 }
8779 p.copyFrom(pp);
8780 } else if (idObj != null) {
8781 String msg = "Bad package setting: package " + pp.name
8782 + " has shared uid " + pp.sharedId
8783 + " that is not a shared uid\n";
8784 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008785 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786 } else {
8787 String msg = "Bad package setting: package " + pp.name
8788 + " has shared uid " + pp.sharedId
8789 + " that is not defined\n";
8790 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008791 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008792 }
8793 }
8794 mPendingPackages.clear();
8795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008796 mReadMessages.append("Read completed successfully: "
8797 + mPackages.size() + " packages, "
8798 + mSharedUsers.size() + " shared uids\n");
8799
8800 return true;
8801 }
8802
8803 private int readInt(XmlPullParser parser, String ns, String name,
8804 int defValue) {
8805 String v = parser.getAttributeValue(ns, name);
8806 try {
8807 if (v == null) {
8808 return defValue;
8809 }
8810 return Integer.parseInt(v);
8811 } catch (NumberFormatException e) {
8812 reportSettingsProblem(Log.WARN,
8813 "Error in package manager settings: attribute " +
8814 name + " has bad integer value " + v + " at "
8815 + parser.getPositionDescription());
8816 }
8817 return defValue;
8818 }
8819
8820 private void readPermissionsLP(HashMap<String, BasePermission> out,
8821 XmlPullParser parser)
8822 throws IOException, XmlPullParserException {
8823 int outerDepth = parser.getDepth();
8824 int type;
8825 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8826 && (type != XmlPullParser.END_TAG
8827 || parser.getDepth() > outerDepth)) {
8828 if (type == XmlPullParser.END_TAG
8829 || type == XmlPullParser.TEXT) {
8830 continue;
8831 }
8832
8833 String tagName = parser.getName();
8834 if (tagName.equals("item")) {
8835 String name = parser.getAttributeValue(null, "name");
8836 String sourcePackage = parser.getAttributeValue(null, "package");
8837 String ptype = parser.getAttributeValue(null, "type");
8838 if (name != null && sourcePackage != null) {
8839 boolean dynamic = "dynamic".equals(ptype);
8840 BasePermission bp = new BasePermission(name, sourcePackage,
8841 dynamic
8842 ? BasePermission.TYPE_DYNAMIC
8843 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008844 bp.protectionLevel = readInt(parser, null, "protection",
8845 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008846 if (dynamic) {
8847 PermissionInfo pi = new PermissionInfo();
8848 pi.packageName = sourcePackage.intern();
8849 pi.name = name.intern();
8850 pi.icon = readInt(parser, null, "icon", 0);
8851 pi.nonLocalizedLabel = parser.getAttributeValue(
8852 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008853 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008854 bp.pendingInfo = pi;
8855 }
8856 out.put(bp.name, bp);
8857 } else {
8858 reportSettingsProblem(Log.WARN,
8859 "Error in package manager settings: permissions has"
8860 + " no name at " + parser.getPositionDescription());
8861 }
8862 } else {
8863 reportSettingsProblem(Log.WARN,
8864 "Unknown element reading permissions: "
8865 + parser.getName() + " at "
8866 + parser.getPositionDescription());
8867 }
8868 XmlUtils.skipCurrentTag(parser);
8869 }
8870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008872 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008873 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008874 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008875 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 String codePathStr = parser.getAttributeValue(null, "codePath");
8877 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008878 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008879 resourcePathStr = codePathStr;
8880 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008881 String version = parser.getAttributeValue(null, "version");
8882 int versionCode = 0;
8883 if (version != null) {
8884 try {
8885 versionCode = Integer.parseInt(version);
8886 } catch (NumberFormatException e) {
8887 }
8888 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 int pkgFlags = 0;
8891 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008892 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008893 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008894 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008895 String timeStampStr = parser.getAttributeValue(null, "ts");
8896 if (timeStampStr != null) {
8897 try {
8898 long timeStamp = Long.parseLong(timeStampStr);
8899 ps.setTimeStamp(timeStamp, timeStampStr);
8900 } catch (NumberFormatException e) {
8901 }
8902 }
8903 String idStr = parser.getAttributeValue(null, "userId");
8904 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8905 if(ps.userId <= 0) {
8906 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8907 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8908 }
8909 int outerDepth = parser.getDepth();
8910 int type;
8911 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8912 && (type != XmlPullParser.END_TAG
8913 || parser.getDepth() > outerDepth)) {
8914 if (type == XmlPullParser.END_TAG
8915 || type == XmlPullParser.TEXT) {
8916 continue;
8917 }
8918
8919 String tagName = parser.getName();
8920 if (tagName.equals("perms")) {
8921 readGrantedPermissionsLP(parser,
8922 ps.grantedPermissions);
8923 } else {
8924 reportSettingsProblem(Log.WARN,
8925 "Unknown element under <updated-package>: "
8926 + parser.getName());
8927 XmlUtils.skipCurrentTag(parser);
8928 }
8929 }
8930 mDisabledSysPackages.put(name, ps);
8931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 private void readPackageLP(XmlPullParser parser)
8934 throws XmlPullParserException, IOException {
8935 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008936 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937 String idStr = null;
8938 String sharedIdStr = null;
8939 String codePathStr = null;
8940 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07008941 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07008942 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008944 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008945 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 int pkgFlags = 0;
8947 String timeStampStr;
8948 long timeStamp = 0;
8949 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008950 String version = null;
8951 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 try {
8953 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008954 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008956 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008957 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8958 codePathStr = parser.getAttributeValue(null, "codePath");
8959 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07008960 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07008961 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008962 version = parser.getAttributeValue(null, "version");
8963 if (version != null) {
8964 try {
8965 versionCode = Integer.parseInt(version);
8966 } catch (NumberFormatException e) {
8967 }
8968 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008969 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008970
8971 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008972 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008973 try {
8974 pkgFlags = Integer.parseInt(systemStr);
8975 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008976 }
8977 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008978 // For backward compatibility
8979 systemStr = parser.getAttributeValue(null, "system");
8980 if (systemStr != null) {
8981 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8982 } else {
8983 // Old settings that don't specify system... just treat
8984 // them as system, good enough.
8985 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008987 }
8988 timeStampStr = parser.getAttributeValue(null, "ts");
8989 if (timeStampStr != null) {
8990 try {
8991 timeStamp = Long.parseLong(timeStampStr);
8992 } catch (NumberFormatException e) {
8993 }
8994 }
8995 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8996 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8997 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8998 if (resourcePathStr == null) {
8999 resourcePathStr = codePathStr;
9000 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009001 if (realName != null) {
9002 realName = realName.intern();
9003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009004 if (name == null) {
9005 reportSettingsProblem(Log.WARN,
9006 "Error in package manager settings: <package> has no name at "
9007 + parser.getPositionDescription());
9008 } else if (codePathStr == null) {
9009 reportSettingsProblem(Log.WARN,
9010 "Error in package manager settings: <package> has no codePath at "
9011 + parser.getPositionDescription());
9012 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009013 packageSetting = addPackageLP(name.intern(), realName,
9014 new File(codePathStr), new File(resourcePathStr),
9015 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9017 + ": userId=" + userId + " pkg=" + packageSetting);
9018 if (packageSetting == null) {
9019 reportSettingsProblem(Log.ERROR,
9020 "Failure adding uid " + userId
9021 + " while parsing settings at "
9022 + parser.getPositionDescription());
9023 } else {
9024 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9025 }
9026 } else if (sharedIdStr != null) {
9027 userId = sharedIdStr != null
9028 ? Integer.parseInt(sharedIdStr) : 0;
9029 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009030 packageSetting = new PendingPackage(name.intern(), realName,
9031 new File(codePathStr), new File(resourcePathStr),
9032 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009033 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9034 mPendingPackages.add((PendingPackage) packageSetting);
9035 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9036 + ": sharedUserId=" + userId + " pkg="
9037 + packageSetting);
9038 } else {
9039 reportSettingsProblem(Log.WARN,
9040 "Error in package manager settings: package "
9041 + name + " has bad sharedId " + sharedIdStr
9042 + " at " + parser.getPositionDescription());
9043 }
9044 } else {
9045 reportSettingsProblem(Log.WARN,
9046 "Error in package manager settings: package "
9047 + name + " has bad userId " + idStr + " at "
9048 + parser.getPositionDescription());
9049 }
9050 } catch (NumberFormatException e) {
9051 reportSettingsProblem(Log.WARN,
9052 "Error in package manager settings: package "
9053 + name + " has bad userId " + idStr + " at "
9054 + parser.getPositionDescription());
9055 }
9056 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009057 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009058 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009059 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009060 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 final String enabledStr = parser.getAttributeValue(null, "enabled");
9062 if (enabledStr != null) {
9063 if (enabledStr.equalsIgnoreCase("true")) {
9064 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9065 } else if (enabledStr.equalsIgnoreCase("false")) {
9066 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9067 } else if (enabledStr.equalsIgnoreCase("default")) {
9068 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9069 } else {
9070 reportSettingsProblem(Log.WARN,
9071 "Error in package manager settings: package "
9072 + name + " has bad enabled value: " + idStr
9073 + " at " + parser.getPositionDescription());
9074 }
9075 } else {
9076 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9077 }
9078 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9079 if (installStatusStr != null) {
9080 if (installStatusStr.equalsIgnoreCase("false")) {
9081 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9082 } else {
9083 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9084 }
9085 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009087 int outerDepth = parser.getDepth();
9088 int type;
9089 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9090 && (type != XmlPullParser.END_TAG
9091 || parser.getDepth() > outerDepth)) {
9092 if (type == XmlPullParser.END_TAG
9093 || type == XmlPullParser.TEXT) {
9094 continue;
9095 }
9096
9097 String tagName = parser.getName();
9098 if (tagName.equals("disabled-components")) {
9099 readDisabledComponentsLP(packageSetting, parser);
9100 } else if (tagName.equals("enabled-components")) {
9101 readEnabledComponentsLP(packageSetting, parser);
9102 } else if (tagName.equals("sigs")) {
9103 packageSetting.signatures.readXml(parser, mPastSignatures);
9104 } else if (tagName.equals("perms")) {
9105 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009106 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009107 packageSetting.permissionsFixed = true;
9108 } else {
9109 reportSettingsProblem(Log.WARN,
9110 "Unknown element under <package>: "
9111 + parser.getName());
9112 XmlUtils.skipCurrentTag(parser);
9113 }
9114 }
9115 } else {
9116 XmlUtils.skipCurrentTag(parser);
9117 }
9118 }
9119
9120 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9121 XmlPullParser parser)
9122 throws IOException, XmlPullParserException {
9123 int outerDepth = parser.getDepth();
9124 int type;
9125 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9126 && (type != XmlPullParser.END_TAG
9127 || parser.getDepth() > outerDepth)) {
9128 if (type == XmlPullParser.END_TAG
9129 || type == XmlPullParser.TEXT) {
9130 continue;
9131 }
9132
9133 String tagName = parser.getName();
9134 if (tagName.equals("item")) {
9135 String name = parser.getAttributeValue(null, "name");
9136 if (name != null) {
9137 packageSetting.disabledComponents.add(name.intern());
9138 } else {
9139 reportSettingsProblem(Log.WARN,
9140 "Error in package manager settings: <disabled-components> has"
9141 + " no name at " + parser.getPositionDescription());
9142 }
9143 } else {
9144 reportSettingsProblem(Log.WARN,
9145 "Unknown element under <disabled-components>: "
9146 + parser.getName());
9147 }
9148 XmlUtils.skipCurrentTag(parser);
9149 }
9150 }
9151
9152 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9153 XmlPullParser parser)
9154 throws IOException, XmlPullParserException {
9155 int outerDepth = parser.getDepth();
9156 int type;
9157 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9158 && (type != XmlPullParser.END_TAG
9159 || parser.getDepth() > outerDepth)) {
9160 if (type == XmlPullParser.END_TAG
9161 || type == XmlPullParser.TEXT) {
9162 continue;
9163 }
9164
9165 String tagName = parser.getName();
9166 if (tagName.equals("item")) {
9167 String name = parser.getAttributeValue(null, "name");
9168 if (name != null) {
9169 packageSetting.enabledComponents.add(name.intern());
9170 } else {
9171 reportSettingsProblem(Log.WARN,
9172 "Error in package manager settings: <enabled-components> has"
9173 + " no name at " + parser.getPositionDescription());
9174 }
9175 } else {
9176 reportSettingsProblem(Log.WARN,
9177 "Unknown element under <enabled-components>: "
9178 + parser.getName());
9179 }
9180 XmlUtils.skipCurrentTag(parser);
9181 }
9182 }
9183
9184 private void readSharedUserLP(XmlPullParser parser)
9185 throws XmlPullParserException, IOException {
9186 String name = null;
9187 String idStr = null;
9188 int pkgFlags = 0;
9189 SharedUserSetting su = null;
9190 try {
9191 name = parser.getAttributeValue(null, "name");
9192 idStr = parser.getAttributeValue(null, "userId");
9193 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9194 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9195 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9196 }
9197 if (name == null) {
9198 reportSettingsProblem(Log.WARN,
9199 "Error in package manager settings: <shared-user> has no name at "
9200 + parser.getPositionDescription());
9201 } else if (userId == 0) {
9202 reportSettingsProblem(Log.WARN,
9203 "Error in package manager settings: shared-user "
9204 + name + " has bad userId " + idStr + " at "
9205 + parser.getPositionDescription());
9206 } else {
9207 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9208 reportSettingsProblem(Log.ERROR,
9209 "Occurred while parsing settings at "
9210 + parser.getPositionDescription());
9211 }
9212 }
9213 } catch (NumberFormatException e) {
9214 reportSettingsProblem(Log.WARN,
9215 "Error in package manager settings: package "
9216 + name + " has bad userId " + idStr + " at "
9217 + parser.getPositionDescription());
9218 };
9219
9220 if (su != null) {
9221 int outerDepth = parser.getDepth();
9222 int type;
9223 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9224 && (type != XmlPullParser.END_TAG
9225 || parser.getDepth() > outerDepth)) {
9226 if (type == XmlPullParser.END_TAG
9227 || type == XmlPullParser.TEXT) {
9228 continue;
9229 }
9230
9231 String tagName = parser.getName();
9232 if (tagName.equals("sigs")) {
9233 su.signatures.readXml(parser, mPastSignatures);
9234 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009235 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009236 } else {
9237 reportSettingsProblem(Log.WARN,
9238 "Unknown element under <shared-user>: "
9239 + parser.getName());
9240 XmlUtils.skipCurrentTag(parser);
9241 }
9242 }
9243
9244 } else {
9245 XmlUtils.skipCurrentTag(parser);
9246 }
9247 }
9248
9249 private void readGrantedPermissionsLP(XmlPullParser parser,
9250 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9251 int outerDepth = parser.getDepth();
9252 int type;
9253 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9254 && (type != XmlPullParser.END_TAG
9255 || parser.getDepth() > outerDepth)) {
9256 if (type == XmlPullParser.END_TAG
9257 || type == XmlPullParser.TEXT) {
9258 continue;
9259 }
9260
9261 String tagName = parser.getName();
9262 if (tagName.equals("item")) {
9263 String name = parser.getAttributeValue(null, "name");
9264 if (name != null) {
9265 outPerms.add(name.intern());
9266 } else {
9267 reportSettingsProblem(Log.WARN,
9268 "Error in package manager settings: <perms> has"
9269 + " no name at " + parser.getPositionDescription());
9270 }
9271 } else {
9272 reportSettingsProblem(Log.WARN,
9273 "Unknown element under <perms>: "
9274 + parser.getName());
9275 }
9276 XmlUtils.skipCurrentTag(parser);
9277 }
9278 }
9279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009280 private void readPreferredActivitiesLP(XmlPullParser parser)
9281 throws XmlPullParserException, IOException {
9282 int outerDepth = parser.getDepth();
9283 int type;
9284 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9285 && (type != XmlPullParser.END_TAG
9286 || parser.getDepth() > outerDepth)) {
9287 if (type == XmlPullParser.END_TAG
9288 || type == XmlPullParser.TEXT) {
9289 continue;
9290 }
9291
9292 String tagName = parser.getName();
9293 if (tagName.equals("item")) {
9294 PreferredActivity pa = new PreferredActivity(parser);
9295 if (pa.mParseError == null) {
9296 mPreferredActivities.addFilter(pa);
9297 } else {
9298 reportSettingsProblem(Log.WARN,
9299 "Error in package manager settings: <preferred-activity> "
9300 + pa.mParseError + " at "
9301 + parser.getPositionDescription());
9302 }
9303 } else {
9304 reportSettingsProblem(Log.WARN,
9305 "Unknown element under <preferred-activities>: "
9306 + parser.getName());
9307 XmlUtils.skipCurrentTag(parser);
9308 }
9309 }
9310 }
9311
9312 // Returns -1 if we could not find an available UserId to assign
9313 private int newUserIdLP(Object obj) {
9314 // Let's be stupidly inefficient for now...
9315 final int N = mUserIds.size();
9316 for (int i=0; i<N; i++) {
9317 if (mUserIds.get(i) == null) {
9318 mUserIds.set(i, obj);
9319 return FIRST_APPLICATION_UID + i;
9320 }
9321 }
9322
9323 // None left?
9324 if (N >= MAX_APPLICATION_UIDS) {
9325 return -1;
9326 }
9327
9328 mUserIds.add(obj);
9329 return FIRST_APPLICATION_UID + N;
9330 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 public PackageSetting getDisabledSystemPkg(String name) {
9333 synchronized(mPackages) {
9334 PackageSetting ps = mDisabledSysPackages.get(name);
9335 return ps;
9336 }
9337 }
9338
9339 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009340 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9341 return true;
9342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009343 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9344 if (Config.LOGV) {
9345 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9346 + " componentName = " + componentInfo.name);
9347 Log.v(TAG, "enabledComponents: "
9348 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9349 Log.v(TAG, "disabledComponents: "
9350 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9351 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009352 if (packageSettings == null) {
9353 if (false) {
9354 Log.w(TAG, "WAITING FOR DEBUGGER");
9355 Debug.waitForDebugger();
9356 Log.i(TAG, "We will crash!");
9357 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009358 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009359 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009360 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9361 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9362 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9363 return false;
9364 }
9365 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9366 return true;
9367 }
9368 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9369 return false;
9370 }
9371 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009372 }
9373 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009374
9375 // ------- apps on sdcard specific code -------
9376 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009377 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009378 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009379 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009380 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009381
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009382 private String getEncryptKey() {
9383 try {
9384 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9385 if (sdEncKey == null) {
9386 sdEncKey = SystemKeyStore.getInstance().
9387 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9388 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009389 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009390 return null;
9391 }
9392 }
9393 return sdEncKey;
9394 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009395 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009396 return null;
9397 }
9398 }
9399
Kenny Rootc78a8072010-07-27 15:18:38 -07009400 /* package */ static String getTempContainerId() {
9401 int tmpIdx = 1;
9402 String list[] = PackageHelper.getSecureContainerList();
9403 if (list != null) {
9404 for (final String name : list) {
9405 // Ignore null and non-temporary container entries
9406 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9407 continue;
9408 }
9409
9410 String subStr = name.substring(mTempContainerPrefix.length());
9411 try {
9412 int cid = Integer.parseInt(subStr);
9413 if (cid >= tmpIdx) {
9414 tmpIdx = cid + 1;
9415 }
9416 } catch (NumberFormatException e) {
9417 }
9418 }
9419 }
9420 return mTempContainerPrefix + tmpIdx;
9421 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009422
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009423 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009424 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009425 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009426 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9427 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9428 throw new SecurityException("Media status can only be updated by the system");
9429 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009430 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009431 Log.i(TAG, "Updating external media status from " +
9432 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9433 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009434 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9435 mediaStatus+", mMediaMounted=" + mMediaMounted);
9436 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009437 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9438 reportStatus ? 1 : 0, -1);
9439 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009440 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009441 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009442 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009443 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009444 // Queue up an async operation since the package installation may take a little while.
9445 mHandler.post(new Runnable() {
9446 public void run() {
9447 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009448 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009449 }
9450 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009451 }
9452
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009453 /*
9454 * Collect information of applications on external media, map them
9455 * against existing containers and update information based on current
9456 * mount status. Please note that we always have to report status
9457 * if reportStatus has been set to true especially when unloading packages.
9458 */
9459 private void updateExternalMediaStatusInner(boolean mediaStatus,
9460 boolean reportStatus) {
9461 // Collection of uids
9462 int uidArr[] = null;
9463 // Collection of stale containers
9464 HashSet<String> removeCids = new HashSet<String>();
9465 // Collection of packages on external media with valid containers.
9466 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9467 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009468 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009469 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009470 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009471 } else {
9472 // Process list of secure containers and categorize them
9473 // as active or stale based on their package internal state.
9474 int uidList[] = new int[list.length];
9475 int num = 0;
9476 synchronized (mPackages) {
9477 for (String cid : list) {
9478 SdInstallArgs args = new SdInstallArgs(cid);
9479 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009480 String pkgName = args.getPackageName();
9481 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009482 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9483 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009484 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009485 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009486 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9487 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009488 // The package status is changed only if the code path
9489 // matches between settings and the container id.
9490 if (ps != null && ps.codePathString != null &&
9491 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009492 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9493 " corresponds to pkg : " + pkgName +
9494 " at code path: " + ps.codePathString);
9495 // We do have a valid package installed on sdcard
9496 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009497 int uid = ps.userId;
9498 if (uid != -1) {
9499 uidList[num++] = uid;
9500 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009501 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009502 // Stale container on sdcard. Just delete
9503 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9504 removeCids.add(cid);
9505 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009506 }
9507 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009508
9509 if (num > 0) {
9510 // Sort uid list
9511 Arrays.sort(uidList, 0, num);
9512 // Throw away duplicates
9513 uidArr = new int[num];
9514 uidArr[0] = uidList[0];
9515 int di = 0;
9516 for (int i = 1; i < num; i++) {
9517 if (uidList[i-1] != uidList[i]) {
9518 uidArr[di++] = uidList[i];
9519 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009520 }
9521 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009522 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009523 // Process packages with valid entries.
9524 if (mediaStatus) {
9525 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009526 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009527 startCleaningPackages();
9528 } else {
9529 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009530 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009531 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009532 }
9533
9534 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009535 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009536 int size = pkgList.size();
9537 if (size > 0) {
9538 // Send broadcasts here
9539 Bundle extras = new Bundle();
9540 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9541 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009542 if (uidArr != null) {
9543 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9544 }
9545 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9546 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009547 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009548 }
9549 }
9550
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009551 /*
9552 * Look at potentially valid container ids from processCids
9553 * If package information doesn't match the one on record
9554 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009555 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009556 */
9557 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009558 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009559 ArrayList<String> pkgList = new ArrayList<String>();
9560 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009561 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009562 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009563 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009564 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9565 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009566 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009567 try {
9568 // Make sure there are no container errors first.
9569 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9570 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009571 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009572 " when installing from sdcard");
9573 continue;
9574 }
9575 // Check code path here.
9576 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009577 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009578 " does not match one in settings " + codePath);
9579 continue;
9580 }
9581 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009582 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009583 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009584 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009585 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9586 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009587 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009588 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009589 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009590 retCode = PackageManager.INSTALL_SUCCEEDED;
9591 pkgList.add(pkg.packageName);
9592 // Post process args
9593 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9594 }
9595 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009596 Slog.i(TAG, "Failed to install pkg from " +
9597 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009598 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009599 }
9600
9601 } finally {
9602 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9603 // Don't destroy container here. Wait till gc clears things up.
9604 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009605 }
9606 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009607 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009608 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009609 // If the platform SDK has changed since the last time we booted,
9610 // we need to re-grant app permission to catch any new ones that
9611 // appear. This is really a hack, and means that apps can in some
9612 // cases get permissions that the user didn't initially explicitly
9613 // allow... it would be nice to have some better way to handle
9614 // this situation.
9615 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9616 != mSdkVersion;
9617 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9618 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9619 + "; regranting permissions for external storage");
9620 mSettings.mExternalSdkPlatform = mSdkVersion;
9621
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009622 // Make sure group IDs have been assigned, and any permission
9623 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009624 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009625 // Persist settings
9626 mSettings.writeLP();
9627 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009628 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009629 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009630 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009631 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009632 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009633 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009634 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009635 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009636 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009637 if (removeCids != null) {
9638 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009639 if (cid.startsWith(mTempContainerPrefix)) {
9640 Log.i(TAG, "Destroying stale temporary container " + cid);
9641 PackageHelper.destroySdDir(cid);
9642 } else {
9643 Log.w(TAG, "Container " + cid + " is stale");
9644 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009645 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009646 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009647 }
9648
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009649 /*
9650 * Utility method to unload a list of specified containers
9651 */
9652 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9653 // Just unmount all valid containers.
9654 for (SdInstallArgs arg : cidArgs) {
9655 synchronized (mInstallLock) {
9656 arg.doPostDeleteLI(false);
9657 }
9658 }
9659 }
9660
9661 /*
9662 * Unload packages mounted on external media. This involves deleting
9663 * package data from internal structures, sending broadcasts about
9664 * diabled packages, gc'ing to free up references, unmounting all
9665 * secure containers corresponding to packages on external media, and
9666 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9667 * Please note that we always have to post this message if status has
9668 * been requested no matter what.
9669 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009670 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009671 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009672 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009673 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009674 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009675 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009676 for (SdInstallArgs args : keys) {
9677 String cid = args.cid;
9678 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009679 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009680 // Delete package internally
9681 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9682 synchronized (mInstallLock) {
9683 boolean res = deletePackageLI(pkgName, false,
9684 PackageManager.DONT_DELETE_DATA, outInfo);
9685 if (res) {
9686 pkgList.add(pkgName);
9687 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009688 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009689 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009690 }
9691 }
9692 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009693 // We have to absolutely send UPDATED_MEDIA_STATUS only
9694 // after confirming that all the receivers processed the ordered
9695 // broadcast when packages get disabled, force a gc to clean things up.
9696 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009697 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009698 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9699 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9700 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009701 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9702 reportStatus ? 1 : 0, 1, keys);
9703 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009704 }
9705 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009706 } else {
9707 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9708 reportStatus ? 1 : 0, -1, keys);
9709 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009710 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009711 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009712
9713 public void movePackage(final String packageName,
9714 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009715 mContext.enforceCallingOrSelfPermission(
9716 android.Manifest.permission.MOVE_PACKAGE, null);
9717 int returnCode = PackageManager.MOVE_SUCCEEDED;
9718 int currFlags = 0;
9719 int newFlags = 0;
9720 synchronized (mPackages) {
9721 PackageParser.Package pkg = mPackages.get(packageName);
9722 if (pkg == null) {
9723 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009724 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009725 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009726 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009727 Slog.w(TAG, "Cannot move system application");
9728 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009729 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009730 Slog.w(TAG, "Cannot move forward locked app.");
9731 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009732 } else if (pkg.mOperationPending) {
9733 Slog.w(TAG, "Attempt to move package which has pending operations");
9734 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009735 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009736 // Find install location first
9737 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9738 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9739 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009740 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009741 } else {
9742 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9743 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009744 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9745 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009746 if (newFlags == currFlags) {
9747 Slog.w(TAG, "No move required. Trying to move to same location");
9748 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9749 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009750 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009751 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9752 pkg.mOperationPending = true;
9753 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009754 }
9755 }
9756 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009757 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009758 } else {
9759 Message msg = mHandler.obtainMessage(INIT_COPY);
9760 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009761 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9762 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9763 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009764 msg.obj = mp;
9765 mHandler.sendMessage(msg);
9766 }
9767 }
9768 }
9769
9770 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9771 // Queue up an async operation since the package deletion may take a little while.
9772 mHandler.post(new Runnable() {
9773 public void run() {
9774 mHandler.removeCallbacks(this);
9775 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009776 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9777 int uidArr[] = null;
9778 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009779 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009780 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009781 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009782 Slog.w(TAG, " Package " + mp.packageName +
9783 " doesn't exist. Aborting move");
9784 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9785 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9786 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9787 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9788 " Aborting move and returning error");
9789 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9790 } else {
9791 uidArr = new int[] { pkg.applicationInfo.uid };
9792 pkgList = new ArrayList<String>();
9793 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009794 }
9795 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009796 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9797 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009798 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009799 // Update package code and resource paths
9800 synchronized (mInstallLock) {
9801 synchronized (mPackages) {
9802 PackageParser.Package pkg = mPackages.get(mp.packageName);
9803 // Recheck for package again.
9804 if (pkg == null ) {
9805 Slog.w(TAG, " Package " + mp.packageName +
9806 " doesn't exist. Aborting move");
9807 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9808 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9809 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9810 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9811 " Aborting move and returning error");
9812 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9813 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009814 final String oldCodePath = pkg.mPath;
9815 final String newCodePath = mp.targetArgs.getCodePath();
9816 final String newResPath = mp.targetArgs.getResourcePath();
9817 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009818 pkg.mPath = newCodePath;
9819 // Move dex files around
9820 if (moveDexFilesLI(pkg)
9821 != PackageManager.INSTALL_SUCCEEDED) {
9822 // Moving of dex files failed. Set
9823 // error code and abort move.
9824 pkg.mPath = pkg.mScanPath;
9825 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9826 } else {
9827 pkg.mScanPath = newCodePath;
9828 pkg.applicationInfo.sourceDir = newCodePath;
9829 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009830 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009831 PackageSetting ps = (PackageSetting) pkg.mExtras;
9832 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9833 ps.codePathString = ps.codePath.getPath();
9834 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9835 ps.resourcePathString = ps.resourcePath.getPath();
9836 // Set the application info flag correctly.
9837 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9838 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9839 } else {
9840 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9841 }
9842 ps.setFlags(pkg.applicationInfo.flags);
9843 mAppDirs.remove(oldCodePath);
9844 mAppDirs.put(newCodePath, pkg);
9845 // Persist settings
9846 mSettings.writeLP();
9847 }
9848 }
9849 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009850 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009851 // Send resources available broadcast
9852 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009853 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009854 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009855 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009856 // Clean up failed installation
9857 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009858 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009859 }
9860 } else {
9861 // Force a gc to clear things up.
9862 Runtime.getRuntime().gc();
9863 // Delete older code
9864 synchronized (mInstallLock) {
9865 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009866 }
9867 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009868
9869 // Allow more operations on this file if we didn't fail because
9870 // an operation was already pending for this package.
9871 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9872 synchronized (mPackages) {
9873 PackageParser.Package pkg = mPackages.get(mp.packageName);
9874 if (pkg != null) {
9875 pkg.mOperationPending = false;
9876 }
9877 }
9878 }
9879
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009880 IPackageMoveObserver observer = mp.observer;
9881 if (observer != null) {
9882 try {
9883 observer.packageMoved(mp.packageName, returnCode);
9884 } catch (RemoteException e) {
9885 Log.i(TAG, "Observer no longer exists.");
9886 }
9887 }
9888 }
9889 });
9890 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009891
9892 public boolean setInstallLocation(int loc) {
9893 mContext.enforceCallingOrSelfPermission(
9894 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9895 if (getInstallLocation() == loc) {
9896 return true;
9897 }
9898 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9899 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9900 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9901 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9902 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9903 return true;
9904 }
9905 return false;
9906 }
9907
9908 public int getInstallLocation() {
9909 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9910 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009912}