blob: 4c15c940eff7f948d462ef97b6123c6da3e5c90d [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
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700225 // This is the object monitoring the system app dir.
226 final FileObserver mVendorInstallObserver;
227
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 // This is the object monitoring mAppInstallDir.
229 final FileObserver mAppInstallObserver;
230
231 // This is the object monitoring mDrmAppPrivateInstallDir.
232 final FileObserver mDrmAppInstallObserver;
233
234 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
235 // LOCK HELD. Can be called with mInstallLock held.
236 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238 final File mFrameworkDir;
239 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700240 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700242 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243
244 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
245 // apps.
246 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 // Lock for state used when installing and doing other long running
251 // operations. Methods that must be called with this lock held have
252 // the prefix "LI".
253 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 // These are the directories in the 3rd party applications installed dir
256 // that we have currently loaded packages from. Keys are the application's
257 // installed zip file (absolute codePath), and values are Package.
258 final HashMap<String, PackageParser.Package> mAppDirs =
259 new HashMap<String, PackageParser.Package>();
260
261 // Information for the parser to write more useful error messages.
262 File mScanningPath;
263 int mLastScanError;
264
265 final int[] mOutPermissions = new int[3];
266
267 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269 // Keys are String (package name), values are Package. This also serves
270 // as the lock for the global state. Methods that must be called with
271 // this lock held have the prefix "LP".
272 final HashMap<String, PackageParser.Package> mPackages =
273 new HashMap<String, PackageParser.Package>();
274
275 final Settings mSettings;
276 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800277
278 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
279 int[] mGlobalGids;
280
281 // These are the built-in uid -> permission mappings that were read from the
282 // etc/permissions.xml file.
283 final SparseArray<HashSet<String>> mSystemPermissions =
284 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800286 // These are the built-in shared libraries that were read from the
287 // etc/permissions.xml file.
288 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800289
Dianne Hackborn49237342009-08-27 20:08:01 -0700290 // Temporary for building the final shared libraries for an .apk.
291 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800292
Dianne Hackborn49237342009-08-27 20:08:01 -0700293 // These are the features this devices supports that were read from the
294 // etc/permissions.xml file.
295 final HashMap<String, FeatureInfo> mAvailableFeatures =
296 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 // All available activities, for your resolving pleasure.
299 final ActivityIntentResolver mActivities =
300 new ActivityIntentResolver();
301
302 // All available receivers, for your resolving pleasure.
303 final ActivityIntentResolver mReceivers =
304 new ActivityIntentResolver();
305
306 // All available services, for your resolving pleasure.
307 final ServiceIntentResolver mServices = new ServiceIntentResolver();
308
309 // Keys are String (provider class name), values are Provider.
310 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
311 new HashMap<ComponentName, PackageParser.Provider>();
312
313 // Mapping from provider base names (first directory in content URI codePath)
314 // to the provider information.
315 final HashMap<String, PackageParser.Provider> mProviders =
316 new HashMap<String, PackageParser.Provider>();
317
318 // Mapping from instrumentation class names to info about them.
319 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
320 new HashMap<ComponentName, PackageParser.Instrumentation>();
321
322 // Mapping from permission names to info about them.
323 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
324 new HashMap<String, PackageParser.PermissionGroup>();
325
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800326 // Packages whose data we have transfered into another package, thus
327 // should no longer exist.
328 final HashSet<String> mTransferedPackages = new HashSet<String>();
329
Dianne Hackborn854060af2009-07-09 18:14:31 -0700330 // Broadcast actions that are only available to the system.
331 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800333 boolean mSystemReady;
334 boolean mSafeMode;
335 boolean mHasSystemUidErrors;
336
337 ApplicationInfo mAndroidApplication;
338 final ActivityInfo mResolveActivity = new ActivityInfo();
339 final ResolveInfo mResolveInfo = new ResolveInfo();
340 ComponentName mResolveComponentName;
341 PackageParser.Package mPlatformPackage;
342
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700343 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800344 final HashMap<String, ArrayList<String>> mPendingBroadcasts
345 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800346 // Service Connection to remote media container service to copy
347 // package uri's from external media onto secure containers
348 // or internal storage.
349 private IMediaContainerService mContainerService = null;
350
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700351 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800352 static final int MCS_BOUND = 3;
353 static final int END_COPY = 4;
354 static final int INIT_COPY = 5;
355 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800356 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800357 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800358 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800359 static final int MCS_RECONNECT = 10;
360 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700361 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700362 static final int WRITE_SETTINGS = 13;
363
364 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800365
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700366 // Delay time in millisecs
367 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800368 final private DefaultContainerConnection mDefContainerConn =
369 new DefaultContainerConnection();
370 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800371 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800373 IMediaContainerService imcs =
374 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 }
377
378 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800379 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800380 }
381 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700382
Christopher Tate1bb69062010-02-19 17:02:12 -0800383 // Recordkeeping of restore-after-install operations that are currently in flight
384 // between the Package Manager and the Backup Manager
385 class PostInstallData {
386 public InstallArgs args;
387 public PackageInstalledInfo res;
388
389 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
390 args = _a;
391 res = _r;
392 }
393 };
394 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
395 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
396
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700397 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800398 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800399 final ArrayList<HandlerParams> mPendingInstalls =
400 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800401
402 private boolean connectToService() {
403 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
404 " DefaultContainerService");
405 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700406 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800407 if (mContext.bindService(service, mDefContainerConn,
408 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 mBound = true;
411 return true;
412 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800414 return false;
415 }
416
417 private void disconnectService() {
418 mContainerService = null;
419 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700420 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800421 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700422 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800423 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800424
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700425 PackageHandler(Looper looper) {
426 super(looper);
427 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700428
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700429 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700430 try {
431 doHandleMessage(msg);
432 } finally {
433 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
434 }
435 }
436
437 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700438 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800439 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800440 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800441 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800442 int idx = mPendingInstalls.size();
443 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
444 // If a bind was already initiated we dont really
445 // need to do anything. The pending install
446 // will be processed later on.
447 if (!mBound) {
448 // If this is the only one pending we might
449 // have to bind to the service again.
450 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800451 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800452 params.serviceError();
453 return;
454 } else {
455 // Once we bind to the service, the first
456 // pending request will be processed.
457 mPendingInstalls.add(idx, params);
458 }
459 } else {
460 mPendingInstalls.add(idx, params);
461 // Already bound to the service. Just make
462 // sure we trigger off processing the first request.
463 if (idx == 0) {
464 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800465 }
466 }
467 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800468 }
469 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800471 if (msg.obj != null) {
472 mContainerService = (IMediaContainerService) msg.obj;
473 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800474 if (mContainerService == null) {
475 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800476 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800477 for (HandlerParams params : mPendingInstalls) {
478 mPendingInstalls.remove(0);
479 // Indicate service bind error
480 params.serviceError();
481 }
482 mPendingInstalls.clear();
483 } else if (mPendingInstalls.size() > 0) {
484 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800485 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800486 params.startCopy();
487 }
488 } else {
489 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800490 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800491 }
492 break;
493 }
494 case MCS_RECONNECT : {
495 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
496 if (mPendingInstalls.size() > 0) {
497 if (mBound) {
498 disconnectService();
499 }
500 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800501 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800502 for (HandlerParams params : mPendingInstalls) {
503 mPendingInstalls.remove(0);
504 // Indicate service bind error
505 params.serviceError();
506 }
507 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800508 }
509 }
510 break;
511 }
512 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800513 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
514 // Delete pending install
515 if (mPendingInstalls.size() > 0) {
516 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800517 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800518 if (mPendingInstalls.size() == 0) {
519 if (mBound) {
520 disconnectService();
521 }
522 } else {
523 // There are more pending requests in queue.
524 // Just post MCS_BOUND message to trigger processing
525 // of next pending install.
526 mHandler.sendEmptyMessage(MCS_BOUND);
527 }
528 break;
529 }
530 case MCS_GIVE_UP: {
531 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
532 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800533 break;
534 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800536 String packages[];
537 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700538 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700540 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800542 if (mPendingBroadcasts == null) {
543 return;
544 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700545 size = mPendingBroadcasts.size();
546 if (size <= 0) {
547 // Nothing to be done. Just return
548 return;
549 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800550 packages = new String[size];
551 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700552 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800553 Iterator<HashMap.Entry<String, ArrayList<String>>>
554 it = mPendingBroadcasts.entrySet().iterator();
555 int i = 0;
556 while (it.hasNext() && i < size) {
557 HashMap.Entry<String, ArrayList<String>> ent = it.next();
558 packages[i] = ent.getKey();
559 components[i] = ent.getValue();
560 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700561 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800562 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700563 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800564 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700565 mPendingBroadcasts.clear();
566 }
567 // Send broadcasts
568 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800569 sendPackageChangedBroadcast(packages[i], true,
570 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700571 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700572 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700573 break;
574 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800575 case START_CLEANING_PACKAGE: {
576 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700577 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800578 synchronized (mPackages) {
579 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
580 mSettings.mPackagesToBeCleaned.add(packageName);
581 }
582 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700583 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800584 startCleaningPackages();
585 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800586 case POST_INSTALL: {
587 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
588 PostInstallData data = mRunningInstalls.get(msg.arg1);
589 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700590 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800591
592 if (data != null) {
593 InstallArgs args = data.args;
594 PackageInstalledInfo res = data.res;
595
596 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700597 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800598 Bundle extras = new Bundle(1);
599 extras.putInt(Intent.EXTRA_UID, res.uid);
600 final boolean update = res.removedInfo.removedPackage != null;
601 if (update) {
602 extras.putBoolean(Intent.EXTRA_REPLACING, true);
603 }
604 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
605 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700606 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800607 if (update) {
608 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
609 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700610 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800611 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700612 if (res.removedInfo.args != null) {
613 // Remove the replaced package's older resources safely now
614 deleteOld = true;
615 }
616 }
617 // Force a gc to clear up things
618 Runtime.getRuntime().gc();
619 // We delete after a gc for applications on sdcard.
620 if (deleteOld) {
621 synchronized (mInstallLock) {
622 res.removedInfo.args.doPostDeleteLI(true);
623 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800624 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800625 if (args.observer != null) {
626 try {
627 args.observer.packageInstalled(res.name, res.returnCode);
628 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800629 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800630 }
631 }
632 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800633 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800634 }
635 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700636 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700637 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
638 boolean reportStatus = msg.arg1 == 1;
639 boolean doGc = msg.arg2 == 1;
640 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
641 if (doGc) {
642 // Force a gc to clear up stale containers.
643 Runtime.getRuntime().gc();
644 }
645 if (msg.obj != null) {
646 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
647 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
648 // Unload containers
649 unloadAllContainers(args);
650 }
651 if (reportStatus) {
652 try {
653 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
654 PackageHelper.getMountService().finishMediaUpdate();
655 } catch (RemoteException e) {
656 Log.e(TAG, "MountService not running?");
657 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700658 }
659 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700660 case WRITE_SETTINGS: {
661 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
662 synchronized (mPackages) {
663 removeMessages(WRITE_SETTINGS);
664 mSettings.writeLP();
665 }
666 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
667 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700668 }
669 }
670 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800671
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700672 void scheduleWriteSettingsLocked() {
673 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
674 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
675 }
676 }
677
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800678 static boolean installOnSd(int flags) {
679 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700680 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800681 return false;
682 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700683 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
684 return true;
685 }
686 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800687 }
688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689 public static final IPackageManager main(Context context, boolean factoryTest) {
690 PackageManagerService m = new PackageManagerService(context, factoryTest);
691 ServiceManager.addService("package", m);
692 return m;
693 }
694
695 static String[] splitString(String str, char sep) {
696 int count = 1;
697 int i = 0;
698 while ((i=str.indexOf(sep, i)) >= 0) {
699 count++;
700 i++;
701 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800703 String[] res = new String[count];
704 i=0;
705 count = 0;
706 int lastI=0;
707 while ((i=str.indexOf(sep, i)) >= 0) {
708 res[count] = str.substring(lastI, i);
709 count++;
710 i++;
711 lastI = i;
712 }
713 res[count] = str.substring(lastI, str.length());
714 return res;
715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800718 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800722 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 mContext = context;
726 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700727 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 mMetrics = new DisplayMetrics();
729 mSettings = new Settings();
730 mSettings.addSharedUserLP("android.uid.system",
731 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
732 mSettings.addSharedUserLP("android.uid.phone",
733 MULTIPLE_APPLICATION_UIDS
734 ? RADIO_UID : FIRST_APPLICATION_UID,
735 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400736 mSettings.addSharedUserLP("android.uid.log",
737 MULTIPLE_APPLICATION_UIDS
738 ? LOG_UID : FIRST_APPLICATION_UID,
739 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800740
741 String separateProcesses = SystemProperties.get("debug.separate_processes");
742 if (separateProcesses != null && separateProcesses.length() > 0) {
743 if ("*".equals(separateProcesses)) {
744 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
745 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800746 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 } else {
748 mDefParseFlags = 0;
749 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800750 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800751 + separateProcesses);
752 }
753 } else {
754 mDefParseFlags = 0;
755 mSeparateProcesses = null;
756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800758 Installer installer = new Installer();
759 // Little hacky thing to check if installd is here, to determine
760 // whether we are running on the simulator and thus need to take
761 // care of building the /data file structure ourself.
762 // (apparently the sim now has a working installer)
763 if (installer.ping() && Process.supportsProcesses()) {
764 mInstaller = installer;
765 } else {
766 mInstaller = null;
767 }
768
769 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
770 Display d = wm.getDefaultDisplay();
771 d.getMetrics(mMetrics);
772
773 synchronized (mInstallLock) {
774 synchronized (mPackages) {
775 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700776 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 File dataDir = Environment.getDataDirectory();
779 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800780 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
782
783 if (mInstaller == null) {
784 // Make sure these dirs exist, when we are running in
785 // the simulator.
786 // Make a wide-open directory for random misc stuff.
787 File miscDir = new File(dataDir, "misc");
788 miscDir.mkdirs();
789 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800790 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 mDrmAppPrivateInstallDir.mkdirs();
792 }
793
794 readPermissions();
795
796 mRestoredSettings = mSettings.readLP();
797 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800798
799 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800801
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800802 // Set flag to monitor and not change apk file paths when
803 // scanning install directories.
804 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700805 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800806 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800807 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700808 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800809
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700813 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700816 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 /**
819 * Out of paranoia, ensure that everything in the boot class
820 * path has been dexed.
821 */
822 String bootClassPath = System.getProperty("java.boot.class.path");
823 if (bootClassPath != null) {
824 String[] paths = splitString(bootClassPath, ':');
825 for (int i=0; i<paths.length; i++) {
826 try {
827 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
828 libFiles.add(paths[i]);
829 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700830 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800831 }
832 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800833 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800835 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
837 }
838 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800839 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 /**
843 * Also ensure all external libraries have had dexopt run on them.
844 */
845 if (mSharedLibraries.size() > 0) {
846 Iterator<String> libs = mSharedLibraries.values().iterator();
847 while (libs.hasNext()) {
848 String lib = libs.next();
849 try {
850 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
851 libFiles.add(lib);
852 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700853 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 }
855 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800856 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800858 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 }
860 }
861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 // Gross hack for now: we know this file doesn't contain any
864 // code, so don't dexopt it to avoid the resulting log spew.
865 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 /**
868 * And there are a number of commands implemented in Java, which
869 * we currently need to do the dexopt on so that they can be
870 * run from a non-root shell.
871 */
872 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700873 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 for (int i=0; i<frameworkFiles.length; i++) {
875 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
876 String path = libPath.getPath();
877 // Skip the file if we alrady did it.
878 if (libFiles.contains(path)) {
879 continue;
880 }
881 // Skip the file if it is not a type we want to dexopt.
882 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
883 continue;
884 }
885 try {
886 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
887 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700888 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800889 }
890 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800891 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800893 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 }
895 }
896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800897
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700898 if (didDexOpt) {
899 // If we had to do a dexopt of one of the previous
900 // things, then something on the system has changed.
901 // Consider this significant, and wipe away all other
902 // existing dexopt files to ensure we don't leave any
903 // dangling around.
904 String[] files = mDalvikCacheDir.list();
905 if (files != null) {
906 for (int i=0; i<files.length; i++) {
907 String fn = files[i];
908 if (fn.startsWith("data@app@")
909 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800910 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700911 (new File(mDalvikCacheDir, fn)).delete();
912 }
913 }
914 }
915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800917
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800918 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 mFrameworkInstallObserver = new AppDirObserver(
920 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
921 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700922 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
923 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800924 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800925
926 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
928 mSystemInstallObserver = new AppDirObserver(
929 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
930 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700931 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
932 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800933
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700934 // Collect all vendor packages.
935 mVendorAppDir = new File("/vendor/app");
936 mVendorInstallObserver = new AppDirObserver(
937 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
938 mVendorInstallObserver.startWatching();
939 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
940 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
941
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800942 if (mInstaller != null) {
943 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
944 mInstaller.moveFiles();
945 }
946
947 // Prune any system packages that no longer exist.
948 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
949 while (psit.hasNext()) {
950 PackageSetting ps = psit.next();
951 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800952 && !mPackages.containsKey(ps.name)
953 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800954 psit.remove();
955 String msg = "System package " + ps.name
956 + " no longer exists; wiping its data";
957 reportSettingsProblem(Log.WARN, msg);
958 if (mInstaller != null) {
959 // XXX how to set useEncryptedFSDir for packages that
960 // are not encrypted?
961 mInstaller.remove(ps.name, true);
962 }
963 }
964 }
965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800966 mAppInstallDir = new File(dataDir, "app");
967 if (mInstaller == null) {
968 // Make sure these dirs exist, when we are running in
969 // the simulator.
970 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
971 }
972 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800973 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 //clean up list
975 for(int i = 0; i < deletePkgsList.size(); i++) {
976 //clean up here
977 cleanupInstallFailedPackage(deletePkgsList.get(i));
978 }
979 //delete tmp files
980 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800981
982 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 SystemClock.uptimeMillis());
984 mAppInstallObserver = new AppDirObserver(
985 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
986 mAppInstallObserver.startWatching();
987 scanDirLI(mAppInstallDir, 0, scanMode);
988
989 mDrmAppInstallObserver = new AppDirObserver(
990 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
991 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800992 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800994 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800996 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 + ((SystemClock.uptimeMillis()-startTime)/1000f)
998 + " seconds");
999
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001000 // If the platform SDK has changed since the last time we booted,
1001 // we need to re-grant app permission to catch any new ones that
1002 // appear. This is really a hack, and means that apps can in some
1003 // cases get permissions that the user didn't initially explicitly
1004 // allow... it would be nice to have some better way to handle
1005 // this situation.
1006 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1007 != mSdkVersion;
1008 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1009 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1010 + "; regranting permissions for internal storage");
1011 mSettings.mInternalSdkPlatform = mSdkVersion;
1012
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001013 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014
1015 mSettings.writeLP();
1016
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001017 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001019
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 // Now after opening every single application zip, make sure they
1021 // are all flushed. Not really needed, but keeps things nice and
1022 // tidy.
1023 Runtime.getRuntime().gc();
1024 } // synchronized (mPackages)
1025 } // synchronized (mInstallLock)
1026 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 @Override
1029 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1030 throws RemoteException {
1031 try {
1032 return super.onTransact(code, data, reply, flags);
1033 } catch (RuntimeException e) {
1034 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001035 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
1037 throw e;
1038 }
1039 }
1040
Dianne Hackborne6620b22010-01-22 14:46:21 -08001041 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001042 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001044 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1045 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001047 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001048 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050 } else {
1051 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001052 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 File dataDir = new File(pkg.applicationInfo.dataDir);
1054 dataDir.delete();
1055 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001056 if (ps.codePath != null) {
1057 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001058 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001059 }
1060 }
1061 if (ps.resourcePath != null) {
1062 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001063 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001064 }
1065 }
1066 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068
1069 void readPermissions() {
1070 // Read permissions from .../etc/permission directory.
1071 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1072 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001073 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 return;
1075 }
1076 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001077 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 return;
1079 }
1080
1081 // Iterate over the files in the directory and scan .xml files
1082 for (File f : libraryDir.listFiles()) {
1083 // We'll read platform.xml last
1084 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1085 continue;
1086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001089 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 continue;
1091 }
1092 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001093 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 continue;
1095 }
1096
1097 readPermissionsFromXml(f);
1098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1101 final File permFile = new File(Environment.getRootDirectory(),
1102 "etc/permissions/platform.xml");
1103 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001104
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001105 StringBuilder sb = new StringBuilder(128);
1106 sb.append("Libs:");
1107 Iterator<String> it = mSharedLibraries.keySet().iterator();
1108 while (it.hasNext()) {
1109 sb.append(' ');
1110 String name = it.next();
1111 sb.append(name);
1112 sb.append(':');
1113 sb.append(mSharedLibraries.get(name));
1114 }
1115 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001116
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001117 sb.setLength(0);
1118 sb.append("Features:");
1119 it = mAvailableFeatures.keySet().iterator();
1120 while (it.hasNext()) {
1121 sb.append(' ');
1122 sb.append(it.next());
1123 }
1124 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001126
1127 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 FileReader permReader = null;
1129 try {
1130 permReader = new FileReader(permFile);
1131 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001132 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 return;
1134 }
1135
1136 try {
1137 XmlPullParser parser = Xml.newPullParser();
1138 parser.setInput(permReader);
1139
1140 XmlUtils.beginDocument(parser, "permissions");
1141
1142 while (true) {
1143 XmlUtils.nextElement(parser);
1144 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1145 break;
1146 }
1147
1148 String name = parser.getName();
1149 if ("group".equals(name)) {
1150 String gidStr = parser.getAttributeValue(null, "gid");
1151 if (gidStr != null) {
1152 int gid = Integer.parseInt(gidStr);
1153 mGlobalGids = appendInt(mGlobalGids, gid);
1154 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001155 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 + parser.getPositionDescription());
1157 }
1158
1159 XmlUtils.skipCurrentTag(parser);
1160 continue;
1161 } else if ("permission".equals(name)) {
1162 String perm = parser.getAttributeValue(null, "name");
1163 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001164 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 + parser.getPositionDescription());
1166 XmlUtils.skipCurrentTag(parser);
1167 continue;
1168 }
1169 perm = perm.intern();
1170 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001171
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 } else if ("assign-permission".equals(name)) {
1173 String perm = parser.getAttributeValue(null, "name");
1174 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001175 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 + parser.getPositionDescription());
1177 XmlUtils.skipCurrentTag(parser);
1178 continue;
1179 }
1180 String uidStr = parser.getAttributeValue(null, "uid");
1181 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001182 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 + parser.getPositionDescription());
1184 XmlUtils.skipCurrentTag(parser);
1185 continue;
1186 }
1187 int uid = Process.getUidForName(uidStr);
1188 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001189 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001190 + uidStr + "\" at "
1191 + parser.getPositionDescription());
1192 XmlUtils.skipCurrentTag(parser);
1193 continue;
1194 }
1195 perm = perm.intern();
1196 HashSet<String> perms = mSystemPermissions.get(uid);
1197 if (perms == null) {
1198 perms = new HashSet<String>();
1199 mSystemPermissions.put(uid, perms);
1200 }
1201 perms.add(perm);
1202 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 } else if ("library".equals(name)) {
1205 String lname = parser.getAttributeValue(null, "name");
1206 String lfile = parser.getAttributeValue(null, "file");
1207 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001208 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001209 + parser.getPositionDescription());
1210 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001211 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 + parser.getPositionDescription());
1213 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001214 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 mSharedLibraries.put(lname, lfile);
1216 }
1217 XmlUtils.skipCurrentTag(parser);
1218 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001219
Dianne Hackborn49237342009-08-27 20:08:01 -07001220 } else if ("feature".equals(name)) {
1221 String fname = parser.getAttributeValue(null, "name");
1222 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001223 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001224 + parser.getPositionDescription());
1225 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001226 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001227 FeatureInfo fi = new FeatureInfo();
1228 fi.name = fname;
1229 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 }
1231 XmlUtils.skipCurrentTag(parser);
1232 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001233
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001234 } else {
1235 XmlUtils.skipCurrentTag(parser);
1236 continue;
1237 }
1238
1239 }
1240 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001241 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001243 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 }
1245 }
1246
1247 void readPermission(XmlPullParser parser, String name)
1248 throws IOException, XmlPullParserException {
1249
1250 name = name.intern();
1251
1252 BasePermission bp = mSettings.mPermissions.get(name);
1253 if (bp == null) {
1254 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1255 mSettings.mPermissions.put(name, bp);
1256 }
1257 int outerDepth = parser.getDepth();
1258 int type;
1259 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1260 && (type != XmlPullParser.END_TAG
1261 || parser.getDepth() > outerDepth)) {
1262 if (type == XmlPullParser.END_TAG
1263 || type == XmlPullParser.TEXT) {
1264 continue;
1265 }
1266
1267 String tagName = parser.getName();
1268 if ("group".equals(tagName)) {
1269 String gidStr = parser.getAttributeValue(null, "gid");
1270 if (gidStr != null) {
1271 int gid = Process.getGidForName(gidStr);
1272 bp.gids = appendInt(bp.gids, gid);
1273 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001274 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 + parser.getPositionDescription());
1276 }
1277 }
1278 XmlUtils.skipCurrentTag(parser);
1279 }
1280 }
1281
1282 static int[] appendInt(int[] cur, int val) {
1283 if (cur == null) {
1284 return new int[] { val };
1285 }
1286 final int N = cur.length;
1287 for (int i=0; i<N; i++) {
1288 if (cur[i] == val) {
1289 return cur;
1290 }
1291 }
1292 int[] ret = new int[N+1];
1293 System.arraycopy(cur, 0, ret, 0, N);
1294 ret[N] = val;
1295 return ret;
1296 }
1297
1298 static int[] appendInts(int[] cur, int[] add) {
1299 if (add == null) return cur;
1300 if (cur == null) return add;
1301 final int N = add.length;
1302 for (int i=0; i<N; i++) {
1303 cur = appendInt(cur, add[i]);
1304 }
1305 return cur;
1306 }
1307
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001308 static int[] removeInt(int[] cur, int val) {
1309 if (cur == null) {
1310 return null;
1311 }
1312 final int N = cur.length;
1313 for (int i=0; i<N; i++) {
1314 if (cur[i] == val) {
1315 int[] ret = new int[N-1];
1316 if (i > 0) {
1317 System.arraycopy(cur, 0, ret, 0, i);
1318 }
1319 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001320 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001321 }
1322 return ret;
1323 }
1324 }
1325 return cur;
1326 }
1327
1328 static int[] removeInts(int[] cur, int[] rem) {
1329 if (rem == null) return cur;
1330 if (cur == null) return cur;
1331 final int N = rem.length;
1332 for (int i=0; i<N; i++) {
1333 cur = removeInt(cur, rem[i]);
1334 }
1335 return cur;
1336 }
1337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001339 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1340 // The package has been uninstalled but has retained data and resources.
1341 return PackageParser.generatePackageInfo(p, null, flags);
1342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001343 final PackageSetting ps = (PackageSetting)p.mExtras;
1344 if (ps == null) {
1345 return null;
1346 }
1347 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1348 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1349 }
1350
1351 public PackageInfo getPackageInfo(String packageName, int flags) {
1352 synchronized (mPackages) {
1353 PackageParser.Package p = mPackages.get(packageName);
1354 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001355 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 + ": " + p);
1357 if (p != null) {
1358 return generatePackageInfo(p, flags);
1359 }
1360 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1361 return generatePackageInfoFromSettingsLP(packageName, flags);
1362 }
1363 }
1364 return null;
1365 }
1366
Dianne Hackborn47096932010-02-11 15:57:09 -08001367 public String[] currentToCanonicalPackageNames(String[] names) {
1368 String[] out = new String[names.length];
1369 synchronized (mPackages) {
1370 for (int i=names.length-1; i>=0; i--) {
1371 PackageSetting ps = mSettings.mPackages.get(names[i]);
1372 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1373 }
1374 }
1375 return out;
1376 }
1377
1378 public String[] canonicalToCurrentPackageNames(String[] names) {
1379 String[] out = new String[names.length];
1380 synchronized (mPackages) {
1381 for (int i=names.length-1; i>=0; i--) {
1382 String cur = mSettings.mRenamedPackages.get(names[i]);
1383 out[i] = cur != null ? cur : names[i];
1384 }
1385 }
1386 return out;
1387 }
1388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 public int getPackageUid(String packageName) {
1390 synchronized (mPackages) {
1391 PackageParser.Package p = mPackages.get(packageName);
1392 if(p != null) {
1393 return p.applicationInfo.uid;
1394 }
1395 PackageSetting ps = mSettings.mPackages.get(packageName);
1396 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1397 return -1;
1398 }
1399 p = ps.pkg;
1400 return p != null ? p.applicationInfo.uid : -1;
1401 }
1402 }
1403
1404 public int[] getPackageGids(String packageName) {
1405 synchronized (mPackages) {
1406 PackageParser.Package p = mPackages.get(packageName);
1407 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001408 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 + ": " + p);
1410 if (p != null) {
1411 final PackageSetting ps = (PackageSetting)p.mExtras;
1412 final SharedUserSetting suid = ps.sharedUser;
1413 return suid != null ? suid.gids : ps.gids;
1414 }
1415 }
1416 // stupid thing to indicate an error.
1417 return new int[0];
1418 }
1419
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001420 static final PermissionInfo generatePermissionInfo(
1421 BasePermission bp, int flags) {
1422 if (bp.perm != null) {
1423 return PackageParser.generatePermissionInfo(bp.perm, flags);
1424 }
1425 PermissionInfo pi = new PermissionInfo();
1426 pi.name = bp.name;
1427 pi.packageName = bp.sourcePackage;
1428 pi.nonLocalizedLabel = bp.name;
1429 pi.protectionLevel = bp.protectionLevel;
1430 return pi;
1431 }
1432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 public PermissionInfo getPermissionInfo(String name, int flags) {
1434 synchronized (mPackages) {
1435 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001436 if (p != null) {
1437 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 return null;
1440 }
1441 }
1442
1443 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1444 synchronized (mPackages) {
1445 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1446 for (BasePermission p : mSettings.mPermissions.values()) {
1447 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001448 if (p.perm == null || p.perm.info.group == null) {
1449 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 }
1451 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001452 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1454 }
1455 }
1456 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 if (out.size() > 0) {
1459 return out;
1460 }
1461 return mPermissionGroups.containsKey(group) ? out : null;
1462 }
1463 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1466 synchronized (mPackages) {
1467 return PackageParser.generatePermissionGroupInfo(
1468 mPermissionGroups.get(name), flags);
1469 }
1470 }
1471
1472 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1473 synchronized (mPackages) {
1474 final int N = mPermissionGroups.size();
1475 ArrayList<PermissionGroupInfo> out
1476 = new ArrayList<PermissionGroupInfo>(N);
1477 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1478 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1479 }
1480 return out;
1481 }
1482 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1485 PackageSetting ps = mSettings.mPackages.get(packageName);
1486 if(ps != null) {
1487 if(ps.pkg == null) {
1488 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1489 if(pInfo != null) {
1490 return pInfo.applicationInfo;
1491 }
1492 return null;
1493 }
1494 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1495 }
1496 return null;
1497 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1500 PackageSetting ps = mSettings.mPackages.get(packageName);
1501 if(ps != null) {
1502 if(ps.pkg == null) {
1503 ps.pkg = new PackageParser.Package(packageName);
1504 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001505 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1506 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1507 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1508 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001509 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001510 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512 return generatePackageInfo(ps.pkg, flags);
1513 }
1514 return null;
1515 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1518 synchronized (mPackages) {
1519 PackageParser.Package p = mPackages.get(packageName);
1520 if (Config.LOGV) Log.v(
1521 TAG, "getApplicationInfo " + packageName
1522 + ": " + p);
1523 if (p != null) {
1524 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001525 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
1527 if ("android".equals(packageName)||"system".equals(packageName)) {
1528 return mAndroidApplication;
1529 }
1530 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1531 return generateApplicationInfoFromSettingsLP(packageName, flags);
1532 }
1533 }
1534 return null;
1535 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001536
1537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1539 mContext.enforceCallingOrSelfPermission(
1540 android.Manifest.permission.CLEAR_APP_CACHE, null);
1541 // Queue up an async operation since clearing cache may take a little while.
1542 mHandler.post(new Runnable() {
1543 public void run() {
1544 mHandler.removeCallbacks(this);
1545 int retCode = -1;
1546 if (mInstaller != null) {
1547 retCode = mInstaller.freeCache(freeStorageSize);
1548 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001549 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551 } //end if mInstaller
1552 if (observer != null) {
1553 try {
1554 observer.onRemoveCompleted(null, (retCode >= 0));
1555 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001556 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001557 }
1558 }
1559 }
1560 });
1561 }
1562
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001563 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001564 mContext.enforceCallingOrSelfPermission(
1565 android.Manifest.permission.CLEAR_APP_CACHE, null);
1566 // Queue up an async operation since clearing cache may take a little while.
1567 mHandler.post(new Runnable() {
1568 public void run() {
1569 mHandler.removeCallbacks(this);
1570 int retCode = -1;
1571 if (mInstaller != null) {
1572 retCode = mInstaller.freeCache(freeStorageSize);
1573 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001574 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001575 }
1576 }
1577 if(pi != null) {
1578 try {
1579 // Callback via pending intent
1580 int code = (retCode >= 0) ? 1 : 0;
1581 pi.sendIntent(null, code, null,
1582 null, null);
1583 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001584 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001585 }
1586 }
1587 }
1588 });
1589 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1592 synchronized (mPackages) {
1593 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001594
1595 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001597 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598 }
1599 if (mResolveComponentName.equals(component)) {
1600 return mResolveActivity;
1601 }
1602 }
1603 return null;
1604 }
1605
1606 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1607 synchronized (mPackages) {
1608 PackageParser.Activity a = mReceivers.mActivities.get(component);
1609 if (Config.LOGV) Log.v(
1610 TAG, "getReceiverInfo " + component + ": " + a);
1611 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1612 return PackageParser.generateActivityInfo(a, flags);
1613 }
1614 }
1615 return null;
1616 }
1617
1618 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1619 synchronized (mPackages) {
1620 PackageParser.Service s = mServices.mServices.get(component);
1621 if (Config.LOGV) Log.v(
1622 TAG, "getServiceInfo " + component + ": " + s);
1623 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1624 return PackageParser.generateServiceInfo(s, flags);
1625 }
1626 }
1627 return null;
1628 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001629
Dianne Hackborn361199b2010-08-30 17:42:07 -07001630 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1631 synchronized (mPackages) {
1632 PackageParser.Provider p = mProvidersByComponent.get(component);
1633 if (Config.LOGV) Log.v(
1634 TAG, "getProviderInfo " + component + ": " + p);
1635 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1636 return PackageParser.generateProviderInfo(p, flags);
1637 }
1638 }
1639 return null;
1640 }
1641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 public String[] getSystemSharedLibraryNames() {
1643 Set<String> libSet;
1644 synchronized (mPackages) {
1645 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001646 int size = libSet.size();
1647 if (size > 0) {
1648 String[] libs = new String[size];
1649 libSet.toArray(libs);
1650 return libs;
1651 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001652 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001653 return null;
1654 }
1655
1656 public FeatureInfo[] getSystemAvailableFeatures() {
1657 Collection<FeatureInfo> featSet;
1658 synchronized (mPackages) {
1659 featSet = mAvailableFeatures.values();
1660 int size = featSet.size();
1661 if (size > 0) {
1662 FeatureInfo[] features = new FeatureInfo[size+1];
1663 featSet.toArray(features);
1664 FeatureInfo fi = new FeatureInfo();
1665 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1666 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1667 features[size] = fi;
1668 return features;
1669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 }
1671 return null;
1672 }
1673
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001674 public boolean hasSystemFeature(String name) {
1675 synchronized (mPackages) {
1676 return mAvailableFeatures.containsKey(name);
1677 }
1678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 public int checkPermission(String permName, String pkgName) {
1681 synchronized (mPackages) {
1682 PackageParser.Package p = mPackages.get(pkgName);
1683 if (p != null && p.mExtras != null) {
1684 PackageSetting ps = (PackageSetting)p.mExtras;
1685 if (ps.sharedUser != null) {
1686 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1687 return PackageManager.PERMISSION_GRANTED;
1688 }
1689 } else if (ps.grantedPermissions.contains(permName)) {
1690 return PackageManager.PERMISSION_GRANTED;
1691 }
1692 }
1693 }
1694 return PackageManager.PERMISSION_DENIED;
1695 }
1696
1697 public int checkUidPermission(String permName, int uid) {
1698 synchronized (mPackages) {
1699 Object obj = mSettings.getUserIdLP(uid);
1700 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001701 GrantedPermissions gp = (GrantedPermissions)obj;
1702 if (gp.grantedPermissions.contains(permName)) {
1703 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 }
1705 } else {
1706 HashSet<String> perms = mSystemPermissions.get(uid);
1707 if (perms != null && perms.contains(permName)) {
1708 return PackageManager.PERMISSION_GRANTED;
1709 }
1710 }
1711 }
1712 return PackageManager.PERMISSION_DENIED;
1713 }
1714
1715 private BasePermission findPermissionTreeLP(String permName) {
1716 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1717 if (permName.startsWith(bp.name) &&
1718 permName.length() > bp.name.length() &&
1719 permName.charAt(bp.name.length()) == '.') {
1720 return bp;
1721 }
1722 }
1723 return null;
1724 }
1725
1726 private BasePermission checkPermissionTreeLP(String permName) {
1727 if (permName != null) {
1728 BasePermission bp = findPermissionTreeLP(permName);
1729 if (bp != null) {
1730 if (bp.uid == Binder.getCallingUid()) {
1731 return bp;
1732 }
1733 throw new SecurityException("Calling uid "
1734 + Binder.getCallingUid()
1735 + " is not allowed to add to permission tree "
1736 + bp.name + " owned by uid " + bp.uid);
1737 }
1738 }
1739 throw new SecurityException("No permission tree found for " + permName);
1740 }
1741
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001742 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1743 if (s1 == null) {
1744 return s2 == null;
1745 }
1746 if (s2 == null) {
1747 return false;
1748 }
1749 if (s1.getClass() != s2.getClass()) {
1750 return false;
1751 }
1752 return s1.equals(s2);
1753 }
1754
1755 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1756 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001757 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001758 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1759 if (!compareStrings(pi1.name, pi2.name)) return false;
1760 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1761 // We'll take care of setting this one.
1762 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1763 // These are not currently stored in settings.
1764 //if (!compareStrings(pi1.group, pi2.group)) return false;
1765 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1766 //if (pi1.labelRes != pi2.labelRes) return false;
1767 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1768 return true;
1769 }
1770
1771 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1772 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1773 throw new SecurityException("Label must be specified in permission");
1774 }
1775 BasePermission tree = checkPermissionTreeLP(info.name);
1776 BasePermission bp = mSettings.mPermissions.get(info.name);
1777 boolean added = bp == null;
1778 boolean changed = true;
1779 if (added) {
1780 bp = new BasePermission(info.name, tree.sourcePackage,
1781 BasePermission.TYPE_DYNAMIC);
1782 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1783 throw new SecurityException(
1784 "Not allowed to modify non-dynamic permission "
1785 + info.name);
1786 } else {
1787 if (bp.protectionLevel == info.protectionLevel
1788 && bp.perm.owner.equals(tree.perm.owner)
1789 && bp.uid == tree.uid
1790 && comparePermissionInfos(bp.perm.info, info)) {
1791 changed = false;
1792 }
1793 }
1794 bp.protectionLevel = info.protectionLevel;
1795 bp.perm = new PackageParser.Permission(tree.perm.owner,
1796 new PermissionInfo(info));
1797 bp.perm.info.packageName = tree.perm.info.packageName;
1798 bp.uid = tree.uid;
1799 if (added) {
1800 mSettings.mPermissions.put(info.name, bp);
1801 }
1802 if (changed) {
1803 if (!async) {
1804 mSettings.writeLP();
1805 } else {
1806 scheduleWriteSettingsLocked();
1807 }
1808 }
1809 return added;
1810 }
1811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 public boolean addPermission(PermissionInfo info) {
1813 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001814 return addPermissionLocked(info, false);
1815 }
1816 }
1817
1818 public boolean addPermissionAsync(PermissionInfo info) {
1819 synchronized (mPackages) {
1820 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 }
1822 }
1823
1824 public void removePermission(String name) {
1825 synchronized (mPackages) {
1826 checkPermissionTreeLP(name);
1827 BasePermission bp = mSettings.mPermissions.get(name);
1828 if (bp != null) {
1829 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1830 throw new SecurityException(
1831 "Not allowed to modify non-dynamic permission "
1832 + name);
1833 }
1834 mSettings.mPermissions.remove(name);
1835 mSettings.writeLP();
1836 }
1837 }
1838 }
1839
Dianne Hackborn854060af2009-07-09 18:14:31 -07001840 public boolean isProtectedBroadcast(String actionName) {
1841 synchronized (mPackages) {
1842 return mProtectedBroadcasts.contains(actionName);
1843 }
1844 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 public int checkSignatures(String pkg1, String pkg2) {
1847 synchronized (mPackages) {
1848 PackageParser.Package p1 = mPackages.get(pkg1);
1849 PackageParser.Package p2 = mPackages.get(pkg2);
1850 if (p1 == null || p1.mExtras == null
1851 || p2 == null || p2.mExtras == null) {
1852 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1853 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001854 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856 }
1857
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001858 public int checkUidSignatures(int uid1, int uid2) {
1859 synchronized (mPackages) {
1860 Signature[] s1;
1861 Signature[] s2;
1862 Object obj = mSettings.getUserIdLP(uid1);
1863 if (obj != null) {
1864 if (obj instanceof SharedUserSetting) {
1865 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1866 } else if (obj instanceof PackageSetting) {
1867 s1 = ((PackageSetting)obj).signatures.mSignatures;
1868 } else {
1869 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1870 }
1871 } else {
1872 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1873 }
1874 obj = mSettings.getUserIdLP(uid2);
1875 if (obj != null) {
1876 if (obj instanceof SharedUserSetting) {
1877 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1878 } else if (obj instanceof PackageSetting) {
1879 s2 = ((PackageSetting)obj).signatures.mSignatures;
1880 } else {
1881 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1882 }
1883 } else {
1884 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1885 }
1886 return checkSignaturesLP(s1, s2);
1887 }
1888 }
1889
1890 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1891 if (s1 == null) {
1892 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1894 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1895 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001896 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1898 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001899 HashSet<Signature> set1 = new HashSet<Signature>();
1900 for (Signature sig : s1) {
1901 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001903 HashSet<Signature> set2 = new HashSet<Signature>();
1904 for (Signature sig : s2) {
1905 set2.add(sig);
1906 }
1907 // Make sure s2 contains all signatures in s1.
1908 if (set1.equals(set2)) {
1909 return PackageManager.SIGNATURE_MATCH;
1910 }
1911 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 }
1913
1914 public String[] getPackagesForUid(int uid) {
1915 synchronized (mPackages) {
1916 Object obj = mSettings.getUserIdLP(uid);
1917 if (obj instanceof SharedUserSetting) {
1918 SharedUserSetting sus = (SharedUserSetting)obj;
1919 final int N = sus.packages.size();
1920 String[] res = new String[N];
1921 Iterator<PackageSetting> it = sus.packages.iterator();
1922 int i=0;
1923 while (it.hasNext()) {
1924 res[i++] = it.next().name;
1925 }
1926 return res;
1927 } else if (obj instanceof PackageSetting) {
1928 PackageSetting ps = (PackageSetting)obj;
1929 return new String[] { ps.name };
1930 }
1931 }
1932 return null;
1933 }
1934
1935 public String getNameForUid(int uid) {
1936 synchronized (mPackages) {
1937 Object obj = mSettings.getUserIdLP(uid);
1938 if (obj instanceof SharedUserSetting) {
1939 SharedUserSetting sus = (SharedUserSetting)obj;
1940 return sus.name + ":" + sus.userId;
1941 } else if (obj instanceof PackageSetting) {
1942 PackageSetting ps = (PackageSetting)obj;
1943 return ps.name;
1944 }
1945 }
1946 return null;
1947 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001948
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 public int getUidForSharedUser(String sharedUserName) {
1950 if(sharedUserName == null) {
1951 return -1;
1952 }
1953 synchronized (mPackages) {
1954 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1955 if(suid == null) {
1956 return -1;
1957 }
1958 return suid.userId;
1959 }
1960 }
1961
1962 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1963 int flags) {
1964 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001965 return chooseBestActivity(intent, resolvedType, flags, query);
1966 }
1967
Mihai Predaeae850c2009-05-13 10:13:48 +02001968 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1969 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 if (query != null) {
1971 final int N = query.size();
1972 if (N == 1) {
1973 return query.get(0);
1974 } else if (N > 1) {
1975 // If there is more than one activity with the same priority,
1976 // then let the user decide between them.
1977 ResolveInfo r0 = query.get(0);
1978 ResolveInfo r1 = query.get(1);
1979 if (false) {
1980 System.out.println(r0.activityInfo.name +
1981 "=" + r0.priority + " vs " +
1982 r1.activityInfo.name +
1983 "=" + r1.priority);
1984 }
1985 // If the first activity has a higher priority, or a different
1986 // default, then it is always desireable to pick it.
1987 if (r0.priority != r1.priority
1988 || r0.preferredOrder != r1.preferredOrder
1989 || r0.isDefault != r1.isDefault) {
1990 return query.get(0);
1991 }
1992 // If we have saved a preference for a preferred activity for
1993 // this Intent, use that.
1994 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1995 flags, query, r0.priority);
1996 if (ri != null) {
1997 return ri;
1998 }
1999 return mResolveInfo;
2000 }
2001 }
2002 return null;
2003 }
2004
2005 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
2006 int flags, List<ResolveInfo> query, int priority) {
2007 synchronized (mPackages) {
2008 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
2009 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02002010 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002011 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2012 if (prefs != null && prefs.size() > 0) {
2013 // First figure out how good the original match set is.
2014 // We will only allow preferred activities that came
2015 // from the same match quality.
2016 int match = 0;
2017 final int N = query.size();
2018 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2019 for (int j=0; j<N; j++) {
2020 ResolveInfo ri = query.get(j);
2021 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2022 + ": 0x" + Integer.toHexString(match));
2023 if (ri.match > match) match = ri.match;
2024 }
2025 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2026 + Integer.toHexString(match));
2027 match &= IntentFilter.MATCH_CATEGORY_MASK;
2028 final int M = prefs.size();
2029 for (int i=0; i<M; i++) {
2030 PreferredActivity pa = prefs.get(i);
2031 if (pa.mMatch != match) {
2032 continue;
2033 }
2034 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2035 if (DEBUG_PREFERRED) {
2036 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002037 if (ai != null) {
2038 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2039 } else {
2040 Log.v(TAG, " null");
2041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 }
2043 if (ai != null) {
2044 for (int j=0; j<N; j++) {
2045 ResolveInfo ri = query.get(j);
2046 if (!ri.activityInfo.applicationInfo.packageName
2047 .equals(ai.applicationInfo.packageName)) {
2048 continue;
2049 }
2050 if (!ri.activityInfo.name.equals(ai.name)) {
2051 continue;
2052 }
2053
2054 // Okay we found a previously set preferred app.
2055 // If the result set is different from when this
2056 // was created, we need to clear it and re-ask the
2057 // user their preference.
2058 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002059 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002060 + intent + " type " + resolvedType);
2061 mSettings.mPreferredActivities.removeFilter(pa);
2062 return null;
2063 }
2064
2065 // Yay!
2066 return ri;
2067 }
2068 }
2069 }
2070 }
2071 }
2072 return null;
2073 }
2074
2075 public List<ResolveInfo> queryIntentActivities(Intent intent,
2076 String resolvedType, int flags) {
2077 ComponentName comp = intent.getComponent();
2078 if (comp != null) {
2079 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2080 ActivityInfo ai = getActivityInfo(comp, flags);
2081 if (ai != null) {
2082 ResolveInfo ri = new ResolveInfo();
2083 ri.activityInfo = ai;
2084 list.add(ri);
2085 }
2086 return list;
2087 }
2088
2089 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002090 String pkgName = intent.getPackage();
2091 if (pkgName == null) {
2092 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2093 resolvedType, flags);
2094 }
2095 PackageParser.Package pkg = mPackages.get(pkgName);
2096 if (pkg != null) {
2097 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2098 resolvedType, flags, pkg.activities);
2099 }
2100 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 }
2102 }
2103
2104 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2105 Intent[] specifics, String[] specificTypes, Intent intent,
2106 String resolvedType, int flags) {
2107 final String resultsAction = intent.getAction();
2108
2109 List<ResolveInfo> results = queryIntentActivities(
2110 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2111 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2112
2113 int specificsPos = 0;
2114 int N;
2115
2116 // todo: note that the algorithm used here is O(N^2). This
2117 // isn't a problem in our current environment, but if we start running
2118 // into situations where we have more than 5 or 10 matches then this
2119 // should probably be changed to something smarter...
2120
2121 // First we go through and resolve each of the specific items
2122 // that were supplied, taking care of removing any corresponding
2123 // duplicate items in the generic resolve list.
2124 if (specifics != null) {
2125 for (int i=0; i<specifics.length; i++) {
2126 final Intent sintent = specifics[i];
2127 if (sintent == null) {
2128 continue;
2129 }
2130
2131 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2132 String action = sintent.getAction();
2133 if (resultsAction != null && resultsAction.equals(action)) {
2134 // If this action was explicitly requested, then don't
2135 // remove things that have it.
2136 action = null;
2137 }
2138 ComponentName comp = sintent.getComponent();
2139 ResolveInfo ri = null;
2140 ActivityInfo ai = null;
2141 if (comp == null) {
2142 ri = resolveIntent(
2143 sintent,
2144 specificTypes != null ? specificTypes[i] : null,
2145 flags);
2146 if (ri == null) {
2147 continue;
2148 }
2149 if (ri == mResolveInfo) {
2150 // ACK! Must do something better with this.
2151 }
2152 ai = ri.activityInfo;
2153 comp = new ComponentName(ai.applicationInfo.packageName,
2154 ai.name);
2155 } else {
2156 ai = getActivityInfo(comp, flags);
2157 if (ai == null) {
2158 continue;
2159 }
2160 }
2161
2162 // Look for any generic query activities that are duplicates
2163 // of this specific one, and remove them from the results.
2164 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2165 N = results.size();
2166 int j;
2167 for (j=specificsPos; j<N; j++) {
2168 ResolveInfo sri = results.get(j);
2169 if ((sri.activityInfo.name.equals(comp.getClassName())
2170 && sri.activityInfo.applicationInfo.packageName.equals(
2171 comp.getPackageName()))
2172 || (action != null && sri.filter.matchAction(action))) {
2173 results.remove(j);
2174 if (Config.LOGV) Log.v(
2175 TAG, "Removing duplicate item from " + j
2176 + " due to specific " + specificsPos);
2177 if (ri == null) {
2178 ri = sri;
2179 }
2180 j--;
2181 N--;
2182 }
2183 }
2184
2185 // Add this specific item to its proper place.
2186 if (ri == null) {
2187 ri = new ResolveInfo();
2188 ri.activityInfo = ai;
2189 }
2190 results.add(specificsPos, ri);
2191 ri.specificIndex = i;
2192 specificsPos++;
2193 }
2194 }
2195
2196 // Now we go through the remaining generic results and remove any
2197 // duplicate actions that are found here.
2198 N = results.size();
2199 for (int i=specificsPos; i<N-1; i++) {
2200 final ResolveInfo rii = results.get(i);
2201 if (rii.filter == null) {
2202 continue;
2203 }
2204
2205 // Iterate over all of the actions of this result's intent
2206 // filter... typically this should be just one.
2207 final Iterator<String> it = rii.filter.actionsIterator();
2208 if (it == null) {
2209 continue;
2210 }
2211 while (it.hasNext()) {
2212 final String action = it.next();
2213 if (resultsAction != null && resultsAction.equals(action)) {
2214 // If this action was explicitly requested, then don't
2215 // remove things that have it.
2216 continue;
2217 }
2218 for (int j=i+1; j<N; j++) {
2219 final ResolveInfo rij = results.get(j);
2220 if (rij.filter != null && rij.filter.hasAction(action)) {
2221 results.remove(j);
2222 if (Config.LOGV) Log.v(
2223 TAG, "Removing duplicate item from " + j
2224 + " due to action " + action + " at " + i);
2225 j--;
2226 N--;
2227 }
2228 }
2229 }
2230
2231 // If the caller didn't request filter information, drop it now
2232 // so we don't have to marshall/unmarshall it.
2233 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2234 rii.filter = null;
2235 }
2236 }
2237
2238 // Filter out the caller activity if so requested.
2239 if (caller != null) {
2240 N = results.size();
2241 for (int i=0; i<N; i++) {
2242 ActivityInfo ainfo = results.get(i).activityInfo;
2243 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2244 && caller.getClassName().equals(ainfo.name)) {
2245 results.remove(i);
2246 break;
2247 }
2248 }
2249 }
2250
2251 // If the caller didn't request filter information,
2252 // drop them now so we don't have to
2253 // marshall/unmarshall it.
2254 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2255 N = results.size();
2256 for (int i=0; i<N; i++) {
2257 results.get(i).filter = null;
2258 }
2259 }
2260
2261 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2262 return results;
2263 }
2264
2265 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2266 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002267 ComponentName comp = intent.getComponent();
2268 if (comp != null) {
2269 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2270 ActivityInfo ai = getReceiverInfo(comp, flags);
2271 if (ai != null) {
2272 ResolveInfo ri = new ResolveInfo();
2273 ri.activityInfo = ai;
2274 list.add(ri);
2275 }
2276 return list;
2277 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002280 String pkgName = intent.getPackage();
2281 if (pkgName == null) {
2282 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2283 resolvedType, flags);
2284 }
2285 PackageParser.Package pkg = mPackages.get(pkgName);
2286 if (pkg != null) {
2287 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2288 resolvedType, flags, pkg.receivers);
2289 }
2290 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 }
2292 }
2293
2294 public ResolveInfo resolveService(Intent intent, String resolvedType,
2295 int flags) {
2296 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2297 flags);
2298 if (query != null) {
2299 if (query.size() >= 1) {
2300 // If there is more than one service with the same priority,
2301 // just arbitrarily pick the first one.
2302 return query.get(0);
2303 }
2304 }
2305 return null;
2306 }
2307
2308 public List<ResolveInfo> queryIntentServices(Intent intent,
2309 String resolvedType, int flags) {
2310 ComponentName comp = intent.getComponent();
2311 if (comp != null) {
2312 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2313 ServiceInfo si = getServiceInfo(comp, flags);
2314 if (si != null) {
2315 ResolveInfo ri = new ResolveInfo();
2316 ri.serviceInfo = si;
2317 list.add(ri);
2318 }
2319 return list;
2320 }
2321
2322 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002323 String pkgName = intent.getPackage();
2324 if (pkgName == null) {
2325 return (List<ResolveInfo>)mServices.queryIntent(intent,
2326 resolvedType, flags);
2327 }
2328 PackageParser.Package pkg = mPackages.get(pkgName);
2329 if (pkg != null) {
2330 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2331 resolvedType, flags, pkg.services);
2332 }
2333 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 }
2335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002337 public List<PackageInfo> getInstalledPackages(int flags) {
2338 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2339
2340 synchronized (mPackages) {
2341 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2342 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2343 while (i.hasNext()) {
2344 final PackageSetting ps = i.next();
2345 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2346 if(psPkg != null) {
2347 finalList.add(psPkg);
2348 }
2349 }
2350 }
2351 else {
2352 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2353 while (i.hasNext()) {
2354 final PackageParser.Package p = i.next();
2355 if (p.applicationInfo != null) {
2356 PackageInfo pi = generatePackageInfo(p, flags);
2357 if(pi != null) {
2358 finalList.add(pi);
2359 }
2360 }
2361 }
2362 }
2363 }
2364 return finalList;
2365 }
2366
2367 public List<ApplicationInfo> getInstalledApplications(int flags) {
2368 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2369 synchronized(mPackages) {
2370 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2371 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2372 while (i.hasNext()) {
2373 final PackageSetting ps = i.next();
2374 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2375 if(ai != null) {
2376 finalList.add(ai);
2377 }
2378 }
2379 }
2380 else {
2381 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2382 while (i.hasNext()) {
2383 final PackageParser.Package p = i.next();
2384 if (p.applicationInfo != null) {
2385 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2386 if(ai != null) {
2387 finalList.add(ai);
2388 }
2389 }
2390 }
2391 }
2392 }
2393 return finalList;
2394 }
2395
2396 public List<ApplicationInfo> getPersistentApplications(int flags) {
2397 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2398
2399 synchronized (mPackages) {
2400 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2401 while (i.hasNext()) {
2402 PackageParser.Package p = i.next();
2403 if (p.applicationInfo != null
2404 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002405 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002406 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407 }
2408 }
2409 }
2410
2411 return finalList;
2412 }
2413
2414 public ProviderInfo resolveContentProvider(String name, int flags) {
2415 synchronized (mPackages) {
2416 final PackageParser.Provider provider = mProviders.get(name);
2417 return provider != null
2418 && mSettings.isEnabledLP(provider.info, flags)
2419 && (!mSafeMode || (provider.info.applicationInfo.flags
2420 &ApplicationInfo.FLAG_SYSTEM) != 0)
2421 ? PackageParser.generateProviderInfo(provider, flags)
2422 : null;
2423 }
2424 }
2425
Fred Quintana718d8a22009-04-29 17:53:20 -07002426 /**
2427 * @deprecated
2428 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 public void querySyncProviders(List outNames, List outInfo) {
2430 synchronized (mPackages) {
2431 Iterator<Map.Entry<String, PackageParser.Provider>> i
2432 = mProviders.entrySet().iterator();
2433
2434 while (i.hasNext()) {
2435 Map.Entry<String, PackageParser.Provider> entry = i.next();
2436 PackageParser.Provider p = entry.getValue();
2437
2438 if (p.syncable
2439 && (!mSafeMode || (p.info.applicationInfo.flags
2440 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2441 outNames.add(entry.getKey());
2442 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2443 }
2444 }
2445 }
2446 }
2447
2448 public List<ProviderInfo> queryContentProviders(String processName,
2449 int uid, int flags) {
2450 ArrayList<ProviderInfo> finalList = null;
2451
2452 synchronized (mPackages) {
2453 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2454 while (i.hasNext()) {
2455 PackageParser.Provider p = i.next();
2456 if (p.info.authority != null
2457 && (processName == null ||
2458 (p.info.processName.equals(processName)
2459 && p.info.applicationInfo.uid == uid))
2460 && mSettings.isEnabledLP(p.info, flags)
2461 && (!mSafeMode || (p.info.applicationInfo.flags
2462 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2463 if (finalList == null) {
2464 finalList = new ArrayList<ProviderInfo>(3);
2465 }
2466 finalList.add(PackageParser.generateProviderInfo(p,
2467 flags));
2468 }
2469 }
2470 }
2471
2472 if (finalList != null) {
2473 Collections.sort(finalList, mProviderInitOrderSorter);
2474 }
2475
2476 return finalList;
2477 }
2478
2479 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2480 int flags) {
2481 synchronized (mPackages) {
2482 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2483 return PackageParser.generateInstrumentationInfo(i, flags);
2484 }
2485 }
2486
2487 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2488 int flags) {
2489 ArrayList<InstrumentationInfo> finalList =
2490 new ArrayList<InstrumentationInfo>();
2491
2492 synchronized (mPackages) {
2493 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2494 while (i.hasNext()) {
2495 PackageParser.Instrumentation p = i.next();
2496 if (targetPackage == null
2497 || targetPackage.equals(p.info.targetPackage)) {
2498 finalList.add(PackageParser.generateInstrumentationInfo(p,
2499 flags));
2500 }
2501 }
2502 }
2503
2504 return finalList;
2505 }
2506
2507 private void scanDirLI(File dir, int flags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002509 if (files == null) {
2510 Log.d(TAG, "No files in app dir " + dir);
2511 return;
2512 }
2513
2514 Log.d(TAG, "Scanning app dir " + dir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515
2516 int i;
2517 for (i=0; i<files.length; i++) {
2518 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002519 if (!isPackageFilename(files[i])) {
2520 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002521 continue;
2522 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002523 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002525 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002526 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2527 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002528 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002529 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002530 file.delete();
2531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 }
2533 }
2534
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002535 private static File getSettingsProblemFile() {
2536 File dataDir = Environment.getDataDirectory();
2537 File systemDir = new File(dataDir, "system");
2538 File fname = new File(systemDir, "uiderrors.txt");
2539 return fname;
2540 }
2541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 private static void reportSettingsProblem(int priority, String msg) {
2543 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002544 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002545 FileOutputStream out = new FileOutputStream(fname, true);
2546 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002547 SimpleDateFormat formatter = new SimpleDateFormat();
2548 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2549 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 pw.close();
2551 FileUtils.setPermissions(
2552 fname.toString(),
2553 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2554 -1, -1);
2555 } catch (java.io.IOException e) {
2556 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002557 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 }
2559
2560 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2561 PackageParser.Package pkg, File srcFile, int parseFlags) {
2562 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002563 if (ps != null
2564 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002565 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002566 if (ps.signatures.mSignatures != null
2567 && ps.signatures.mSignatures.length != 0) {
2568 // Optimization: reuse the existing cached certificates
2569 // if the package appears to be unchanged.
2570 pkg.mSignatures = ps.signatures.mSignatures;
2571 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 }
Jeff Browne7600722010-04-07 18:28:23 -07002573
2574 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002575 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002576 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2577 }
2578
2579 if (!pp.collectCertificates(pkg, parseFlags)) {
2580 mLastScanError = pp.getParseError();
2581 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 }
2583 }
2584 return true;
2585 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 /*
2588 * Scan a package and return the newly parsed package.
2589 * Returns null in case of errors and the error code is stored in mLastScanError
2590 */
2591 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002592 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002593 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002594 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002596 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002599 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 if (pkg == null) {
2601 mLastScanError = pp.getParseError();
2602 return null;
2603 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002604 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 PackageSetting updatedPkg;
2606 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002607 // Look to see if we already know about this package.
2608 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002609 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002610 // This package has been renamed to its original name. Let's
2611 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002612 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002613 }
2614 // If there was no original package, see one for the real package name.
2615 if (ps == null) {
2616 ps = mSettings.peekPackageLP(pkg.packageName);
2617 }
2618 // Check to see if this package could be hiding/updating a system
2619 // package. Must look for it either under the original or real
2620 // package name depending on our state.
2621 updatedPkg = mSettings.mDisabledSysPackages.get(
2622 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002624 // First check if this is a system package that may involve an update
2625 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002626 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002627 // The path has changed from what was last scanned... check the
2628 // version of the new path against what we have stored to determine
2629 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002630 if (pkg.mVersionCode < ps.versionCode) {
2631 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002632 // Ignore entry. Skip it.
2633 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2634 + "ignored: updated version " + ps.versionCode
2635 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002636 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2637 return null;
2638 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002639 // The current app on the system partion is better than
2640 // what we have updated to on the data partition; switch
2641 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002642 // At this point, its safely assumed that package installation for
2643 // apps in system partition will go through. If not there won't be a working
2644 // version of the app
2645 synchronized (mPackages) {
2646 // Just remove the loaded entries from package lists.
2647 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002648 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002649 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002650 + "reverting from " + ps.codePathString
2651 + ": new version " + pkg.mVersionCode
2652 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002653 InstallArgs args = new FileInstallArgs(ps.codePathString,
2654 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002655 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002656 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 }
2659 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002660 if (updatedPkg != null) {
2661 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2662 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2663 }
2664 // Verify certificates against what was last scanned
2665 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002666 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002667 return null;
2668 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 // The apk is forward locked (not public) if its code and resources
2670 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002671 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002673 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002674 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002675
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002676 String codePath = null;
2677 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002678 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2679 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002680 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002681 } else {
2682 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002683 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002684 }
2685 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002686 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002687 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002688 codePath = pkg.mScanPath;
2689 // Set application objects path explicitly.
2690 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002692 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002693 }
2694
Kenny Root85387d72010-08-26 10:13:11 -07002695 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2696 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002697 pkg.mPath = pkg.mScanPath = destCodePath;
2698 pkg.applicationInfo.sourceDir = destCodePath;
2699 pkg.applicationInfo.publicSourceDir = destResPath;
2700 }
2701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 private static String fixProcessName(String defProcessName,
2703 String processName, int uid) {
2704 if (processName == null) {
2705 return defProcessName;
2706 }
2707 return processName;
2708 }
2709
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002710 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002711 PackageParser.Package pkg) {
2712 if (pkgSetting.signatures.mSignatures != null) {
2713 // Already existing package. Make sure signatures match
2714 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2715 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002716 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002717 + " signatures do not match the previously installed version; ignoring!");
2718 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 return false;
2720 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002721 }
2722 // Check for shared user signatures
2723 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2724 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2725 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2726 Slog.e(TAG, "Package " + pkg.packageName
2727 + " has no signatures that match those in shared user "
2728 + pkgSetting.sharedUser.name + "; ignoring!");
2729 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2730 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 }
2733 return true;
2734 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002735
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002736 public boolean performDexOpt(String packageName) {
2737 if (!mNoDexOpt) {
2738 return false;
2739 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002740
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002741 PackageParser.Package p;
2742 synchronized (mPackages) {
2743 p = mPackages.get(packageName);
2744 if (p == null || p.mDidDexOpt) {
2745 return false;
2746 }
2747 }
2748 synchronized (mInstallLock) {
2749 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2750 }
2751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002752
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002753 static final int DEX_OPT_SKIPPED = 0;
2754 static final int DEX_OPT_PERFORMED = 1;
2755 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002756
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002757 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2758 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002759 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002760 String path = pkg.mScanPath;
2761 int ret = 0;
2762 try {
2763 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002764 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002765 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002766 pkg.mDidDexOpt = true;
2767 performed = true;
2768 }
2769 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002770 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002771 ret = -1;
2772 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002773 Slog.w(TAG, "IOException reading apk: " + path, e);
2774 ret = -1;
2775 } catch (dalvik.system.StaleDexCacheError e) {
2776 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2777 ret = -1;
2778 } catch (Exception e) {
2779 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002780 ret = -1;
2781 }
2782 if (ret < 0) {
2783 //error from installer
2784 return DEX_OPT_FAILED;
2785 }
2786 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002787
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002788 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2789 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002790
2791 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2792 return Environment.isEncryptedFilesystemEnabled() &&
2793 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2794 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002795
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002796 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2797 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002798 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002799 + " to " + newPkg.packageName
2800 + ": old package not in system partition");
2801 return false;
2802 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002803 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002804 + " to " + newPkg.packageName
2805 + ": old package still exists");
2806 return false;
2807 }
2808 return true;
2809 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002810
2811 private File getDataPathForPackage(PackageParser.Package pkg) {
2812 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2813 File dataPath;
2814 if (useEncryptedFSDir) {
2815 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2816 } else {
2817 dataPath = new File(mAppDataDir, pkg.packageName);
2818 }
2819 return dataPath;
2820 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002821
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002822 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2823 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002824 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002825 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2826 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002827 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002828 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002829 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2830 return null;
2831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 mScanningPath = scanFile;
2833 if (pkg == null) {
2834 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2835 return null;
2836 }
2837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2839 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2840 }
2841
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002842 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 synchronized (mPackages) {
2844 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002845 Slog.w(TAG, "*************************************************");
2846 Slog.w(TAG, "Core android package being redefined. Skipping.");
2847 Slog.w(TAG, " file=" + mScanningPath);
2848 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002849 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2850 return null;
2851 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 // Set up information for our fall-back user intent resolution
2854 // activity.
2855 mPlatformPackage = pkg;
2856 pkg.mVersionCode = mSdkVersion;
2857 mAndroidApplication = pkg.applicationInfo;
2858 mResolveActivity.applicationInfo = mAndroidApplication;
2859 mResolveActivity.name = ResolverActivity.class.getName();
2860 mResolveActivity.packageName = mAndroidApplication.packageName;
2861 mResolveActivity.processName = mAndroidApplication.processName;
2862 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2863 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2864 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2865 mResolveActivity.exported = true;
2866 mResolveActivity.enabled = true;
2867 mResolveInfo.activityInfo = mResolveActivity;
2868 mResolveInfo.priority = 0;
2869 mResolveInfo.preferredOrder = 0;
2870 mResolveInfo.match = 0;
2871 mResolveComponentName = new ComponentName(
2872 mAndroidApplication.packageName, mResolveActivity.name);
2873 }
2874 }
2875
2876 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002877 TAG, "Scanning package " + pkg.packageName);
2878 if (mPackages.containsKey(pkg.packageName)
2879 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002880 Slog.w(TAG, "*************************************************");
2881 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002883 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2885 return null;
2886 }
2887
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002888 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002889 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2890 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 SharedUserSetting suid = null;
2893 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002894
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002895 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2896 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002897 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002898 pkg.mRealPackage = null;
2899 pkg.mAdoptPermissions = null;
2900 }
2901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002902 synchronized (mPackages) {
2903 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002904 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2905 if (mTmpSharedLibraries == null ||
2906 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2907 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2908 }
2909 int num = 0;
2910 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2911 for (int i=0; i<N; i++) {
2912 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002914 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002916 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2918 return null;
2919 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002920 mTmpSharedLibraries[num] = file;
2921 num++;
2922 }
2923 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2924 for (int i=0; i<N; i++) {
2925 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2926 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002927 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002928 + " desires unavailable shared library "
2929 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2930 } else {
2931 mTmpSharedLibraries[num] = file;
2932 num++;
2933 }
2934 }
2935 if (num > 0) {
2936 pkg.usesLibraryFiles = new String[num];
2937 System.arraycopy(mTmpSharedLibraries, 0,
2938 pkg.usesLibraryFiles, 0, num);
2939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002940
Dianne Hackborn49237342009-08-27 20:08:01 -07002941 if (pkg.reqFeatures != null) {
2942 N = pkg.reqFeatures.size();
2943 for (int i=0; i<N; i++) {
2944 FeatureInfo fi = pkg.reqFeatures.get(i);
2945 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2946 // Don't care.
2947 continue;
2948 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002949
Dianne Hackborn49237342009-08-27 20:08:01 -07002950 if (fi.name != null) {
2951 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002952 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002953 + " requires unavailable feature "
2954 + fi.name + "; failing!");
2955 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2956 return null;
2957 }
2958 }
2959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 }
2961 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002962
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002963 if (pkg.mSharedUserId != null) {
2964 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2965 pkg.applicationInfo.flags, true);
2966 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002967 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 + " for shared user failed");
2969 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2970 return null;
2971 }
2972 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2973 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2974 + suid.userId + "): packages=" + suid.packages);
2975 }
2976 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002977
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002978 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002979 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002980 Log.w(TAG, "WAITING FOR DEBUGGER");
2981 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002982 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2983 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002984 }
2985 }
2986
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002987 // Check if we are renaming from an original package name.
2988 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002989 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002990 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002991 // This package may need to be renamed to a previously
2992 // installed name. Let's check on that...
2993 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002994 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002995 // This package had originally been installed as the
2996 // original name, and we have already taken care of
2997 // transitioning to the new one. Just update the new
2998 // one to continue using the old name.
2999 realName = pkg.mRealPackage;
3000 if (!pkg.packageName.equals(renamed)) {
3001 // Callers into this function may have already taken
3002 // care of renaming the package; only do it here if
3003 // it is not already done.
3004 pkg.setPackageName(renamed);
3005 }
3006
Dianne Hackbornc1552392010-03-03 16:19:01 -08003007 } else {
3008 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
3009 if ((origPackage=mSettings.peekPackageLP(
3010 pkg.mOriginalPackages.get(i))) != null) {
3011 // We do have the package already installed under its
3012 // original name... should we use it?
3013 if (!verifyPackageUpdate(origPackage, pkg)) {
3014 // New package is not compatible with original.
3015 origPackage = null;
3016 continue;
3017 } else if (origPackage.sharedUser != null) {
3018 // Make sure uid is compatible between packages.
3019 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003020 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003021 + " to " + pkg.packageName + ": old uid "
3022 + origPackage.sharedUser.name
3023 + " differs from " + pkg.mSharedUserId);
3024 origPackage = null;
3025 continue;
3026 }
3027 } else {
3028 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3029 + pkg.packageName + " to old name " + origPackage.name);
3030 }
3031 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003032 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003033 }
3034 }
3035 }
3036
3037 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003038 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003039 + " was transferred to another, but its .apk remains");
3040 }
3041
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003042 // Just create the setting, don't add it yet. For already existing packages
3043 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003044 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003045 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3046 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003048 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3050 return null;
3051 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003052
3053 if (pkgSetting.origPackage != null) {
3054 // If we are first transitioning from an original package,
3055 // fix up the new package's name now. We need to do this after
3056 // looking up the package under its new name, so getPackageLP
3057 // can take care of fiddling things correctly.
3058 pkg.setPackageName(origPackage.name);
3059
3060 // File a report about this.
3061 String msg = "New package " + pkgSetting.realName
3062 + " renamed to replace old package " + pkgSetting.name;
3063 reportSettingsProblem(Log.WARN, msg);
3064
3065 // Make a note of it.
3066 mTransferedPackages.add(origPackage.name);
3067
3068 // No longer need to retain this.
3069 pkgSetting.origPackage = null;
3070 }
3071
3072 if (realName != null) {
3073 // Make a note of it.
3074 mTransferedPackages.add(pkg.packageName);
3075 }
3076
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003077 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3079 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 pkg.applicationInfo.uid = pkgSetting.userId;
3082 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003083
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003084 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003085 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 return null;
3087 }
3088 // The signature has changed, but this package is in the system
3089 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003090 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 // However... if this package is part of a shared user, but it
3092 // doesn't match the signature of the shared user, let's fail.
3093 // What this means is that you can't change the signatures
3094 // associated with an overall shared user, which doesn't seem all
3095 // that unreasonable.
3096 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003097 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3098 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3099 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3101 return null;
3102 }
3103 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003104 // File a report about this.
3105 String msg = "System package " + pkg.packageName
3106 + " signature changed; retaining data.";
3107 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003109
The Android Open Source Project10592532009-03-18 17:39:46 -07003110 // Verify that this new package doesn't have any content providers
3111 // that conflict with existing packages. Only do this if the
3112 // package isn't already installed, since we don't want to break
3113 // things that are installed.
3114 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3115 int N = pkg.providers.size();
3116 int i;
3117 for (i=0; i<N; i++) {
3118 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003119 if (p.info.authority != null) {
3120 String names[] = p.info.authority.split(";");
3121 for (int j = 0; j < names.length; j++) {
3122 if (mProviders.containsKey(names[j])) {
3123 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003124 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003125 " (in package " + pkg.applicationInfo.packageName +
3126 ") is already used by "
3127 + ((other != null && other.getComponentName() != null)
3128 ? other.getComponentName().getPackageName() : "?"));
3129 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3130 return null;
3131 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003132 }
3133 }
3134 }
3135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 }
3137
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003138 final String pkgName = pkg.packageName;
3139
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003140 if (pkg.mAdoptPermissions != null) {
3141 // This package wants to adopt ownership of permissions from
3142 // another package.
3143 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3144 String origName = pkg.mAdoptPermissions.get(i);
3145 PackageSetting orig = mSettings.peekPackageLP(origName);
3146 if (orig != null) {
3147 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003148 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003149 + origName + " to " + pkg.packageName);
3150 mSettings.transferPermissions(origName, pkg.packageName);
3151 }
3152 }
3153 }
3154 }
3155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003156 long scanFileTime = scanFile.lastModified();
3157 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003158 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 pkg.applicationInfo.processName = fixProcessName(
3160 pkg.applicationInfo.packageName,
3161 pkg.applicationInfo.processName,
3162 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163
3164 File dataPath;
3165 if (mPlatformPackage == pkg) {
3166 // The system package is special.
3167 dataPath = new File (Environment.getDataDirectory(), "system");
3168 pkg.applicationInfo.dataDir = dataPath.getPath();
3169 } else {
3170 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003171 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003172 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003173
3174 boolean uidError = false;
3175
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 if (dataPath.exists()) {
3177 mOutPermissions[1] = 0;
3178 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003179
3180 // If we have mismatched owners for the data path, we have a
3181 // problem (unless we're running in the simulator.)
3182 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183 boolean recovered = false;
3184 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3185 // If this is a system app, we can at least delete its
3186 // current data so the application will still work.
3187 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003188 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003189 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 // Old data gone!
3191 String msg = "System package " + pkg.packageName
3192 + " has changed from uid: "
3193 + mOutPermissions[1] + " to "
3194 + pkg.applicationInfo.uid + "; old data erased";
3195 reportSettingsProblem(Log.WARN, msg);
3196 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003199 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 pkg.applicationInfo.uid);
3201 if (ret == -1) {
3202 // Ack should not happen!
3203 msg = "System package " + pkg.packageName
3204 + " could not have data directory re-created after delete.";
3205 reportSettingsProblem(Log.WARN, msg);
3206 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3207 return null;
3208 }
3209 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003210 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 if (!recovered) {
3212 mHasSystemUidErrors = true;
3213 }
3214 }
3215 if (!recovered) {
3216 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3217 + pkg.applicationInfo.uid + "/fs_"
3218 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003219 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 String msg = "Package " + pkg.packageName
3221 + " has mismatched uid: "
3222 + mOutPermissions[1] + " on disk, "
3223 + pkg.applicationInfo.uid + " in settings";
3224 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003225 mSettings.mReadMessages.append(msg);
3226 mSettings.mReadMessages.append('\n');
3227 uidError = true;
3228 if (!pkgSetting.uidError) {
3229 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 }
3232 }
3233 }
3234 pkg.applicationInfo.dataDir = dataPath.getPath();
3235 } else {
3236 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3237 Log.v(TAG, "Want this data dir: " + dataPath);
3238 //invoke installer to do the actual installation
3239 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003240 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003241 pkg.applicationInfo.uid);
3242 if(ret < 0) {
3243 // Error from installer
3244 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3245 return null;
3246 }
3247 } else {
3248 dataPath.mkdirs();
3249 if (dataPath.exists()) {
3250 FileUtils.setPermissions(
3251 dataPath.toString(),
3252 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3253 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3254 }
3255 }
3256 if (dataPath.exists()) {
3257 pkg.applicationInfo.dataDir = dataPath.getPath();
3258 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003259 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 pkg.applicationInfo.dataDir = null;
3261 }
3262 }
Kenny Root85387d72010-08-26 10:13:11 -07003263
Kenny Root806cc132010-09-12 08:34:19 -07003264 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3265
Kenny Root85387d72010-08-26 10:13:11 -07003266 /*
3267 * Set the data dir to the default "/data/data/<package name>/lib"
3268 * if we got here without anyone telling us different (e.g., apps
3269 * stored on SD card have their native libraries stored in the ASEC
3270 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003271 *
3272 * This happens during an upgrade from a package settings file that
3273 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003274 */
Kenny Root806cc132010-09-12 08:34:19 -07003275 if (pkgSetting.nativeLibraryPathString == null && pkg.applicationInfo.dataDir != null) {
3276 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3277 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3278 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
Kenny Root85387d72010-08-26 10:13:11 -07003279 }
3280
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003281 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 }
3283
Kenny Root85387d72010-08-26 10:13:11 -07003284 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 if (mInstaller != null) {
3286 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003287 /* Note: We don't want to unpack the native binaries for
3288 * system applications, unless they have been updated
3289 * (the binaries are already under /system/lib).
3290 * Also, don't unpack libs for apps on the external card
3291 * since they should have their libraries in the ASEC
3292 * container already.
3293 *
3294 * In other words, we're going to unpack the binaries
3295 * only for non-system apps and system app upgrades.
3296 */
3297 if ((!isSystemApp(pkg) || isUpdatedSystemApp(pkg)) && !isExternal(pkg)) {
3298 Log.i(TAG, path + " changed; unpacking");
3299 File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root85387d72010-08-26 10:13:11 -07003300 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003302 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003303
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003304 if ((scanMode&SCAN_NO_DEX) == 0) {
3305 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3307 return null;
3308 }
3309 }
3310 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 if (mFactoryTest && pkg.requestedPermissions.contains(
3313 android.Manifest.permission.FACTORY_TEST)) {
3314 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3315 }
3316
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003317 // Request the ActivityManager to kill the process(only for existing packages)
3318 // so that we do not end up in a confused state while the user is still using the older
3319 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003320 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003321 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003322 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003323 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003326 // We don't expect installation to fail beyond this point,
3327 if ((scanMode&SCAN_MONITOR) != 0) {
3328 mAppDirs.put(pkg.mPath, pkg);
3329 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003331 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003333 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003334 // Make sure we don't accidentally delete its data.
3335 mSettings.mPackagesToBeCleaned.remove(pkgName);
3336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 int N = pkg.providers.size();
3338 StringBuilder r = null;
3339 int i;
3340 for (i=0; i<N; i++) {
3341 PackageParser.Provider p = pkg.providers.get(i);
3342 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3343 p.info.processName, pkg.applicationInfo.uid);
3344 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3345 p.info.name), p);
3346 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003347 if (p.info.authority != null) {
3348 String names[] = p.info.authority.split(";");
3349 p.info.authority = null;
3350 for (int j = 0; j < names.length; j++) {
3351 if (j == 1 && p.syncable) {
3352 // We only want the first authority for a provider to possibly be
3353 // syncable, so if we already added this provider using a different
3354 // authority clear the syncable flag. We copy the provider before
3355 // changing it because the mProviders object contains a reference
3356 // to a provider that we don't want to change.
3357 // Only do this for the second authority since the resulting provider
3358 // object can be the same for all future authorities for this provider.
3359 p = new PackageParser.Provider(p);
3360 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003362 if (!mProviders.containsKey(names[j])) {
3363 mProviders.put(names[j], p);
3364 if (p.info.authority == null) {
3365 p.info.authority = names[j];
3366 } else {
3367 p.info.authority = p.info.authority + ";" + names[j];
3368 }
3369 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3370 Log.d(TAG, "Registered content provider: " + names[j] +
3371 ", className = " + p.info.name +
3372 ", isSyncable = " + p.info.isSyncable);
3373 } else {
3374 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003375 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003376 " (in package " + pkg.applicationInfo.packageName +
3377 "): name already used by "
3378 + ((other != null && other.getComponentName() != null)
3379 ? other.getComponentName().getPackageName() : "?"));
3380 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 }
3382 }
3383 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3384 if (r == null) {
3385 r = new StringBuilder(256);
3386 } else {
3387 r.append(' ');
3388 }
3389 r.append(p.info.name);
3390 }
3391 }
3392 if (r != null) {
3393 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3394 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 N = pkg.services.size();
3397 r = null;
3398 for (i=0; i<N; i++) {
3399 PackageParser.Service s = pkg.services.get(i);
3400 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3401 s.info.processName, pkg.applicationInfo.uid);
3402 mServices.addService(s);
3403 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3404 if (r == null) {
3405 r = new StringBuilder(256);
3406 } else {
3407 r.append(' ');
3408 }
3409 r.append(s.info.name);
3410 }
3411 }
3412 if (r != null) {
3413 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3414 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 N = pkg.receivers.size();
3417 r = null;
3418 for (i=0; i<N; i++) {
3419 PackageParser.Activity a = pkg.receivers.get(i);
3420 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3421 a.info.processName, pkg.applicationInfo.uid);
3422 mReceivers.addActivity(a, "receiver");
3423 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3424 if (r == null) {
3425 r = new StringBuilder(256);
3426 } else {
3427 r.append(' ');
3428 }
3429 r.append(a.info.name);
3430 }
3431 }
3432 if (r != null) {
3433 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3434 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436 N = pkg.activities.size();
3437 r = null;
3438 for (i=0; i<N; i++) {
3439 PackageParser.Activity a = pkg.activities.get(i);
3440 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3441 a.info.processName, pkg.applicationInfo.uid);
3442 mActivities.addActivity(a, "activity");
3443 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3444 if (r == null) {
3445 r = new StringBuilder(256);
3446 } else {
3447 r.append(' ');
3448 }
3449 r.append(a.info.name);
3450 }
3451 }
3452 if (r != null) {
3453 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3454 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003456 N = pkg.permissionGroups.size();
3457 r = null;
3458 for (i=0; i<N; i++) {
3459 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3460 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3461 if (cur == null) {
3462 mPermissionGroups.put(pg.info.name, pg);
3463 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3464 if (r == null) {
3465 r = new StringBuilder(256);
3466 } else {
3467 r.append(' ');
3468 }
3469 r.append(pg.info.name);
3470 }
3471 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003472 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 + pg.info.packageName + " ignored: original from "
3474 + cur.info.packageName);
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("DUP:");
3482 r.append(pg.info.name);
3483 }
3484 }
3485 }
3486 if (r != null) {
3487 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3488 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003490 N = pkg.permissions.size();
3491 r = null;
3492 for (i=0; i<N; i++) {
3493 PackageParser.Permission p = pkg.permissions.get(i);
3494 HashMap<String, BasePermission> permissionMap =
3495 p.tree ? mSettings.mPermissionTrees
3496 : mSettings.mPermissions;
3497 p.group = mPermissionGroups.get(p.info.group);
3498 if (p.info.group == null || p.group != null) {
3499 BasePermission bp = permissionMap.get(p.info.name);
3500 if (bp == null) {
3501 bp = new BasePermission(p.info.name, p.info.packageName,
3502 BasePermission.TYPE_NORMAL);
3503 permissionMap.put(p.info.name, bp);
3504 }
3505 if (bp.perm == null) {
3506 if (bp.sourcePackage == null
3507 || bp.sourcePackage.equals(p.info.packageName)) {
3508 BasePermission tree = findPermissionTreeLP(p.info.name);
3509 if (tree == null
3510 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003511 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 bp.perm = p;
3513 bp.uid = pkg.applicationInfo.uid;
3514 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3515 if (r == null) {
3516 r = new StringBuilder(256);
3517 } else {
3518 r.append(' ');
3519 }
3520 r.append(p.info.name);
3521 }
3522 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003523 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 + p.info.packageName + " ignored: base tree "
3525 + tree.name + " is from package "
3526 + tree.sourcePackage);
3527 }
3528 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003529 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 + p.info.packageName + " ignored: original from "
3531 + bp.sourcePackage);
3532 }
3533 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3534 if (r == null) {
3535 r = new StringBuilder(256);
3536 } else {
3537 r.append(' ');
3538 }
3539 r.append("DUP:");
3540 r.append(p.info.name);
3541 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003542 if (bp.perm == p) {
3543 bp.protectionLevel = p.info.protectionLevel;
3544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003546 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 + p.info.packageName + " ignored: no group "
3548 + p.group);
3549 }
3550 }
3551 if (r != null) {
3552 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3553 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555 N = pkg.instrumentation.size();
3556 r = null;
3557 for (i=0; i<N; i++) {
3558 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3559 a.info.packageName = pkg.applicationInfo.packageName;
3560 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3561 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3562 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003563 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003564 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3566 if (r == null) {
3567 r = new StringBuilder(256);
3568 } else {
3569 r.append(' ');
3570 }
3571 r.append(a.info.name);
3572 }
3573 }
3574 if (r != null) {
3575 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3576 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003577
Dianne Hackborn854060af2009-07-09 18:14:31 -07003578 if (pkg.protectedBroadcasts != null) {
3579 N = pkg.protectedBroadcasts.size();
3580 for (i=0; i<N; i++) {
3581 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3582 }
3583 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003584
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585 pkgSetting.setTimeStamp(scanFileTime);
3586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 return pkg;
3589 }
3590
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003591 private void killApplication(String pkgName, int uid) {
3592 // Request the ActivityManager to kill the process(only for existing packages)
3593 // so that we do not end up in a confused state while the user is still using the older
3594 // version of the application while the new one gets installed.
3595 IActivityManager am = ActivityManagerNative.getDefault();
3596 if (am != null) {
3597 try {
3598 am.killApplicationWithUid(pkgName, uid);
3599 } catch (RemoteException e) {
3600 }
3601 }
3602 }
3603
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003604 // Return the path of the directory that will contain the native binaries
3605 // of a given installed package. This is relative to the data path.
3606 //
Kenny Root85387d72010-08-26 10:13:11 -07003607 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3608 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3609 if (nativeLibraryDir != null) {
3610 return new File(nativeLibraryDir);
3611 } else {
3612 // Fall back for old packages
3613 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3614 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003615 }
3616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3618 if (chatty && Config.LOGD) Log.d(
3619 TAG, "Removing package " + pkg.applicationInfo.packageName );
3620
3621 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 mPackages.remove(pkg.applicationInfo.packageName);
3625 if (pkg.mPath != null) {
3626 mAppDirs.remove(pkg.mPath);
3627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 PackageSetting ps = (PackageSetting)pkg.mExtras;
3630 if (ps != null && ps.sharedUser != null) {
3631 // XXX don't do this until the data is removed.
3632 if (false) {
3633 ps.sharedUser.packages.remove(ps);
3634 if (ps.sharedUser.packages.size() == 0) {
3635 // Remove.
3636 }
3637 }
3638 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 int N = pkg.providers.size();
3641 StringBuilder r = null;
3642 int i;
3643 for (i=0; i<N; i++) {
3644 PackageParser.Provider p = pkg.providers.get(i);
3645 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3646 p.info.name));
3647 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003649 /* The is another ContentProvider with this authority when
3650 * this app was installed so this authority is null,
3651 * Ignore it as we don't have to unregister the provider.
3652 */
3653 continue;
3654 }
3655 String names[] = p.info.authority.split(";");
3656 for (int j = 0; j < names.length; j++) {
3657 if (mProviders.get(names[j]) == p) {
3658 mProviders.remove(names[j]);
3659 if (chatty && Config.LOGD) Log.d(
3660 TAG, "Unregistered content provider: " + names[j] +
3661 ", className = " + p.info.name +
3662 ", isSyncable = " + p.info.isSyncable);
3663 }
3664 }
3665 if (chatty) {
3666 if (r == null) {
3667 r = new StringBuilder(256);
3668 } else {
3669 r.append(' ');
3670 }
3671 r.append(p.info.name);
3672 }
3673 }
3674 if (r != null) {
3675 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003678 N = pkg.services.size();
3679 r = null;
3680 for (i=0; i<N; i++) {
3681 PackageParser.Service s = pkg.services.get(i);
3682 mServices.removeService(s);
3683 if (chatty) {
3684 if (r == null) {
3685 r = new StringBuilder(256);
3686 } else {
3687 r.append(' ');
3688 }
3689 r.append(s.info.name);
3690 }
3691 }
3692 if (r != null) {
3693 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3694 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 N = pkg.receivers.size();
3697 r = null;
3698 for (i=0; i<N; i++) {
3699 PackageParser.Activity a = pkg.receivers.get(i);
3700 mReceivers.removeActivity(a, "receiver");
3701 if (chatty) {
3702 if (r == null) {
3703 r = new StringBuilder(256);
3704 } else {
3705 r.append(' ');
3706 }
3707 r.append(a.info.name);
3708 }
3709 }
3710 if (r != null) {
3711 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3712 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 N = pkg.activities.size();
3715 r = null;
3716 for (i=0; i<N; i++) {
3717 PackageParser.Activity a = pkg.activities.get(i);
3718 mActivities.removeActivity(a, "activity");
3719 if (chatty) {
3720 if (r == null) {
3721 r = new StringBuilder(256);
3722 } else {
3723 r.append(' ');
3724 }
3725 r.append(a.info.name);
3726 }
3727 }
3728 if (r != null) {
3729 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3730 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003731
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003732 N = pkg.permissions.size();
3733 r = null;
3734 for (i=0; i<N; i++) {
3735 PackageParser.Permission p = pkg.permissions.get(i);
3736 boolean tree = false;
3737 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3738 if (bp == null) {
3739 tree = true;
3740 bp = mSettings.mPermissionTrees.get(p.info.name);
3741 }
3742 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003743 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 if (chatty) {
3745 if (r == null) {
3746 r = new StringBuilder(256);
3747 } else {
3748 r.append(' ');
3749 }
3750 r.append(p.info.name);
3751 }
3752 }
3753 }
3754 if (r != null) {
3755 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 N = pkg.instrumentation.size();
3759 r = null;
3760 for (i=0; i<N; i++) {
3761 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003762 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 if (chatty) {
3764 if (r == null) {
3765 r = new StringBuilder(256);
3766 } else {
3767 r.append(' ');
3768 }
3769 r.append(a.info.name);
3770 }
3771 }
3772 if (r != null) {
3773 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3774 }
3775 }
3776 }
3777
3778 private static final boolean isPackageFilename(String name) {
3779 return name != null && name.endsWith(".apk");
3780 }
3781
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003782 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3783 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3784 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3785 return true;
3786 }
3787 }
3788 return false;
3789 }
3790
3791 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003792 PackageParser.Package pkgInfo, boolean grantPermissions,
3793 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003794 // Make sure there are no dangling permission trees.
3795 Iterator<BasePermission> it = mSettings.mPermissionTrees
3796 .values().iterator();
3797 while (it.hasNext()) {
3798 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003799 if (bp.packageSetting == null) {
3800 // We may not yet have parsed the package, so just see if
3801 // we still know about its settings.
3802 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3803 }
3804 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003805 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003806 + " from package " + bp.sourcePackage);
3807 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003808 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3809 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3810 Slog.i(TAG, "Removing old permission tree: " + bp.name
3811 + " from package " + bp.sourcePackage);
3812 grantPermissions = true;
3813 it.remove();
3814 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 }
3816 }
3817
3818 // Make sure all dynamic permissions have been assigned to a package,
3819 // and make sure there are no dangling permissions.
3820 it = mSettings.mPermissions.values().iterator();
3821 while (it.hasNext()) {
3822 BasePermission bp = it.next();
3823 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3824 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3825 + bp.name + " pkg=" + bp.sourcePackage
3826 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003827 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003828 BasePermission tree = findPermissionTreeLP(bp.name);
3829 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003830 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 bp.perm = new PackageParser.Permission(tree.perm.owner,
3832 new PermissionInfo(bp.pendingInfo));
3833 bp.perm.info.packageName = tree.perm.info.packageName;
3834 bp.perm.info.name = bp.name;
3835 bp.uid = tree.uid;
3836 }
3837 }
3838 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003839 if (bp.packageSetting == null) {
3840 // We may not yet have parsed the package, so just see if
3841 // we still know about its settings.
3842 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3843 }
3844 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003845 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003846 + " from package " + bp.sourcePackage);
3847 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003848 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3849 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3850 Slog.i(TAG, "Removing old permission: " + bp.name
3851 + " from package " + bp.sourcePackage);
3852 grantPermissions = true;
3853 it.remove();
3854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 }
3856 }
3857
3858 // Now update the permissions for all packages, in particular
3859 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003860 if (grantPermissions) {
3861 for (PackageParser.Package pkg : mPackages.values()) {
3862 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003863 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003864 }
3865 }
3866 }
3867
3868 if (pkgInfo != null) {
3869 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 }
3871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3874 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3875 if (ps == null) {
3876 return;
3877 }
3878 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003879 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 if (replace) {
3882 ps.permissionsFixed = false;
3883 if (gp == ps) {
3884 gp.grantedPermissions.clear();
3885 gp.gids = mGlobalGids;
3886 }
3887 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 if (gp.gids == null) {
3890 gp.gids = mGlobalGids;
3891 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003892
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 final int N = pkg.requestedPermissions.size();
3894 for (int i=0; i<N; i++) {
3895 String name = pkg.requestedPermissions.get(i);
3896 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003897 if (false) {
3898 if (gp != ps) {
3899 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003900 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 }
3902 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003903 if (bp != null && bp.packageSetting != null) {
3904 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003906 boolean allowedSig = false;
3907 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3908 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003910 } else if (bp.packageSetting == null) {
3911 // This permission is invalid; skip it.
3912 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003913 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3914 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3915 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003917 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003919 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003920 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 // For updated system applications, the signatureOrSystem permission
3922 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003923 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3925 if(sysPs.grantedPermissions.contains(perm)) {
3926 allowed = true;
3927 } else {
3928 allowed = false;
3929 }
3930 } else {
3931 allowed = true;
3932 }
3933 }
3934 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003935 if (allowed) {
3936 allowedSig = true;
3937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 } else {
3939 allowed = false;
3940 }
3941 if (false) {
3942 if (gp != ps) {
3943 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3944 }
3945 }
3946 if (allowed) {
3947 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3948 && ps.permissionsFixed) {
3949 // If this is an existing, non-system package, then
3950 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003951 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003953 // Except... if this is a permission that was added
3954 // to the platform (note: need to only do this when
3955 // updating the platform).
3956 final int NP = PackageParser.NEW_PERMISSIONS.length;
3957 for (int ip=0; ip<NP; ip++) {
3958 final PackageParser.NewPermissionInfo npi
3959 = PackageParser.NEW_PERMISSIONS[ip];
3960 if (npi.name.equals(perm)
3961 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3962 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003963 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003964 + pkg.packageName);
3965 break;
3966 }
3967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003968 }
3969 }
3970 if (allowed) {
3971 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003972 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 gp.grantedPermissions.add(perm);
3974 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003975 } else if (!ps.haveGids) {
3976 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 }
3978 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003979 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 + " to package " + pkg.packageName
3981 + " because it was previously installed without");
3982 }
3983 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003984 if (gp.grantedPermissions.remove(perm)) {
3985 changedPermission = true;
3986 gp.gids = removeInts(gp.gids, bp.gids);
3987 Slog.i(TAG, "Un-granting permission " + perm
3988 + " from package " + pkg.packageName
3989 + " (protectionLevel=" + bp.protectionLevel
3990 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3991 + ")");
3992 } else {
3993 Slog.w(TAG, "Not granting permission " + perm
3994 + " to package " + pkg.packageName
3995 + " (protectionLevel=" + bp.protectionLevel
3996 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3997 + ")");
3998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 }
4000 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004001 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004002 + " in package " + pkg.packageName);
4003 }
4004 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004005
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004006 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004007 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4008 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 // This is the first that we have heard about this package, so the
4010 // permissions we have now selected are fixed until explicitly
4011 // changed.
4012 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004014 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004015 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004016
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004017 private final class ActivityIntentResolver
4018 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004019 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004021 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 }
4023
Mihai Preda074edef2009-05-18 17:13:31 +02004024 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004026 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4028 }
4029
Mihai Predaeae850c2009-05-13 10:13:48 +02004030 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4031 ArrayList<PackageParser.Activity> packageActivities) {
4032 if (packageActivities == null) {
4033 return null;
4034 }
4035 mFlags = flags;
4036 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4037 int N = packageActivities.size();
4038 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4039 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004040
4041 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004042 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004043 intentFilters = packageActivities.get(i).intents;
4044 if (intentFilters != null && intentFilters.size() > 0) {
4045 listCut.add(intentFilters);
4046 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004047 }
4048 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4049 }
4050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004052 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 if (SHOW_INFO || Config.LOGV) Log.v(
4054 TAG, " " + type + " " +
4055 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4056 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4057 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004058 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004059 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4060 if (SHOW_INFO || Config.LOGV) {
4061 Log.v(TAG, " IntentFilter:");
4062 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4063 }
4064 if (!intent.debugCheck()) {
4065 Log.w(TAG, "==> For Activity " + a.info.name);
4066 }
4067 addFilter(intent);
4068 }
4069 }
4070
4071 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004072 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 if (SHOW_INFO || Config.LOGV) Log.v(
4074 TAG, " " + type + " " +
4075 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4076 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4077 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004078 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4080 if (SHOW_INFO || Config.LOGV) {
4081 Log.v(TAG, " IntentFilter:");
4082 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4083 }
4084 removeFilter(intent);
4085 }
4086 }
4087
4088 @Override
4089 protected boolean allowFilterResult(
4090 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4091 ActivityInfo filterAi = filter.activity.info;
4092 for (int i=dest.size()-1; i>=0; i--) {
4093 ActivityInfo destAi = dest.get(i).activityInfo;
4094 if (destAi.name == filterAi.name
4095 && destAi.packageName == filterAi.packageName) {
4096 return false;
4097 }
4098 }
4099 return true;
4100 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004103 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4104 return info.activity.owner.packageName;
4105 }
4106
4107 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4109 int match) {
4110 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4111 return null;
4112 }
4113 final PackageParser.Activity activity = info.activity;
4114 if (mSafeMode && (activity.info.applicationInfo.flags
4115 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4116 return null;
4117 }
4118 final ResolveInfo res = new ResolveInfo();
4119 res.activityInfo = PackageParser.generateActivityInfo(activity,
4120 mFlags);
4121 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4122 res.filter = info;
4123 }
4124 res.priority = info.getPriority();
4125 res.preferredOrder = activity.owner.mPreferredOrder;
4126 //System.out.println("Result: " + res.activityInfo.className +
4127 // " = " + res.priority);
4128 res.match = match;
4129 res.isDefault = info.hasDefault;
4130 res.labelRes = info.labelRes;
4131 res.nonLocalizedLabel = info.nonLocalizedLabel;
4132 res.icon = info.icon;
4133 return res;
4134 }
4135
4136 @Override
4137 protected void sortResults(List<ResolveInfo> results) {
4138 Collections.sort(results, mResolvePrioritySorter);
4139 }
4140
4141 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004142 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004144 out.print(prefix); out.print(
4145 Integer.toHexString(System.identityHashCode(filter.activity)));
4146 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004147 out.print(filter.activity.getComponentShortName());
4148 out.print(" filter ");
4149 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 }
4151
4152// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4153// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4154// final List<ResolveInfo> retList = Lists.newArrayList();
4155// while (i.hasNext()) {
4156// final ResolveInfo resolveInfo = i.next();
4157// if (isEnabledLP(resolveInfo.activityInfo)) {
4158// retList.add(resolveInfo);
4159// }
4160// }
4161// return retList;
4162// }
4163
4164 // Keys are String (activity class name), values are Activity.
4165 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4166 = new HashMap<ComponentName, PackageParser.Activity>();
4167 private int mFlags;
4168 }
4169
4170 private final class ServiceIntentResolver
4171 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004172 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004173 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004174 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 }
4176
Mihai Preda074edef2009-05-18 17:13:31 +02004177 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004179 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4181 }
4182
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004183 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4184 ArrayList<PackageParser.Service> packageServices) {
4185 if (packageServices == null) {
4186 return null;
4187 }
4188 mFlags = flags;
4189 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4190 int N = packageServices.size();
4191 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4192 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4193
4194 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4195 for (int i = 0; i < N; ++i) {
4196 intentFilters = packageServices.get(i).intents;
4197 if (intentFilters != null && intentFilters.size() > 0) {
4198 listCut.add(intentFilters);
4199 }
4200 }
4201 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4202 }
4203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004205 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 if (SHOW_INFO || Config.LOGV) Log.v(
4207 TAG, " " + (s.info.nonLocalizedLabel != null
4208 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4209 if (SHOW_INFO || Config.LOGV) Log.v(
4210 TAG, " Class=" + s.info.name);
4211 int NI = s.intents.size();
4212 int j;
4213 for (j=0; j<NI; j++) {
4214 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4215 if (SHOW_INFO || Config.LOGV) {
4216 Log.v(TAG, " IntentFilter:");
4217 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4218 }
4219 if (!intent.debugCheck()) {
4220 Log.w(TAG, "==> For Service " + s.info.name);
4221 }
4222 addFilter(intent);
4223 }
4224 }
4225
4226 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004227 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228 if (SHOW_INFO || Config.LOGV) Log.v(
4229 TAG, " " + (s.info.nonLocalizedLabel != null
4230 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4231 if (SHOW_INFO || Config.LOGV) Log.v(
4232 TAG, " Class=" + s.info.name);
4233 int NI = s.intents.size();
4234 int j;
4235 for (j=0; j<NI; j++) {
4236 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4237 if (SHOW_INFO || Config.LOGV) {
4238 Log.v(TAG, " IntentFilter:");
4239 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4240 }
4241 removeFilter(intent);
4242 }
4243 }
4244
4245 @Override
4246 protected boolean allowFilterResult(
4247 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4248 ServiceInfo filterSi = filter.service.info;
4249 for (int i=dest.size()-1; i>=0; i--) {
4250 ServiceInfo destAi = dest.get(i).serviceInfo;
4251 if (destAi.name == filterSi.name
4252 && destAi.packageName == filterSi.packageName) {
4253 return false;
4254 }
4255 }
4256 return true;
4257 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004260 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4261 return info.service.owner.packageName;
4262 }
4263
4264 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004265 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4266 int match) {
4267 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4268 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4269 return null;
4270 }
4271 final PackageParser.Service service = info.service;
4272 if (mSafeMode && (service.info.applicationInfo.flags
4273 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4274 return null;
4275 }
4276 final ResolveInfo res = new ResolveInfo();
4277 res.serviceInfo = PackageParser.generateServiceInfo(service,
4278 mFlags);
4279 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4280 res.filter = filter;
4281 }
4282 res.priority = info.getPriority();
4283 res.preferredOrder = service.owner.mPreferredOrder;
4284 //System.out.println("Result: " + res.activityInfo.className +
4285 // " = " + res.priority);
4286 res.match = match;
4287 res.isDefault = info.hasDefault;
4288 res.labelRes = info.labelRes;
4289 res.nonLocalizedLabel = info.nonLocalizedLabel;
4290 res.icon = info.icon;
4291 return res;
4292 }
4293
4294 @Override
4295 protected void sortResults(List<ResolveInfo> results) {
4296 Collections.sort(results, mResolvePrioritySorter);
4297 }
4298
4299 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004300 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004302 out.print(prefix); out.print(
4303 Integer.toHexString(System.identityHashCode(filter.service)));
4304 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004305 out.print(filter.service.getComponentShortName());
4306 out.print(" filter ");
4307 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 }
4309
4310// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4311// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4312// final List<ResolveInfo> retList = Lists.newArrayList();
4313// while (i.hasNext()) {
4314// final ResolveInfo resolveInfo = (ResolveInfo) i;
4315// if (isEnabledLP(resolveInfo.serviceInfo)) {
4316// retList.add(resolveInfo);
4317// }
4318// }
4319// return retList;
4320// }
4321
4322 // Keys are String (activity class name), values are Activity.
4323 private final HashMap<ComponentName, PackageParser.Service> mServices
4324 = new HashMap<ComponentName, PackageParser.Service>();
4325 private int mFlags;
4326 };
4327
4328 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4329 new Comparator<ResolveInfo>() {
4330 public int compare(ResolveInfo r1, ResolveInfo r2) {
4331 int v1 = r1.priority;
4332 int v2 = r2.priority;
4333 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4334 if (v1 != v2) {
4335 return (v1 > v2) ? -1 : 1;
4336 }
4337 v1 = r1.preferredOrder;
4338 v2 = r2.preferredOrder;
4339 if (v1 != v2) {
4340 return (v1 > v2) ? -1 : 1;
4341 }
4342 if (r1.isDefault != r2.isDefault) {
4343 return r1.isDefault ? -1 : 1;
4344 }
4345 v1 = r1.match;
4346 v2 = r2.match;
4347 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4348 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4349 }
4350 };
4351
4352 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4353 new Comparator<ProviderInfo>() {
4354 public int compare(ProviderInfo p1, ProviderInfo p2) {
4355 final int v1 = p1.initOrder;
4356 final int v2 = p2.initOrder;
4357 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4358 }
4359 };
4360
Kenny Root93565c4b2010-06-18 15:46:06 -07004361 private static final boolean DEBUG_OBB = false;
4362
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004363 private static final void sendPackageBroadcast(String action, String pkg,
4364 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004365 IActivityManager am = ActivityManagerNative.getDefault();
4366 if (am != null) {
4367 try {
4368 final Intent intent = new Intent(action,
4369 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4370 if (extras != null) {
4371 intent.putExtras(extras);
4372 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004373 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004374 am.broadcastIntent(null, intent, null, finishedReceiver,
4375 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 } catch (RemoteException ex) {
4377 }
4378 }
4379 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004380
4381 public String nextPackageToClean(String lastPackage) {
4382 synchronized (mPackages) {
4383 if (!mMediaMounted) {
4384 // If the external storage is no longer mounted at this point,
4385 // the caller may not have been able to delete all of this
4386 // packages files and can not delete any more. Bail.
4387 return null;
4388 }
4389 if (lastPackage != null) {
4390 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4391 }
4392 return mSettings.mPackagesToBeCleaned.size() > 0
4393 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4394 }
4395 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004397 void schedulePackageCleaning(String packageName) {
4398 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4399 }
4400
4401 void startCleaningPackages() {
4402 synchronized (mPackages) {
4403 if (!mMediaMounted) {
4404 return;
4405 }
4406 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4407 return;
4408 }
4409 }
4410 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4411 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4412 IActivityManager am = ActivityManagerNative.getDefault();
4413 if (am != null) {
4414 try {
4415 am.startService(null, intent, null);
4416 } catch (RemoteException e) {
4417 }
4418 }
4419 }
4420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004421 private final class AppDirObserver extends FileObserver {
4422 public AppDirObserver(String path, int mask, boolean isrom) {
4423 super(path, mask);
4424 mRootDir = path;
4425 mIsRom = isrom;
4426 }
4427
4428 public void onEvent(int event, String path) {
4429 String removedPackage = null;
4430 int removedUid = -1;
4431 String addedPackage = null;
4432 int addedUid = -1;
4433
4434 synchronized (mInstallLock) {
4435 String fullPathStr = null;
4436 File fullPath = null;
4437 if (path != null) {
4438 fullPath = new File(mRootDir, path);
4439 fullPathStr = fullPath.getPath();
4440 }
4441
4442 if (Config.LOGV) Log.v(
4443 TAG, "File " + fullPathStr + " changed: "
4444 + Integer.toHexString(event));
4445
4446 if (!isPackageFilename(path)) {
4447 if (Config.LOGV) Log.v(
4448 TAG, "Ignoring change of non-package file: " + fullPathStr);
4449 return;
4450 }
4451
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004452 // Ignore packages that are being installed or
4453 // have just been installed.
4454 if (ignoreCodePath(fullPathStr)) {
4455 return;
4456 }
4457 PackageParser.Package p = null;
4458 synchronized (mPackages) {
4459 p = mAppDirs.get(fullPathStr);
4460 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004462 if (p != null) {
4463 removePackageLI(p, true);
4464 removedPackage = p.applicationInfo.packageName;
4465 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004466 }
4467 }
4468
4469 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004470 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004471 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004472 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4473 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004474 PackageParser.PARSE_CHATTY |
4475 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004476 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 if (p != null) {
4478 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004479 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004480 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 }
4482 addedPackage = p.applicationInfo.packageName;
4483 addedUid = p.applicationInfo.uid;
4484 }
4485 }
4486 }
4487
4488 synchronized (mPackages) {
4489 mSettings.writeLP();
4490 }
4491 }
4492
4493 if (removedPackage != null) {
4494 Bundle extras = new Bundle(1);
4495 extras.putInt(Intent.EXTRA_UID, removedUid);
4496 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004497 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4498 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004499 }
4500 if (addedPackage != null) {
4501 Bundle extras = new Bundle(1);
4502 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004503 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4504 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 }
4506 }
4507
4508 private final String mRootDir;
4509 private final boolean mIsRom;
4510 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 /* Called when a downloaded package installation has been confirmed by the user */
4513 public void installPackage(
4514 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004515 installPackage(packageURI, observer, flags, null);
4516 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004517
Jacek Surazski65e13172009-04-28 15:26:38 +02004518 /* Called when a downloaded package installation has been confirmed by the user */
4519 public void installPackage(
4520 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4521 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004522 mContext.enforceCallingOrSelfPermission(
4523 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004524
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004525 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004526 msg.obj = new InstallParams(packageURI, observer, flags,
4527 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004528 mHandler.sendMessage(msg);
4529 }
4530
Christopher Tate1bb69062010-02-19 17:02:12 -08004531 public void finishPackageInstall(int token) {
4532 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4533 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4534 mHandler.sendMessage(msg);
4535 }
4536
Kenny Root93565c4b2010-06-18 15:46:06 -07004537 public void setPackageObbPath(String packageName, String path) {
4538 if (DEBUG_OBB)
4539 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4540 PackageSetting pkgSetting;
4541 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004542 final int permission = mContext.checkCallingPermission(
4543 android.Manifest.permission.INSTALL_PACKAGES);
4544 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004545 synchronized (mPackages) {
4546 pkgSetting = mSettings.mPackages.get(packageName);
4547 if (pkgSetting == null) {
4548 throw new IllegalArgumentException("Unknown package: " + packageName);
4549 }
4550 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4551 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4552 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4553 + pkgSetting.userId);
4554 }
4555 pkgSetting.obbPathString = path;
4556 mSettings.writeLP();
4557 }
4558 }
4559
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004560 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 // Queue up an async operation since the package installation may take a little while.
4562 mHandler.post(new Runnable() {
4563 public void run() {
4564 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004565 // Result object to be returned
4566 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004567 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004568 res.uid = -1;
4569 res.pkg = null;
4570 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004571 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004572 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004573 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004574 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004575 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004576 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004577 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004578
4579 // A restore should be performed at this point if (a) the install
4580 // succeeded, (b) the operation is not an update, and (c) the new
4581 // package has a backupAgent defined.
4582 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004583 boolean doRestore = (!update
4584 && res.pkg != null
4585 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004586
4587 // Set up the post-install work request bookkeeping. This will be used
4588 // and cleaned up by the post-install event handling regardless of whether
4589 // there's a restore pass performed. Token values are >= 1.
4590 int token;
4591 if (mNextInstallToken < 0) mNextInstallToken = 1;
4592 token = mNextInstallToken++;
4593
4594 PostInstallData data = new PostInstallData(args, res);
4595 mRunningInstalls.put(token, data);
4596 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4597
4598 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4599 // Pass responsibility to the Backup Manager. It will perform a
4600 // restore if appropriate, then pass responsibility back to the
4601 // Package Manager to run the post-install observer callbacks
4602 // and broadcasts.
4603 IBackupManager bm = IBackupManager.Stub.asInterface(
4604 ServiceManager.getService(Context.BACKUP_SERVICE));
4605 if (bm != null) {
4606 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4607 + " to BM for possible restore");
4608 try {
4609 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4610 } catch (RemoteException e) {
4611 // can't happen; the backup manager is local
4612 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004613 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004614 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004615 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004616 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004617 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004618 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004620 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004621
4622 if (!doRestore) {
4623 // No restore possible, or the Backup Manager was mysteriously not
4624 // available -- just fire the post-install work request directly.
4625 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4626 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4627 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004629 }
4630 });
4631 }
4632
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004633 abstract class HandlerParams {
4634 final static int MAX_RETRIES = 4;
4635 int retry = 0;
4636 final void startCopy() {
4637 try {
4638 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4639 retry++;
4640 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004641 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004642 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4643 handleServiceError();
4644 return;
4645 } else {
4646 handleStartCopy();
4647 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4648 mHandler.sendEmptyMessage(MCS_UNBIND);
4649 }
4650 } catch (RemoteException e) {
4651 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4652 mHandler.sendEmptyMessage(MCS_RECONNECT);
4653 }
4654 handleReturnCode();
4655 }
4656
4657 final void serviceError() {
4658 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4659 handleServiceError();
4660 handleReturnCode();
4661 }
4662 abstract void handleStartCopy() throws RemoteException;
4663 abstract void handleServiceError();
4664 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004665 }
4666
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004667 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004668 final IPackageInstallObserver observer;
4669 int flags;
4670 final Uri packageURI;
4671 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004672 private InstallArgs mArgs;
4673 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004674 InstallParams(Uri packageURI,
4675 IPackageInstallObserver observer, int flags,
4676 String installerPackageName) {
4677 this.packageURI = packageURI;
4678 this.flags = flags;
4679 this.observer = observer;
4680 this.installerPackageName = installerPackageName;
4681 }
4682
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004683 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4684 String packageName = pkgLite.packageName;
4685 int installLocation = pkgLite.installLocation;
4686 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4687 synchronized (mPackages) {
4688 PackageParser.Package pkg = mPackages.get(packageName);
4689 if (pkg != null) {
4690 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4691 // Check for updated system application.
4692 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4693 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004694 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004695 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4696 }
4697 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4698 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004699 if (onSd) {
4700 // Install flag overrides everything.
4701 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4702 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004703 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004704 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4705 // Application explicitly specified internal.
4706 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4707 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4708 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004709 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004710 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004711 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004712 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4713 }
4714 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004715 }
4716 }
4717 } else {
4718 // Invalid install. Return error code
4719 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4720 }
4721 }
4722 }
4723 // All the special cases have been taken care of.
4724 // Return result based on recommended install location.
4725 if (onSd) {
4726 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4727 }
4728 return pkgLite.recommendedInstallLocation;
4729 }
4730
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004731 /*
4732 * Invoke remote method to get package information and install
4733 * location values. Override install location based on default
4734 * policy if needed and then create install arguments based
4735 * on the install location.
4736 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004737 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004738 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004739 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4740 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004741 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4742 if (onInt && onSd) {
4743 // Check if both bits are set.
4744 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4745 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4746 } else if (fwdLocked && onSd) {
4747 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004748 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004749 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004750 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004751 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004752 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004753 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004754 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4755 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4756 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4757 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4758 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004759 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4760 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4761 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004762 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4763 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004764 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004765 // Override with defaults if needed.
4766 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004767 if (!onSd && !onInt) {
4768 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004769 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4770 // Set the flag to install on external media.
4771 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004772 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004773 } else {
4774 // Make sure the flag for installing on external
4775 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004776 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004777 flags &= ~PackageManager.INSTALL_EXTERNAL;
4778 }
4779 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004780 }
4781 }
4782 // Create the file args now.
4783 mArgs = createInstallArgs(this);
4784 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4785 // Create copy only if we are not in an erroneous state.
4786 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004787 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004788 }
4789 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004790 }
4791
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004792 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004793 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004794 // If mArgs is null, then MCS couldn't be reached. When it
4795 // reconnects, it will try again to install. At that point, this
4796 // will succeed.
4797 if (mArgs != null) {
4798 processPendingInstall(mArgs, mRet);
4799 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004800 }
4801
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004802 @Override
4803 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004804 mArgs = createInstallArgs(this);
4805 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004806 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004807 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004808
4809 /*
4810 * Utility class used in movePackage api.
4811 * srcArgs and targetArgs are not set for invalid flags and make
4812 * sure to do null checks when invoking methods on them.
4813 * We probably want to return ErrorPrams for both failed installs
4814 * and moves.
4815 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004816 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004817 final IPackageMoveObserver observer;
4818 final int flags;
4819 final String packageName;
4820 final InstallArgs srcArgs;
4821 final InstallArgs targetArgs;
4822 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004823
4824 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4825 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004826 this.srcArgs = srcArgs;
4827 this.observer = observer;
4828 this.flags = flags;
4829 this.packageName = packageName;
4830 if (srcArgs != null) {
4831 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004832 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004833 } else {
4834 targetArgs = null;
4835 }
4836 }
4837
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004838 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004839 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4840 // Check for storage space on target medium
4841 if (!targetArgs.checkFreeStorage(mContainerService)) {
4842 Log.w(TAG, "Insufficient storage to install");
4843 return;
4844 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004845 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004846 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004847 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004848 if (DEBUG_SD_INSTALL) {
4849 StringBuilder builder = new StringBuilder();
4850 if (srcArgs != null) {
4851 builder.append("src: ");
4852 builder.append(srcArgs.getCodePath());
4853 }
4854 if (targetArgs != null) {
4855 builder.append(" target : ");
4856 builder.append(targetArgs.getCodePath());
4857 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004858 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004859 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004860 }
4861
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004862 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004863 void handleReturnCode() {
4864 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004865 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4866 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4867 currentStatus = PackageManager.MOVE_SUCCEEDED;
4868 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4869 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4870 }
4871 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004872 }
4873
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004874 @Override
4875 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004876 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004877 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004878 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004879
4880 private InstallArgs createInstallArgs(InstallParams params) {
4881 if (installOnSd(params.flags)) {
4882 return new SdInstallArgs(params);
4883 } else {
4884 return new FileInstallArgs(params);
4885 }
4886 }
4887
Kenny Root85387d72010-08-26 10:13:11 -07004888 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4889 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004890 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004891 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004892 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004893 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004894 }
4895 }
4896
Kenny Root85387d72010-08-26 10:13:11 -07004897 // Used by package mover
4898 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004899 if (installOnSd(flags)) {
4900 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4901 return new SdInstallArgs(packageURI, cid);
4902 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004903 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004904 }
4905 }
4906
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004907 static abstract class InstallArgs {
4908 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004909 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004910 final int flags;
4911 final Uri packageURI;
4912 final String installerPackageName;
4913
4914 InstallArgs(Uri packageURI,
4915 IPackageInstallObserver observer, int flags,
4916 String installerPackageName) {
4917 this.packageURI = packageURI;
4918 this.flags = flags;
4919 this.observer = observer;
4920 this.installerPackageName = installerPackageName;
4921 }
4922
4923 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004924 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004925 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004926 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004927 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004928 abstract String getCodePath();
4929 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004930 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004931 // Need installer lock especially for dex file removal.
4932 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004933 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004934 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004935 }
4936
4937 class FileInstallArgs extends InstallArgs {
4938 File installDir;
4939 String codeFileName;
4940 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004941 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004942 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004943
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004944 FileInstallArgs(InstallParams params) {
4945 super(params.packageURI, params.observer,
4946 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004947 }
4948
Kenny Root85387d72010-08-26 10:13:11 -07004949 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004950 super(null, null, 0, null);
4951 File codeFile = new File(fullCodePath);
4952 installDir = codeFile.getParentFile();
4953 codeFileName = fullCodePath;
4954 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004955 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004956 }
4957
Kenny Root85387d72010-08-26 10:13:11 -07004958 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004959 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004960 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 String apkName = getNextCodePath(null, pkgName, ".apk");
4962 codeFileName = new File(installDir, apkName + ".apk").getPath();
4963 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004964 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004965 }
4966
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004967 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4968 return imcs.checkFreeStorage(false, packageURI);
4969 }
4970
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004971 String getCodePath() {
4972 return codeFileName;
4973 }
4974
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004975 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004976 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004977 codeFileName = createTempPackageFile(installDir).getPath();
4978 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004979 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004980 }
4981
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004982 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004983 if (temp) {
4984 // Generate temp file name
4985 createCopyFile();
4986 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004987 // Get a ParcelFileDescriptor to write to the output file
4988 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004989 if (!created) {
4990 try {
4991 codeFile.createNewFile();
4992 // Set permissions
4993 if (!setPermissions()) {
4994 // Failed setting permissions.
4995 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4996 }
4997 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004998 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004999 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5000 }
5001 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005002 ParcelFileDescriptor out = null;
5003 try {
Kenny Root85387d72010-08-26 10:13:11 -07005004 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005005 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005006 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005007 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5008 }
5009 // Copy the resource now
5010 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5011 try {
5012 if (imcs.copyResource(packageURI, out)) {
5013 ret = PackageManager.INSTALL_SUCCEEDED;
5014 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005015 } finally {
5016 try { if (out != null) out.close(); } catch (IOException e) {}
5017 }
Kenny Root85387d72010-08-26 10:13:11 -07005018
5019 if (!temp) {
5020 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5021 }
5022
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005023 return ret;
5024 }
5025
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005026 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005027 if (status != PackageManager.INSTALL_SUCCEEDED) {
5028 cleanUp();
5029 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005030 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005031 }
5032
5033 boolean doRename(int status, final String pkgName, String oldCodePath) {
5034 if (status != PackageManager.INSTALL_SUCCEEDED) {
5035 cleanUp();
5036 return false;
5037 } else {
5038 // Rename based on packageName
5039 File codeFile = new File(getCodePath());
5040 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5041 File desFile = new File(installDir, apkName + ".apk");
5042 if (!codeFile.renameTo(desFile)) {
5043 return false;
5044 }
5045 // Reset paths since the file has been renamed.
5046 codeFileName = desFile.getPath();
5047 resourceFileName = getResourcePathFromCodePath();
5048 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005049 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005050 // Failed setting permissions.
5051 return false;
5052 }
5053 return true;
5054 }
5055 }
5056
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005057 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005058 if (status != PackageManager.INSTALL_SUCCEEDED) {
5059 cleanUp();
5060 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005061 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005062 }
5063
5064 String getResourcePath() {
5065 return resourceFileName;
5066 }
5067
5068 String getResourcePathFromCodePath() {
5069 String codePath = getCodePath();
5070 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5071 String apkNameOnly = getApkName(codePath);
5072 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5073 } else {
5074 return codePath;
5075 }
5076 }
5077
Kenny Root85387d72010-08-26 10:13:11 -07005078 @Override
5079 String getNativeLibraryPath() {
5080 return libraryPath;
5081 }
5082
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005083 private boolean cleanUp() {
5084 boolean ret = true;
5085 String sourceDir = getCodePath();
5086 String publicSourceDir = getResourcePath();
5087 if (sourceDir != null) {
5088 File sourceFile = new File(sourceDir);
5089 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005090 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005091 ret = false;
5092 }
5093 // Delete application's code and resources
5094 sourceFile.delete();
5095 }
5096 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5097 final File publicSourceFile = new File(publicSourceDir);
5098 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005099 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005100 }
5101 if (publicSourceFile.exists()) {
5102 publicSourceFile.delete();
5103 }
5104 }
5105 return ret;
5106 }
5107
5108 void cleanUpResourcesLI() {
5109 String sourceDir = getCodePath();
5110 if (cleanUp() && mInstaller != null) {
5111 int retCode = mInstaller.rmdex(sourceDir);
5112 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005113 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005114 + " at location "
5115 + sourceDir + ", retcode=" + retCode);
5116 // we don't consider this to be a failure of the core package deletion
5117 }
5118 }
Kenny Root85387d72010-08-26 10:13:11 -07005119 if (libraryPath != null) {
Kenny Root8f7cc022010-09-12 09:04:56 -07005120 NativeLibraryHelper.removeNativeBinariesLI(libraryPath);
Kenny Root85387d72010-08-26 10:13:11 -07005121 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005122 }
5123
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005124 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005125 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005126 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005127 final int filePermissions =
5128 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5129 |FileUtils.S_IROTH;
5130 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5131 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005132 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005133 getCodePath()
5134 + ". The return code was: " + retCode);
5135 // TODO Define new internal error
5136 return false;
5137 }
5138 return true;
5139 }
5140 return true;
5141 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005142
5143 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005144 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005145 cleanUpResourcesLI();
5146 return true;
5147 }
Kenny Root85387d72010-08-26 10:13:11 -07005148
5149 private boolean isFwdLocked() {
5150 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5151 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005152 }
5153
5154 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005155 static final String RES_FILE_NAME = "pkg.apk";
5156
Kenny Root85387d72010-08-26 10:13:11 -07005157 String cid;
5158 String packagePath;
5159 String libraryPath;
5160
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005161 SdInstallArgs(InstallParams params) {
5162 super(params.packageURI, params.observer,
5163 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005164 }
5165
Kenny Root85387d72010-08-26 10:13:11 -07005166 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005167 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005168 // Extract cid from fullCodePath
5169 int eidx = fullCodePath.lastIndexOf("/");
5170 String subStr1 = fullCodePath.substring(0, eidx);
5171 int sidx = subStr1.lastIndexOf("/");
5172 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005173 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005174 }
5175
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005176 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005177 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5178 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005179 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005180 }
5181
5182 SdInstallArgs(Uri packageURI, String cid) {
5183 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005184 this.cid = cid;
5185 }
5186
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005187 void createCopyFile() {
5188 cid = getTempContainerId();
5189 }
5190
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005191 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5192 return imcs.checkFreeStorage(true, packageURI);
5193 }
5194
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005195 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005196 if (temp) {
5197 createCopyFile();
5198 }
Kenny Root85387d72010-08-26 10:13:11 -07005199 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005200 packageURI, cid,
5201 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005202 if (newCachePath != null) {
5203 setCachePath(newCachePath);
5204 return PackageManager.INSTALL_SUCCEEDED;
5205 } else {
5206 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5207 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005208 }
5209
5210 @Override
5211 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005212 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005213 }
5214
5215 @Override
5216 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005217 return packagePath;
5218 }
5219
5220 @Override
5221 String getNativeLibraryPath() {
5222 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005223 }
5224
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005225 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005226 if (status != PackageManager.INSTALL_SUCCEEDED) {
5227 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005228 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005229 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005230 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005231 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005232 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5233 Process.SYSTEM_UID);
5234 if (newCachePath != null) {
5235 setCachePath(newCachePath);
5236 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005237 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5238 }
5239 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005240 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005241 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005242 }
5243
5244 boolean doRename(int status, final String pkgName,
5245 String oldCodePath) {
5246 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005247 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005248 if (PackageHelper.isContainerMounted(cid)) {
5249 // Unmount the container
5250 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005251 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005252 return false;
5253 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005254 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005255 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005256 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5257 " which might be stale. Will try to clean up.");
5258 // Clean up the stale container and proceed to recreate.
5259 if (!PackageHelper.destroySdDir(newCacheId)) {
5260 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5261 return false;
5262 }
5263 // Successfully cleaned up stale container. Try to rename again.
5264 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5265 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5266 + " inspite of cleaning it up.");
5267 return false;
5268 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005269 }
5270 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005271 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005272 newCachePath = PackageHelper.mountSdDir(newCacheId,
5273 getEncryptKey(), Process.SYSTEM_UID);
5274 } else {
5275 newCachePath = PackageHelper.getSdDir(newCacheId);
5276 }
5277 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005278 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005279 return false;
5280 }
5281 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005282 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005283 " at new path: " + newCachePath);
5284 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005285 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005286 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005287 }
5288
Kenny Root85387d72010-08-26 10:13:11 -07005289 private void setCachePath(String newCachePath) {
5290 File cachePath = new File(newCachePath);
5291 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5292 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5293 }
5294
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005295 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005296 if (status != PackageManager.INSTALL_SUCCEEDED) {
5297 cleanUp();
5298 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005299 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005300 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005301 PackageHelper.mountSdDir(cid,
5302 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005303 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005304 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005305 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005306 }
5307
5308 private void cleanUp() {
5309 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005310 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 }
5312
5313 void cleanUpResourcesLI() {
5314 String sourceFile = getCodePath();
5315 // Remove dex file
5316 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005317 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005318 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005319 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005320 + " at location "
5321 + sourceFile.toString() + ", retcode=" + retCode);
5322 // we don't consider this to be a failure of the core package deletion
5323 }
5324 }
5325 cleanUp();
5326 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005327
5328 boolean matchContainer(String app) {
5329 if (cid.startsWith(app)) {
5330 return true;
5331 }
5332 return false;
5333 }
5334
5335 String getPackageName() {
5336 int idx = cid.lastIndexOf("-");
5337 if (idx == -1) {
5338 return cid;
5339 }
5340 return cid.substring(0, idx);
5341 }
5342
5343 boolean doPostDeleteLI(boolean delete) {
5344 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005345 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005346 if (mounted) {
5347 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005348 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005349 }
5350 if (ret && delete) {
5351 cleanUpResourcesLI();
5352 }
5353 return ret;
5354 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005355 };
5356
5357 // Utility method used to create code paths based on package name and available index.
5358 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5359 String idxStr = "";
5360 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005361 // Fall back to default value of idx=1 if prefix is not
5362 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005363 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005364 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005365 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005366 if (subStr.endsWith(suffix)) {
5367 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005368 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005369 // If oldCodePath already contains prefix find out the
5370 // ending index to either increment or decrement.
5371 int sidx = subStr.lastIndexOf(prefix);
5372 if (sidx != -1) {
5373 subStr = subStr.substring(sidx + prefix.length());
5374 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005375 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5376 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005377 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005378 try {
5379 idx = Integer.parseInt(subStr);
5380 if (idx <= 1) {
5381 idx++;
5382 } else {
5383 idx--;
5384 }
5385 } catch(NumberFormatException e) {
5386 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005387 }
5388 }
5389 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005390 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005391 return prefix + idxStr;
5392 }
5393
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005394 // Utility method used to ignore ADD/REMOVE events
5395 // by directory observer.
5396 private static boolean ignoreCodePath(String fullPathStr) {
5397 String apkName = getApkName(fullPathStr);
5398 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5399 if (idx != -1 && ((idx+1) < apkName.length())) {
5400 // Make sure the package ends with a numeral
5401 String version = apkName.substring(idx+1);
5402 try {
5403 Integer.parseInt(version);
5404 return true;
5405 } catch (NumberFormatException e) {}
5406 }
5407 return false;
5408 }
5409
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005410 // Utility method that returns the relative package path with respect
5411 // to the installation directory. Like say for /data/data/com.test-1.apk
5412 // string com.test-1 is returned.
5413 static String getApkName(String codePath) {
5414 if (codePath == null) {
5415 return null;
5416 }
5417 int sidx = codePath.lastIndexOf("/");
5418 int eidx = codePath.lastIndexOf(".");
5419 if (eidx == -1) {
5420 eidx = codePath.length();
5421 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005422 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005423 return null;
5424 }
5425 return codePath.substring(sidx+1, eidx);
5426 }
5427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005428 class PackageInstalledInfo {
5429 String name;
5430 int uid;
5431 PackageParser.Package pkg;
5432 int returnCode;
5433 PackageRemovedInfo removedInfo;
5434 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005435
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005436 /*
5437 * Install a non-existing package.
5438 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005439 private void installNewPackageLI(PackageParser.Package pkg,
5440 int parseFlags,
5441 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005442 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005444 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005445
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005446 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 res.name = pkgName;
5448 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005449 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5450 // A package with the same name is already installed, though
5451 // it has been renamed to an older name. The package we
5452 // are trying to install should be installed as an update to
5453 // the existing one, but that has not been requested, so bail.
5454 Slog.w(TAG, "Attempt to re-install " + pkgName
5455 + " without first uninstalling package running as "
5456 + mSettings.mRenamedPackages.get(pkgName));
5457 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5458 return;
5459 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005460 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005461 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005462 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005463 + " without first uninstalling.");
5464 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5465 return;
5466 }
5467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005469 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005471 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5473 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5474 }
5475 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005476 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005477 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005478 res);
5479 // delete the partially installed application. the data directory will have to be
5480 // restored if it was already existing
5481 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5482 // remove package from internal structures. Note that we want deletePackageX to
5483 // delete the package data and cache directories that it created in
5484 // scanPackageLocked, unless those directories existed before we even tried to
5485 // install.
5486 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005487 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005488 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5489 res.removedInfo);
5490 }
5491 }
5492 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005493
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005494 private void replacePackageLI(PackageParser.Package pkg,
5495 int parseFlags,
5496 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005497 String installerPackageName, PackageInstalledInfo res) {
5498
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005499 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005500 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 // First find the old package info and check signatures
5502 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005503 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005504 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005505 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5507 return;
5508 }
5509 }
Kenny Root85387d72010-08-26 10:13:11 -07005510 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005511 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005512 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005513 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005514 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 }
5516 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005519 PackageParser.Package pkg,
5520 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005521 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 PackageParser.Package newPackage = null;
5523 String pkgName = deletedPackage.packageName;
5524 boolean deletedPkg = true;
5525 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005526
Jacek Surazski65e13172009-04-28 15:26:38 +02005527 String oldInstallerPackageName = null;
5528 synchronized (mPackages) {
5529 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005532 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005533 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 res.removedInfo)) {
5535 // If the existing package was'nt successfully deleted
5536 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5537 deletedPkg = false;
5538 } else {
5539 // Successfully deleted the old package. Now proceed with re-installation
5540 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005541 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005543 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005544 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5545 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005546 }
5547 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005548 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005549 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005550 res);
5551 updatedSettings = true;
5552 }
5553 }
5554
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005555 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 // remove package from internal structures. Note that we want deletePackageX to
5557 // delete the package data and cache directories that it created in
5558 // scanPackageLocked, unless those directories existed before we even tried to
5559 // install.
5560 if(updatedSettings) {
5561 deletePackageLI(
5562 pkgName, true,
5563 PackageManager.DONT_DELETE_DATA,
5564 res.removedInfo);
5565 }
5566 // Since we failed to install the new package we need to restore the old
5567 // package that we deleted.
5568 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005569 File restoreFile = new File(deletedPackage.mPath);
5570 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005571 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005572 return;
5573 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005574 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005575 boolean oldOnSd = isExternal(deletedPackage);
5576 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5577 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5578 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5579 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5580 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5581 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5582 return;
5583 }
5584 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005585 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005586 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005587 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005588 mSettings.writeLP();
5589 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005590 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 }
5592 }
5593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005596 PackageParser.Package pkg,
5597 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005598 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005599 PackageParser.Package newPackage = null;
5600 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005601 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 PackageParser.PARSE_IS_SYSTEM;
5603 String packageName = deletedPackage.packageName;
5604 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5605 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005606 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 return;
5608 }
5609 PackageParser.Package oldPkg;
5610 PackageSetting oldPkgSetting;
5611 synchronized (mPackages) {
5612 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005613 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5615 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005616 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005617 return;
5618 }
5619 }
5620 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5621 res.removedInfo.removedPackage = packageName;
5622 // Remove existing system package
5623 removePackageLI(oldPkg, true);
5624 synchronized (mPackages) {
5625 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5626 }
5627
5628 // Successfully disabled the old package. Now proceed with re-installation
5629 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5630 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005631 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005633 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5635 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5636 }
5637 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005638 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 updatedSettings = true;
5640 }
5641
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005642 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 // Re installation failed. Restore old information
5644 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005645 if (newPackage != null) {
5646 removePackageLI(newPackage, true);
5647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005648 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005649 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005651 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005652 // Restore the old system information in Settings
5653 synchronized(mPackages) {
5654 if(updatedSettings) {
5655 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005656 mSettings.setInstallerPackageName(packageName,
5657 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005658 }
5659 mSettings.writeLP();
5660 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005661 } else {
5662 // If this is an update to an existing update, setup
5663 // to remove the existing update.
5664 synchronized (mPackages) {
5665 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5666 if (ps != null && ps.codePathString != null &&
5667 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5668 int installFlags = 0;
5669 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005670 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005671 }
5672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005673 }
5674 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005675
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005676 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005677 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005678 int retCode;
5679 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5680 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5681 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005682 if (mNoDexOpt) {
5683 /*
5684 * If we're in an engineering build, programs are lazily run
5685 * through dexopt. If the .dex file doesn't exist yet, it
5686 * will be created when the program is run next.
5687 */
5688 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5689 } else {
5690 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5691 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5692 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005693 }
5694 }
5695 return PackageManager.INSTALL_SUCCEEDED;
5696 }
5697
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005698 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005699 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005700 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 synchronized (mPackages) {
5702 //write settings. the installStatus will be incomplete at this stage.
5703 //note that the new package setting would have already been
5704 //added to mPackages. It hasn't been persisted yet.
5705 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5706 mSettings.writeLP();
5707 }
5708
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005709 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005710 != PackageManager.INSTALL_SUCCEEDED) {
5711 // Discontinue if moving dex files failed.
5712 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005714 if((res.returnCode = setPermissionsLI(newPackage))
5715 != PackageManager.INSTALL_SUCCEEDED) {
5716 if (mInstaller != null) {
5717 mInstaller.rmdex(newPackage.mScanPath);
5718 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005719 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005721 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005724 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005725 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 res.name = pkgName;
5727 res.uid = newPackage.applicationInfo.uid;
5728 res.pkg = newPackage;
5729 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005730 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5732 //to update install status
5733 mSettings.writeLP();
5734 }
5735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005736
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005737 private void installPackageLI(InstallArgs args,
5738 boolean newInstall, PackageInstalledInfo res) {
5739 int pFlags = args.flags;
5740 String installerPackageName = args.installerPackageName;
5741 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005742 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005743 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005744 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005745 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005746 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005747 // Result object to be returned
5748 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5749
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005750 // Retrieve PackageSettings and parse package
5751 int parseFlags = PackageParser.PARSE_CHATTY |
5752 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5753 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5754 parseFlags |= mDefParseFlags;
5755 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5756 pp.setSeparateProcesses(mSeparateProcesses);
5757 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5758 null, mMetrics, parseFlags);
5759 if (pkg == null) {
5760 res.returnCode = pp.getParseError();
5761 return;
5762 }
5763 String pkgName = res.name = pkg.packageName;
5764 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5765 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5766 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5767 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005769 }
5770 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5771 res.returnCode = pp.getParseError();
5772 return;
5773 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005774 // Get rid of all references to package scan path via parser.
5775 pp = null;
5776 String oldCodePath = null;
5777 boolean systemApp = false;
5778 synchronized (mPackages) {
5779 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005780 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5781 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005782 if (pkg.mOriginalPackages != null
5783 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005784 && mPackages.containsKey(oldName)) {
5785 // This package is derived from an original package,
5786 // and this device has been updating from that original
5787 // name. We must continue using the original name, so
5788 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005789 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005790 pkgName = pkg.packageName;
5791 replace = true;
5792 } else if (mPackages.containsKey(pkgName)) {
5793 // This package, under its official name, already exists
5794 // on the device; we should replace it.
5795 replace = true;
5796 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005797 }
5798 PackageSetting ps = mSettings.mPackages.get(pkgName);
5799 if (ps != null) {
5800 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5801 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5802 systemApp = (ps.pkg.applicationInfo.flags &
5803 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005804 }
5805 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005806 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005807
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005808 if (systemApp && onSd) {
5809 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005810 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005811 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5812 return;
5813 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005814
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005815 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5816 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5817 return;
5818 }
5819 // Set application objects path explicitly after the rename
5820 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005821 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005822 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005823 replacePackageLI(pkg, parseFlags, scanMode,
5824 installerPackageName, res);
5825 } else {
5826 installNewPackageLI(pkg, parseFlags, scanMode,
5827 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005828 }
5829 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005830
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005831 private int setPermissionsLI(PackageParser.Package newPackage) {
5832 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005833 int retCode = 0;
5834 // TODO Gross hack but fix later. Ideally move this to be a post installation
5835 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005836 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005837 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 try {
5839 extractPublicFiles(newPackage, destResourceFile);
5840 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005841 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 -08005842 " forward-locked app.");
5843 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5844 } finally {
5845 //TODO clean up the extracted public files
5846 }
5847 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005848 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 newPackage.applicationInfo.uid);
5850 } else {
5851 final int filePermissions =
5852 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005853 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005854 newPackage.applicationInfo.uid);
5855 }
5856 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005857 // The permissions on the resource file was set when it was copied for
5858 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005862 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005863 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005864 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005865 // TODO Define new internal error
5866 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005867 }
5868 return PackageManager.INSTALL_SUCCEEDED;
5869 }
5870
Kenny Root85387d72010-08-26 10:13:11 -07005871 private static boolean isForwardLocked(PackageParser.Package pkg) {
5872 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005873 }
5874
Kenny Root85387d72010-08-26 10:13:11 -07005875 private static boolean isExternal(PackageParser.Package pkg) {
5876 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5877 }
5878
5879 private static boolean isSystemApp(PackageParser.Package pkg) {
5880 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5881 }
5882
5883 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5884 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005885 }
5886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 private void extractPublicFiles(PackageParser.Package newPackage,
5888 File publicZipFile) throws IOException {
5889 final ZipOutputStream publicZipOutStream =
5890 new ZipOutputStream(new FileOutputStream(publicZipFile));
5891 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5892
5893 // Copy manifest, resources.arsc and res directory to public zip
5894
5895 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5896 while (privateZipEntries.hasMoreElements()) {
5897 final ZipEntry zipEntry = privateZipEntries.nextElement();
5898 final String zipEntryName = zipEntry.getName();
5899 if ("AndroidManifest.xml".equals(zipEntryName)
5900 || "resources.arsc".equals(zipEntryName)
5901 || zipEntryName.startsWith("res/")) {
5902 try {
5903 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5904 } catch (IOException e) {
5905 try {
5906 publicZipOutStream.close();
5907 throw e;
5908 } finally {
5909 publicZipFile.delete();
5910 }
5911 }
5912 }
5913 }
5914
5915 publicZipOutStream.close();
5916 FileUtils.setPermissions(
5917 publicZipFile.getAbsolutePath(),
5918 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5919 -1, -1);
5920 }
5921
5922 private static void copyZipEntry(ZipEntry zipEntry,
5923 ZipFile inZipFile,
5924 ZipOutputStream outZipStream) throws IOException {
5925 byte[] buffer = new byte[4096];
5926 int num;
5927
5928 ZipEntry newEntry;
5929 if (zipEntry.getMethod() == ZipEntry.STORED) {
5930 // Preserve the STORED method of the input entry.
5931 newEntry = new ZipEntry(zipEntry);
5932 } else {
5933 // Create a new entry so that the compressed len is recomputed.
5934 newEntry = new ZipEntry(zipEntry.getName());
5935 }
5936 outZipStream.putNextEntry(newEntry);
5937
5938 InputStream data = inZipFile.getInputStream(zipEntry);
5939 while ((num = data.read(buffer)) > 0) {
5940 outZipStream.write(buffer, 0, num);
5941 }
5942 outZipStream.flush();
5943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005945 private void deleteTempPackageFiles() {
5946 FilenameFilter filter = new FilenameFilter() {
5947 public boolean accept(File dir, String name) {
5948 return name.startsWith("vmdl") && name.endsWith(".tmp");
5949 }
5950 };
5951 String tmpFilesList[] = mAppInstallDir.list(filter);
5952 if(tmpFilesList == null) {
5953 return;
5954 }
5955 for(int i = 0; i < tmpFilesList.length; i++) {
5956 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5957 tmpFile.delete();
5958 }
5959 }
5960
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005961 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005962 File tmpPackageFile;
5963 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005964 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005965 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005966 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005967 return null;
5968 }
5969 try {
5970 FileUtils.setPermissions(
5971 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5972 -1, -1);
5973 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005974 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005975 return null;
5976 }
5977 return tmpPackageFile;
5978 }
5979
5980 public void deletePackage(final String packageName,
5981 final IPackageDeleteObserver observer,
5982 final int flags) {
5983 mContext.enforceCallingOrSelfPermission(
5984 android.Manifest.permission.DELETE_PACKAGES, null);
5985 // Queue up an async operation since the package deletion may take a little while.
5986 mHandler.post(new Runnable() {
5987 public void run() {
5988 mHandler.removeCallbacks(this);
5989 final boolean succeded = deletePackageX(packageName, true, true, flags);
5990 if (observer != null) {
5991 try {
5992 observer.packageDeleted(succeded);
5993 } catch (RemoteException e) {
5994 Log.i(TAG, "Observer no longer exists.");
5995 } //end catch
5996 } //end if
5997 } //end run
5998 });
5999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 /**
6002 * This method is an internal method that could be get invoked either
6003 * to delete an installed package or to clean up a failed installation.
6004 * After deleting an installed package, a broadcast is sent to notify any
6005 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006006 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 * installation wouldn't have sent the initial broadcast either
6008 * The key steps in deleting a package are
6009 * deleting the package information in internal structures like mPackages,
6010 * deleting the packages base directories through installd
6011 * updating mSettings to reflect current status
6012 * persisting settings for later use
6013 * sending a broadcast if necessary
6014 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006015 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6016 boolean deleteCodeAndResources, int flags) {
6017 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006018 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006020 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6021 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6022 try {
6023 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006024 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006025 return false;
6026 }
6027 } catch (RemoteException e) {
6028 }
6029
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006031 res = deletePackageLI(packageName, deleteCodeAndResources,
6032 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006036 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006037 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006038
6039 // If the removed package was a system update, the old system packaged
6040 // was re-enabled; we need to broadcast this information
6041 if (systemUpdate) {
6042 Bundle extras = new Bundle(1);
6043 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6044 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6045
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006046 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6047 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006049 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006050 // Force a gc here.
6051 Runtime.getRuntime().gc();
6052 // Delete the resources here after sending the broadcast to let
6053 // other processes clean up before deleting resources.
6054 if (info.args != null) {
6055 synchronized (mInstallLock) {
6056 info.args.doPostDeleteLI(deleteCodeAndResources);
6057 }
6058 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006059 return res;
6060 }
6061
6062 static class PackageRemovedInfo {
6063 String removedPackage;
6064 int uid = -1;
6065 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006066 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006067 // Clean up resources deleted packages.
6068 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006069
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006070 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 Bundle extras = new Bundle(1);
6072 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6073 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6074 if (replacing) {
6075 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6076 }
6077 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006078 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 }
6080 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006081 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 }
6083 }
6084 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 /*
6087 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6088 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006089 * 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 -08006090 * delete a partially installed application.
6091 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006092 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 int flags) {
6094 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006095 if (outInfo != null) {
6096 outInfo.removedPackage = packageName;
6097 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006098 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 // Retrieve object to delete permissions for shared user later on
6100 PackageSetting deletedPs;
6101 synchronized (mPackages) {
6102 deletedPs = mSettings.mPackages.get(packageName);
6103 }
6104 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006105 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006107 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006108 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006109 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110 + packageName + ", retcode=" + retCode);
6111 // we don't consider this to be a failure of the core package deletion
6112 }
6113 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006114 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 PackageParser.Package pkg = mPackages.get(packageName);
6116 File dataDir = new File(pkg.applicationInfo.dataDir);
6117 dataDir.delete();
6118 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006119 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006120 }
6121 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006122 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006123 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6124 if (outInfo != null) {
6125 outInfo.removedUid = mSettings.removePackageLP(packageName);
6126 }
6127 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006128 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006129 if (deletedPs.sharedUser != null) {
6130 // remove permissions associated with package
6131 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6132 }
6133 }
6134 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006135 // remove from preferred activities.
6136 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6137 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6138 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6139 removed.add(pa);
6140 }
6141 }
6142 for (PreferredActivity pa : removed) {
6143 mSettings.mPreferredActivities.removeFilter(pa);
6144 }
6145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006147 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006148 }
6149 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006151 /*
6152 * Tries to delete system package.
6153 */
6154 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006155 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 ApplicationInfo applicationInfo = p.applicationInfo;
6157 //applicable for non-partially installed applications only
6158 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006159 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006160 return false;
6161 }
6162 PackageSetting ps = null;
6163 // Confirm if the system package has been updated
6164 // An updated system app can be deleted. This will also have to restore
6165 // the system pkg from system partition
6166 synchronized (mPackages) {
6167 ps = mSettings.getDisabledSystemPkg(p.packageName);
6168 }
6169 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006170 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 return false;
6172 } else {
6173 Log.i(TAG, "Deleting system pkg from data partition");
6174 }
6175 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006176 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006177 final boolean deleteCodeAndResources;
6178 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006179 // Delete code and resources for downgrades
6180 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006181 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006182 } else {
6183 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006184 deleteCodeAndResources = false;
6185 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6188 if (!ret) {
6189 return false;
6190 }
6191 synchronized (mPackages) {
6192 // Reinstate the old system package
6193 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006194 // Remove any native libraries from the upgraded package.
6195 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 }
6197 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006198 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006200 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006203 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006204 return false;
6205 }
6206 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006207 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 mSettings.writeLP();
6209 }
6210 return true;
6211 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6214 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6215 ApplicationInfo applicationInfo = p.applicationInfo;
6216 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006217 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 return false;
6219 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006220 if (outInfo != null) {
6221 outInfo.uid = applicationInfo.uid;
6222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223
6224 // Delete package data from internal structures and also remove data if flag is set
6225 removePackageDataLI(p, outInfo, flags);
6226
6227 // Delete application code and resources
6228 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006229 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006230 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6231 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6232 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6233 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234 }
6235 return true;
6236 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006238 /*
6239 * This method handles package deletion in general
6240 */
6241 private boolean deletePackageLI(String packageName,
6242 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6243 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006244 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 return false;
6246 }
6247 PackageParser.Package p;
6248 boolean dataOnly = false;
6249 synchronized (mPackages) {
6250 p = mPackages.get(packageName);
6251 if (p == null) {
6252 //this retrieves partially installed apps
6253 dataOnly = true;
6254 PackageSetting ps = mSettings.mPackages.get(packageName);
6255 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006256 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 return false;
6258 }
6259 p = ps.pkg;
6260 }
6261 }
6262 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006263 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 return false;
6265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 if (dataOnly) {
6268 // Delete application data first
6269 removePackageDataLI(p, outInfo, flags);
6270 return true;
6271 }
6272 // At this point the package should have ApplicationInfo associated with it
6273 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006274 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 return false;
6276 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006277 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006278 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006279 Log.i(TAG, "Removing system package:"+p.packageName);
6280 // When an updated system application is deleted we delete the existing resources as well and
6281 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006282 ret = deleteSystemPackageLI(p, flags, outInfo);
6283 } else {
6284 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006285 // Kill application pre-emptively especially for apps on sd.
6286 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006287 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006289 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006292 public void clearApplicationUserData(final String packageName,
6293 final IPackageDataObserver observer) {
6294 mContext.enforceCallingOrSelfPermission(
6295 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6296 // Queue up an async operation since the package deletion may take a little while.
6297 mHandler.post(new Runnable() {
6298 public void run() {
6299 mHandler.removeCallbacks(this);
6300 final boolean succeeded;
6301 synchronized (mInstallLock) {
6302 succeeded = clearApplicationUserDataLI(packageName);
6303 }
6304 if (succeeded) {
6305 // invoke DeviceStorageMonitor's update method to clear any notifications
6306 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6307 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6308 if (dsm != null) {
6309 dsm.updateMemory();
6310 }
6311 }
6312 if(observer != null) {
6313 try {
6314 observer.onRemoveCompleted(packageName, succeeded);
6315 } catch (RemoteException e) {
6316 Log.i(TAG, "Observer no longer exists.");
6317 }
6318 } //end if observer
6319 } //end run
6320 });
6321 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 private boolean clearApplicationUserDataLI(String packageName) {
6324 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006325 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006326 return false;
6327 }
6328 PackageParser.Package p;
6329 boolean dataOnly = false;
6330 synchronized (mPackages) {
6331 p = mPackages.get(packageName);
6332 if(p == null) {
6333 dataOnly = true;
6334 PackageSetting ps = mSettings.mPackages.get(packageName);
6335 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006336 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 return false;
6338 }
6339 p = ps.pkg;
6340 }
6341 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006342 boolean useEncryptedFSDir = false;
6343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 if(!dataOnly) {
6345 //need to check this only for fully installed applications
6346 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006347 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 return false;
6349 }
6350 final ApplicationInfo applicationInfo = p.applicationInfo;
6351 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006352 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 return false;
6354 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006355 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006356 }
6357 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006358 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006360 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006361 + packageName);
6362 return false;
6363 }
6364 }
6365 return true;
6366 }
6367
6368 public void deleteApplicationCacheFiles(final String packageName,
6369 final IPackageDataObserver observer) {
6370 mContext.enforceCallingOrSelfPermission(
6371 android.Manifest.permission.DELETE_CACHE_FILES, null);
6372 // Queue up an async operation since the package deletion may take a little while.
6373 mHandler.post(new Runnable() {
6374 public void run() {
6375 mHandler.removeCallbacks(this);
6376 final boolean succeded;
6377 synchronized (mInstallLock) {
6378 succeded = deleteApplicationCacheFilesLI(packageName);
6379 }
6380 if(observer != null) {
6381 try {
6382 observer.onRemoveCompleted(packageName, succeded);
6383 } catch (RemoteException e) {
6384 Log.i(TAG, "Observer no longer exists.");
6385 }
6386 } //end if observer
6387 } //end run
6388 });
6389 }
6390
6391 private boolean deleteApplicationCacheFilesLI(String packageName) {
6392 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006393 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 return false;
6395 }
6396 PackageParser.Package p;
6397 synchronized (mPackages) {
6398 p = mPackages.get(packageName);
6399 }
6400 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006401 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006402 return false;
6403 }
6404 final ApplicationInfo applicationInfo = p.applicationInfo;
6405 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006406 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006407 return false;
6408 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006409 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006411 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006413 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 + packageName);
6415 return false;
6416 }
6417 }
6418 return true;
6419 }
6420
6421 public void getPackageSizeInfo(final String packageName,
6422 final IPackageStatsObserver observer) {
6423 mContext.enforceCallingOrSelfPermission(
6424 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6425 // Queue up an async operation since the package deletion may take a little while.
6426 mHandler.post(new Runnable() {
6427 public void run() {
6428 mHandler.removeCallbacks(this);
6429 PackageStats lStats = new PackageStats(packageName);
6430 final boolean succeded;
6431 synchronized (mInstallLock) {
6432 succeded = getPackageSizeInfoLI(packageName, lStats);
6433 }
6434 if(observer != null) {
6435 try {
6436 observer.onGetStatsCompleted(lStats, succeded);
6437 } catch (RemoteException e) {
6438 Log.i(TAG, "Observer no longer exists.");
6439 }
6440 } //end if observer
6441 } //end run
6442 });
6443 }
6444
6445 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6446 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006447 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006448 return false;
6449 }
6450 PackageParser.Package p;
6451 boolean dataOnly = false;
6452 synchronized (mPackages) {
6453 p = mPackages.get(packageName);
6454 if(p == null) {
6455 dataOnly = true;
6456 PackageSetting ps = mSettings.mPackages.get(packageName);
6457 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006458 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 return false;
6460 }
6461 p = ps.pkg;
6462 }
6463 }
6464 String publicSrcDir = null;
6465 if(!dataOnly) {
6466 final ApplicationInfo applicationInfo = p.applicationInfo;
6467 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006468 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 return false;
6470 }
6471 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6472 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006473 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 if (mInstaller != null) {
6475 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006476 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 if (res < 0) {
6478 return false;
6479 } else {
6480 return true;
6481 }
6482 }
6483 return true;
6484 }
6485
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006488 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 }
6490
6491 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006492 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006493 }
6494
6495 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006496 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 }
6498
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006499 int getUidTargetSdkVersionLockedLP(int uid) {
6500 Object obj = mSettings.getUserIdLP(uid);
6501 if (obj instanceof SharedUserSetting) {
6502 SharedUserSetting sus = (SharedUserSetting)obj;
6503 final int N = sus.packages.size();
6504 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6505 Iterator<PackageSetting> it = sus.packages.iterator();
6506 int i=0;
6507 while (it.hasNext()) {
6508 PackageSetting ps = it.next();
6509 if (ps.pkg != null) {
6510 int v = ps.pkg.applicationInfo.targetSdkVersion;
6511 if (v < vers) vers = v;
6512 }
6513 }
6514 return vers;
6515 } else if (obj instanceof PackageSetting) {
6516 PackageSetting ps = (PackageSetting)obj;
6517 if (ps.pkg != null) {
6518 return ps.pkg.applicationInfo.targetSdkVersion;
6519 }
6520 }
6521 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6522 }
6523
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006524 public void addPreferredActivity(IntentFilter filter, int match,
6525 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006526 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006527 if (mContext.checkCallingOrSelfPermission(
6528 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6529 != PackageManager.PERMISSION_GRANTED) {
6530 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6531 < Build.VERSION_CODES.FROYO) {
6532 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6533 + Binder.getCallingUid());
6534 return;
6535 }
6536 mContext.enforceCallingOrSelfPermission(
6537 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6538 }
6539
6540 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6542 mSettings.mPreferredActivities.addFilter(
6543 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006544 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006545 }
6546 }
6547
Satish Sampath8dbe6122009-06-02 23:35:54 +01006548 public void replacePreferredActivity(IntentFilter filter, int match,
6549 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006550 if (filter.countActions() != 1) {
6551 throw new IllegalArgumentException(
6552 "replacePreferredActivity expects filter to have only 1 action.");
6553 }
6554 if (filter.countCategories() != 1) {
6555 throw new IllegalArgumentException(
6556 "replacePreferredActivity expects filter to have only 1 category.");
6557 }
6558 if (filter.countDataAuthorities() != 0
6559 || filter.countDataPaths() != 0
6560 || filter.countDataSchemes() != 0
6561 || filter.countDataTypes() != 0) {
6562 throw new IllegalArgumentException(
6563 "replacePreferredActivity expects filter to have no data authorities, " +
6564 "paths, schemes or types.");
6565 }
6566 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006567 if (mContext.checkCallingOrSelfPermission(
6568 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6569 != PackageManager.PERMISSION_GRANTED) {
6570 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6571 < Build.VERSION_CODES.FROYO) {
6572 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6573 + Binder.getCallingUid());
6574 return;
6575 }
6576 mContext.enforceCallingOrSelfPermission(
6577 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6578 }
6579
Satish Sampath8dbe6122009-06-02 23:35:54 +01006580 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6581 String action = filter.getAction(0);
6582 String category = filter.getCategory(0);
6583 while (it.hasNext()) {
6584 PreferredActivity pa = it.next();
6585 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6586 it.remove();
6587 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6588 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6589 }
6590 }
6591 addPreferredActivity(filter, match, set, activity);
6592 }
6593 }
6594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006595 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006597 int uid = Binder.getCallingUid();
6598 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006599 if (pkg == null || pkg.applicationInfo.uid != uid) {
6600 if (mContext.checkCallingOrSelfPermission(
6601 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6602 != PackageManager.PERMISSION_GRANTED) {
6603 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6604 < Build.VERSION_CODES.FROYO) {
6605 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6606 + Binder.getCallingUid());
6607 return;
6608 }
6609 mContext.enforceCallingOrSelfPermission(
6610 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6611 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006612 }
6613
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006614 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006615 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 }
6617 }
6618 }
6619
6620 boolean clearPackagePreferredActivitiesLP(String packageName) {
6621 boolean changed = false;
6622 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6623 while (it.hasNext()) {
6624 PreferredActivity pa = it.next();
6625 if (pa.mActivity.getPackageName().equals(packageName)) {
6626 it.remove();
6627 changed = true;
6628 }
6629 }
6630 return changed;
6631 }
6632
6633 public int getPreferredActivities(List<IntentFilter> outFilters,
6634 List<ComponentName> outActivities, String packageName) {
6635
6636 int num = 0;
6637 synchronized (mPackages) {
6638 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6639 while (it.hasNext()) {
6640 PreferredActivity pa = it.next();
6641 if (packageName == null
6642 || pa.mActivity.getPackageName().equals(packageName)) {
6643 if (outFilters != null) {
6644 outFilters.add(new IntentFilter(pa));
6645 }
6646 if (outActivities != null) {
6647 outActivities.add(pa.mActivity);
6648 }
6649 }
6650 }
6651 }
6652
6653 return num;
6654 }
6655
6656 public void setApplicationEnabledSetting(String appPackageName,
6657 int newState, int flags) {
6658 setEnabledSetting(appPackageName, null, newState, flags);
6659 }
6660
6661 public void setComponentEnabledSetting(ComponentName componentName,
6662 int newState, int flags) {
6663 setEnabledSetting(componentName.getPackageName(),
6664 componentName.getClassName(), newState, flags);
6665 }
6666
6667 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006668 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6670 || newState == COMPONENT_ENABLED_STATE_ENABLED
6671 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6672 throw new IllegalArgumentException("Invalid new component state: "
6673 + newState);
6674 }
6675 PackageSetting pkgSetting;
6676 final int uid = Binder.getCallingUid();
6677 final int permission = mContext.checkCallingPermission(
6678 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6679 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006680 boolean sendNow = false;
6681 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006682 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006683 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006684 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006685 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006686 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006688 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006690 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 }
6692 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006693 "Unknown component: " + packageName
6694 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 }
6696 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6697 throw new SecurityException(
6698 "Permission Denial: attempt to change component state from pid="
6699 + Binder.getCallingPid()
6700 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6701 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006702 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006703 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006704 if (pkgSetting.enabled == newState) {
6705 // Nothing to do
6706 return;
6707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006708 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006709 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 } else {
6711 // We're dealing with a component level state change
6712 switch (newState) {
6713 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006714 if (!pkgSetting.enableComponentLP(className)) {
6715 return;
6716 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 break;
6718 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006719 if (!pkgSetting.disableComponentLP(className)) {
6720 return;
6721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006722 break;
6723 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006724 if (!pkgSetting.restoreComponentLP(className)) {
6725 return;
6726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 break;
6728 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006729 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006730 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006731 }
6732 }
6733 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006734 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006735 components = mPendingBroadcasts.get(packageName);
6736 boolean newPackage = components == null;
6737 if (newPackage) {
6738 components = new ArrayList<String>();
6739 }
6740 if (!components.contains(componentName)) {
6741 components.add(componentName);
6742 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006743 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6744 sendNow = true;
6745 // Purge entry from pending broadcast list if another one exists already
6746 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006747 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006748 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006749 if (newPackage) {
6750 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006751 }
6752 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6753 // Schedule a message
6754 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6755 }
6756 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 long callingId = Binder.clearCallingIdentity();
6760 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006761 if (sendNow) {
6762 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006763 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006764 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006765 } finally {
6766 Binder.restoreCallingIdentity(callingId);
6767 }
6768 }
6769
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006770 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006771 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6772 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6773 + " components=" + componentNames);
6774 Bundle extras = new Bundle(4);
6775 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6776 String nameList[] = new String[componentNames.size()];
6777 componentNames.toArray(nameList);
6778 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006779 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6780 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006781 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006782 }
6783
Jacek Surazski65e13172009-04-28 15:26:38 +02006784 public String getInstallerPackageName(String packageName) {
6785 synchronized (mPackages) {
6786 PackageSetting pkg = mSettings.mPackages.get(packageName);
6787 if (pkg == null) {
6788 throw new IllegalArgumentException("Unknown package: " + packageName);
6789 }
6790 return pkg.installerPackageName;
6791 }
6792 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794 public int getApplicationEnabledSetting(String appPackageName) {
6795 synchronized (mPackages) {
6796 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6797 if (pkg == null) {
6798 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6799 }
6800 return pkg.enabled;
6801 }
6802 }
6803
6804 public int getComponentEnabledSetting(ComponentName componentName) {
6805 synchronized (mPackages) {
6806 final String packageNameStr = componentName.getPackageName();
6807 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6808 if (pkg == null) {
6809 throw new IllegalArgumentException("Unknown component: " + componentName);
6810 }
6811 final String classNameStr = componentName.getClassName();
6812 return pkg.currentEnabledStateLP(classNameStr);
6813 }
6814 }
6815
6816 public void enterSafeMode() {
6817 if (!mSystemReady) {
6818 mSafeMode = true;
6819 }
6820 }
6821
6822 public void systemReady() {
6823 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006824
6825 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006826 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006827 mContext.getContentResolver(),
6828 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006829 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006830 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006831 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006833 }
6834
6835 public boolean isSafeMode() {
6836 return mSafeMode;
6837 }
6838
6839 public boolean hasSystemUidErrors() {
6840 return mHasSystemUidErrors;
6841 }
6842
6843 static String arrayToString(int[] array) {
6844 StringBuffer buf = new StringBuffer(128);
6845 buf.append('[');
6846 if (array != null) {
6847 for (int i=0; i<array.length; i++) {
6848 if (i > 0) buf.append(", ");
6849 buf.append(array[i]);
6850 }
6851 }
6852 buf.append(']');
6853 return buf.toString();
6854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006856 @Override
6857 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6858 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6859 != PackageManager.PERMISSION_GRANTED) {
6860 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6861 + Binder.getCallingPid()
6862 + ", uid=" + Binder.getCallingUid()
6863 + " without permission "
6864 + android.Manifest.permission.DUMP);
6865 return;
6866 }
6867
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006868 String packageName = null;
6869
6870 int opti = 0;
6871 while (opti < args.length) {
6872 String opt = args[opti];
6873 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6874 break;
6875 }
6876 opti++;
6877 if ("-a".equals(opt)) {
6878 // Right now we only know how to print all.
6879 } else if ("-h".equals(opt)) {
6880 pw.println("Package manager dump options:");
6881 pw.println(" [-h] [cmd] ...");
6882 pw.println(" cmd may be one of:");
6883 pw.println(" [package.name]: info about given package");
6884 return;
6885 } else {
6886 pw.println("Unknown argument: " + opt + "; use -h for help");
6887 }
6888 }
6889
6890 // Is the caller requesting to dump a particular piece of data?
6891 if (opti < args.length) {
6892 String cmd = args[opti];
6893 opti++;
6894 // Is this a package name?
6895 if ("android".equals(cmd) || cmd.contains(".")) {
6896 packageName = cmd;
6897 }
6898 }
6899
6900 boolean printedTitle = false;
6901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006902 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006903 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6904 printedTitle = true;
6905 }
6906 if (mReceivers.dump(pw, printedTitle
6907 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6908 " ", packageName)) {
6909 printedTitle = true;
6910 }
6911 if (mServices.dump(pw, printedTitle
6912 ? "\nService Resolver Table:" : "Service Resolver Table:",
6913 " ", packageName)) {
6914 printedTitle = true;
6915 }
6916 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6917 ? "\nPreferred Activities:" : "Preferred Activities:",
6918 " ", packageName)) {
6919 printedTitle = true;
6920 }
6921 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006922 {
6923 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006924 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6925 continue;
6926 }
6927 if (!printedSomething) {
6928 if (printedTitle) pw.println(" ");
6929 pw.println("Permissions:");
6930 printedSomething = true;
6931 printedTitle = true;
6932 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006933 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6934 pw.print(Integer.toHexString(System.identityHashCode(p)));
6935 pw.println("):");
6936 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6937 pw.print(" uid="); pw.print(p.uid);
6938 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006939 pw.print(" type="); pw.print(p.type);
6940 pw.print(" prot="); pw.println(p.protectionLevel);
6941 if (p.packageSetting != null) {
6942 pw.print(" packageSetting="); pw.println(p.packageSetting);
6943 }
6944 if (p.perm != null) {
6945 pw.print(" perm="); pw.println(p.perm);
6946 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006947 }
6948 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006949 printedSomething = false;
6950 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006951 {
6952 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006953 if (packageName != null && !packageName.equals(ps.realName)
6954 && !packageName.equals(ps.name)) {
6955 continue;
6956 }
6957 if (!printedSomething) {
6958 if (printedTitle) pw.println(" ");
6959 pw.println("Packages:");
6960 printedSomething = true;
6961 printedTitle = true;
6962 }
6963 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006964 pw.print(" Package [");
6965 pw.print(ps.realName != null ? ps.realName : ps.name);
6966 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006967 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6968 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006969 if (ps.realName != null) {
6970 pw.print(" compat name="); pw.println(ps.name);
6971 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006972 pw.print(" userId="); pw.print(ps.userId);
6973 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6974 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6975 pw.print(" pkg="); pw.println(ps.pkg);
6976 pw.print(" codePath="); pw.println(ps.codePathString);
6977 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07006978 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07006979 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006980 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006981 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006982 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07006983 if (ps.pkg.mOperationPending) {
6984 pw.println(" mOperationPending=true");
6985 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006986 pw.print(" supportsScreens=[");
6987 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006988 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07006989 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
6990 if (!first) pw.print(", ");
6991 first = false;
6992 pw.print("small");
6993 }
6994 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006995 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006996 if (!first) pw.print(", ");
6997 first = false;
6998 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007000 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007001 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007002 if (!first) pw.print(", ");
7003 first = false;
7004 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007006 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007007 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007008 if (!first) pw.print(", ");
7009 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007010 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007012 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007013 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007014 if (!first) pw.print(", ");
7015 first = false;
7016 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007018 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007019 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7020 if (!first) pw.print(", ");
7021 first = false;
7022 pw.print("anyDensity");
7023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007025 pw.println("]");
Kenny Root7d794fb2010-09-13 16:29:49 -07007026 pw.print(" timeStamp="); pw.println(String.valueOf(ps.timeStamp));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007027 pw.print(" signatures="); pw.println(ps.signatures);
7028 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007029 pw.print(" haveGids="); pw.println(ps.haveGids);
7030 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007031 pw.print(" installStatus="); pw.print(ps.installStatus);
7032 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007033 if (ps.disabledComponents.size() > 0) {
7034 pw.println(" disabledComponents:");
7035 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007036 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007037 }
7038 }
7039 if (ps.enabledComponents.size() > 0) {
7040 pw.println(" enabledComponents:");
7041 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007042 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 }
7044 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007045 if (ps.grantedPermissions.size() > 0) {
7046 pw.println(" grantedPermissions:");
7047 for (String s : ps.grantedPermissions) {
7048 pw.print(" "); pw.println(s);
7049 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007051 }
7052 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007053 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007054 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007055 for (HashMap.Entry<String, String> e
7056 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007057 if (packageName != null && !packageName.equals(e.getKey())
7058 && !packageName.equals(e.getValue())) {
7059 continue;
7060 }
7061 if (!printedSomething) {
7062 if (printedTitle) pw.println(" ");
7063 pw.println("Renamed packages:");
7064 printedSomething = true;
7065 printedTitle = true;
7066 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007067 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7068 pw.println(e.getValue());
7069 }
7070 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007071 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007072 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007073 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007074 if (packageName != null && !packageName.equals(ps.realName)
7075 && !packageName.equals(ps.name)) {
7076 continue;
7077 }
7078 if (!printedSomething) {
7079 if (printedTitle) pw.println(" ");
7080 pw.println("Hidden system packages:");
7081 printedSomething = true;
7082 printedTitle = true;
7083 }
7084 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007085 pw.print(ps.realName != null ? ps.realName : ps.name);
7086 pw.print("] (");
7087 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7088 pw.println("):");
7089 if (ps.realName != null) {
7090 pw.print(" compat name="); pw.println(ps.name);
7091 }
7092 pw.print(" userId="); pw.println(ps.userId);
7093 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7094 pw.print(" codePath="); pw.println(ps.codePathString);
7095 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7096 }
7097 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007098 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 {
7100 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007101 if (packageName != null && su != packageSharedUser) {
7102 continue;
7103 }
7104 if (!printedSomething) {
7105 if (printedTitle) pw.println(" ");
7106 pw.println("Shared users:");
7107 printedSomething = true;
7108 printedTitle = true;
7109 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007110 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7111 pw.print(Integer.toHexString(System.identityHashCode(su)));
7112 pw.println("):");
7113 pw.print(" userId="); pw.print(su.userId);
7114 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007115 pw.println(" grantedPermissions:");
7116 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007117 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 }
7120 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007121
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007122 if (packageName == null) {
7123 if (printedTitle) pw.println(" ");
7124 printedTitle = true;
7125 pw.println("Settings parse messages:");
7126 pw.println(mSettings.mReadMessages.toString());
7127
7128 pw.println(" ");
7129 pw.println("Package warning messages:");
7130 File fname = getSettingsProblemFile();
7131 FileInputStream in;
7132 try {
7133 in = new FileInputStream(fname);
7134 int avail = in.available();
7135 byte[] data = new byte[avail];
7136 in.read(data);
7137 pw.println(new String(data));
7138 } catch (FileNotFoundException e) {
7139 } catch (IOException e) {
7140 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007142 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007143
7144 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007145 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007146 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007147 if (packageName != null && !packageName.equals(p.info.packageName)) {
7148 continue;
7149 }
7150 if (!printedSomething) {
7151 if (printedTitle) pw.println(" ");
7152 pw.println("Registered ContentProviders:");
7153 printedSomething = true;
7154 printedTitle = true;
7155 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007156 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007157 pw.println(p.toString());
7158 }
7159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007160 }
7161
7162 static final class BasePermission {
7163 final static int TYPE_NORMAL = 0;
7164 final static int TYPE_BUILTIN = 1;
7165 final static int TYPE_DYNAMIC = 2;
7166
7167 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007168 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007169 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007170 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007171 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007172 PackageParser.Permission perm;
7173 PermissionInfo pendingInfo;
7174 int uid;
7175 int[] gids;
7176
7177 BasePermission(String _name, String _sourcePackage, int _type) {
7178 name = _name;
7179 sourcePackage = _sourcePackage;
7180 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007181 // Default to most conservative protection level.
7182 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7183 }
7184
7185 public String toString() {
7186 return "BasePermission{"
7187 + Integer.toHexString(System.identityHashCode(this))
7188 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007189 }
7190 }
7191
7192 static class PackageSignatures {
7193 private Signature[] mSignatures;
7194
7195 PackageSignatures(Signature[] sigs) {
7196 assignSignatures(sigs);
7197 }
7198
7199 PackageSignatures() {
7200 }
7201
7202 void writeXml(XmlSerializer serializer, String tagName,
7203 ArrayList<Signature> pastSignatures) throws IOException {
7204 if (mSignatures == null) {
7205 return;
7206 }
7207 serializer.startTag(null, tagName);
7208 serializer.attribute(null, "count",
7209 Integer.toString(mSignatures.length));
7210 for (int i=0; i<mSignatures.length; i++) {
7211 serializer.startTag(null, "cert");
7212 final Signature sig = mSignatures[i];
7213 final int sigHash = sig.hashCode();
7214 final int numPast = pastSignatures.size();
7215 int j;
7216 for (j=0; j<numPast; j++) {
7217 Signature pastSig = pastSignatures.get(j);
7218 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7219 serializer.attribute(null, "index", Integer.toString(j));
7220 break;
7221 }
7222 }
7223 if (j >= numPast) {
7224 pastSignatures.add(sig);
7225 serializer.attribute(null, "index", Integer.toString(numPast));
7226 serializer.attribute(null, "key", sig.toCharsString());
7227 }
7228 serializer.endTag(null, "cert");
7229 }
7230 serializer.endTag(null, tagName);
7231 }
7232
7233 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7234 throws IOException, XmlPullParserException {
7235 String countStr = parser.getAttributeValue(null, "count");
7236 if (countStr == null) {
7237 reportSettingsProblem(Log.WARN,
7238 "Error in package manager settings: <signatures> has"
7239 + " no count at " + parser.getPositionDescription());
7240 XmlUtils.skipCurrentTag(parser);
7241 }
7242 final int count = Integer.parseInt(countStr);
7243 mSignatures = new Signature[count];
7244 int pos = 0;
7245
7246 int outerDepth = parser.getDepth();
7247 int type;
7248 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7249 && (type != XmlPullParser.END_TAG
7250 || parser.getDepth() > outerDepth)) {
7251 if (type == XmlPullParser.END_TAG
7252 || type == XmlPullParser.TEXT) {
7253 continue;
7254 }
7255
7256 String tagName = parser.getName();
7257 if (tagName.equals("cert")) {
7258 if (pos < count) {
7259 String index = parser.getAttributeValue(null, "index");
7260 if (index != null) {
7261 try {
7262 int idx = Integer.parseInt(index);
7263 String key = parser.getAttributeValue(null, "key");
7264 if (key == null) {
7265 if (idx >= 0 && idx < pastSignatures.size()) {
7266 Signature sig = pastSignatures.get(idx);
7267 if (sig != null) {
7268 mSignatures[pos] = pastSignatures.get(idx);
7269 pos++;
7270 } else {
7271 reportSettingsProblem(Log.WARN,
7272 "Error in package manager settings: <cert> "
7273 + "index " + index + " is not defined at "
7274 + parser.getPositionDescription());
7275 }
7276 } else {
7277 reportSettingsProblem(Log.WARN,
7278 "Error in package manager settings: <cert> "
7279 + "index " + index + " is out of bounds at "
7280 + parser.getPositionDescription());
7281 }
7282 } else {
7283 while (pastSignatures.size() <= idx) {
7284 pastSignatures.add(null);
7285 }
7286 Signature sig = new Signature(key);
7287 pastSignatures.set(idx, sig);
7288 mSignatures[pos] = sig;
7289 pos++;
7290 }
7291 } catch (NumberFormatException e) {
7292 reportSettingsProblem(Log.WARN,
7293 "Error in package manager settings: <cert> "
7294 + "index " + index + " is not a number at "
7295 + parser.getPositionDescription());
7296 }
7297 } else {
7298 reportSettingsProblem(Log.WARN,
7299 "Error in package manager settings: <cert> has"
7300 + " no index at " + parser.getPositionDescription());
7301 }
7302 } else {
7303 reportSettingsProblem(Log.WARN,
7304 "Error in package manager settings: too "
7305 + "many <cert> tags, expected " + count
7306 + " at " + parser.getPositionDescription());
7307 }
7308 } else {
7309 reportSettingsProblem(Log.WARN,
7310 "Unknown element under <cert>: "
7311 + parser.getName());
7312 }
7313 XmlUtils.skipCurrentTag(parser);
7314 }
7315
7316 if (pos < count) {
7317 // Should never happen -- there is an error in the written
7318 // settings -- but if it does we don't want to generate
7319 // a bad array.
7320 Signature[] newSigs = new Signature[pos];
7321 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7322 mSignatures = newSigs;
7323 }
7324 }
7325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007326 private void assignSignatures(Signature[] sigs) {
7327 if (sigs == null) {
7328 mSignatures = null;
7329 return;
7330 }
7331 mSignatures = new Signature[sigs.length];
7332 for (int i=0; i<sigs.length; i++) {
7333 mSignatures[i] = sigs[i];
7334 }
7335 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 @Override
7338 public String toString() {
7339 StringBuffer buf = new StringBuffer(128);
7340 buf.append("PackageSignatures{");
7341 buf.append(Integer.toHexString(System.identityHashCode(this)));
7342 buf.append(" [");
7343 if (mSignatures != null) {
7344 for (int i=0; i<mSignatures.length; i++) {
7345 if (i > 0) buf.append(", ");
7346 buf.append(Integer.toHexString(
7347 System.identityHashCode(mSignatures[i])));
7348 }
7349 }
7350 buf.append("]}");
7351 return buf.toString();
7352 }
7353 }
7354
7355 static class PreferredActivity extends IntentFilter {
7356 final int mMatch;
7357 final String[] mSetPackages;
7358 final String[] mSetClasses;
7359 final String[] mSetComponents;
7360 final ComponentName mActivity;
7361 final String mShortActivity;
7362 String mParseError;
7363
7364 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7365 ComponentName activity) {
7366 super(filter);
7367 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7368 mActivity = activity;
7369 mShortActivity = activity.flattenToShortString();
7370 mParseError = null;
7371 if (set != null) {
7372 final int N = set.length;
7373 String[] myPackages = new String[N];
7374 String[] myClasses = new String[N];
7375 String[] myComponents = new String[N];
7376 for (int i=0; i<N; i++) {
7377 ComponentName cn = set[i];
7378 if (cn == null) {
7379 mSetPackages = null;
7380 mSetClasses = null;
7381 mSetComponents = null;
7382 return;
7383 }
7384 myPackages[i] = cn.getPackageName().intern();
7385 myClasses[i] = cn.getClassName().intern();
7386 myComponents[i] = cn.flattenToShortString().intern();
7387 }
7388 mSetPackages = myPackages;
7389 mSetClasses = myClasses;
7390 mSetComponents = myComponents;
7391 } else {
7392 mSetPackages = null;
7393 mSetClasses = null;
7394 mSetComponents = null;
7395 }
7396 }
7397
7398 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7399 IOException {
7400 mShortActivity = parser.getAttributeValue(null, "name");
7401 mActivity = ComponentName.unflattenFromString(mShortActivity);
7402 if (mActivity == null) {
7403 mParseError = "Bad activity name " + mShortActivity;
7404 }
7405 String matchStr = parser.getAttributeValue(null, "match");
7406 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7407 String setCountStr = parser.getAttributeValue(null, "set");
7408 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7409
7410 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7411 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7412 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7413
7414 int setPos = 0;
7415
7416 int outerDepth = parser.getDepth();
7417 int type;
7418 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7419 && (type != XmlPullParser.END_TAG
7420 || parser.getDepth() > outerDepth)) {
7421 if (type == XmlPullParser.END_TAG
7422 || type == XmlPullParser.TEXT) {
7423 continue;
7424 }
7425
7426 String tagName = parser.getName();
7427 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7428 // + parser.getDepth() + " tag=" + tagName);
7429 if (tagName.equals("set")) {
7430 String name = parser.getAttributeValue(null, "name");
7431 if (name == null) {
7432 if (mParseError == null) {
7433 mParseError = "No name in set tag in preferred activity "
7434 + mShortActivity;
7435 }
7436 } else if (setPos >= setCount) {
7437 if (mParseError == null) {
7438 mParseError = "Too many set tags in preferred activity "
7439 + mShortActivity;
7440 }
7441 } else {
7442 ComponentName cn = ComponentName.unflattenFromString(name);
7443 if (cn == null) {
7444 if (mParseError == null) {
7445 mParseError = "Bad set name " + name + " in preferred activity "
7446 + mShortActivity;
7447 }
7448 } else {
7449 myPackages[setPos] = cn.getPackageName();
7450 myClasses[setPos] = cn.getClassName();
7451 myComponents[setPos] = name;
7452 setPos++;
7453 }
7454 }
7455 XmlUtils.skipCurrentTag(parser);
7456 } else if (tagName.equals("filter")) {
7457 //Log.i(TAG, "Starting to parse filter...");
7458 readFromXml(parser);
7459 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7460 // + parser.getDepth() + " tag=" + parser.getName());
7461 } else {
7462 reportSettingsProblem(Log.WARN,
7463 "Unknown element under <preferred-activities>: "
7464 + parser.getName());
7465 XmlUtils.skipCurrentTag(parser);
7466 }
7467 }
7468
7469 if (setPos != setCount) {
7470 if (mParseError == null) {
7471 mParseError = "Not enough set tags (expected " + setCount
7472 + " but found " + setPos + ") in " + mShortActivity;
7473 }
7474 }
7475
7476 mSetPackages = myPackages;
7477 mSetClasses = myClasses;
7478 mSetComponents = myComponents;
7479 }
7480
7481 public void writeToXml(XmlSerializer serializer) throws IOException {
7482 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7483 serializer.attribute(null, "name", mShortActivity);
7484 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7485 serializer.attribute(null, "set", Integer.toString(NS));
7486 for (int s=0; s<NS; s++) {
7487 serializer.startTag(null, "set");
7488 serializer.attribute(null, "name", mSetComponents[s]);
7489 serializer.endTag(null, "set");
7490 }
7491 serializer.startTag(null, "filter");
7492 super.writeToXml(serializer);
7493 serializer.endTag(null, "filter");
7494 }
7495
7496 boolean sameSet(List<ResolveInfo> query, int priority) {
7497 if (mSetPackages == null) return false;
7498 final int NQ = query.size();
7499 final int NS = mSetPackages.length;
7500 int numMatch = 0;
7501 for (int i=0; i<NQ; i++) {
7502 ResolveInfo ri = query.get(i);
7503 if (ri.priority != priority) continue;
7504 ActivityInfo ai = ri.activityInfo;
7505 boolean good = false;
7506 for (int j=0; j<NS; j++) {
7507 if (mSetPackages[j].equals(ai.packageName)
7508 && mSetClasses[j].equals(ai.name)) {
7509 numMatch++;
7510 good = true;
7511 break;
7512 }
7513 }
7514 if (!good) return false;
7515 }
7516 return numMatch == NS;
7517 }
7518 }
7519
7520 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007521 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 HashSet<String> grantedPermissions = new HashSet<String>();
7524 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007526 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007527 setFlags(pkgFlags);
7528 }
7529
7530 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007531 this.pkgFlags = pkgFlags & (
7532 ApplicationInfo.FLAG_SYSTEM |
7533 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007534 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007535 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 }
7537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007539 /**
7540 * Settings base class for pending and resolved classes.
7541 */
7542 static class PackageSettingBase extends GrantedPermissions {
7543 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007544 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007545 File codePath;
7546 String codePathString;
7547 File resourcePath;
7548 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007549 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007550 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007551 long timeStamp;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007552 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007553
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007554 boolean uidError;
7555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007556 PackageSignatures signatures = new PackageSignatures();
7557
7558 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007559 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 /* Explicitly disabled components */
7562 HashSet<String> disabledComponents = new HashSet<String>(0);
7563 /* Explicitly enabled components */
7564 HashSet<String> enabledComponents = new HashSet<String>(0);
7565 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7566 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007567
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007568 PackageSettingBase origPackage;
7569
Jacek Surazski65e13172009-04-28 15:26:38 +02007570 /* package name of the app that installed this package */
7571 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007572
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007573 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007574 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007575 super(pkgFlags);
7576 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007577 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007578 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007579 }
7580
Kenny Root806cc132010-09-12 08:34:19 -07007581 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7582 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 this.codePath = codePath;
7584 this.codePathString = codePath.toString();
7585 this.resourcePath = resourcePath;
7586 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007587 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007588 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007589 }
Kenny Root85387d72010-08-26 10:13:11 -07007590
Jacek Surazski65e13172009-04-28 15:26:38 +02007591 public void setInstallerPackageName(String packageName) {
7592 installerPackageName = packageName;
7593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007594
Jacek Surazski65e13172009-04-28 15:26:38 +02007595 String getInstallerPackageName() {
7596 return installerPackageName;
7597 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 public void setInstallStatus(int newStatus) {
7600 installStatus = newStatus;
7601 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007603 public int getInstallStatus() {
7604 return installStatus;
7605 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007606
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007607 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 }
7610
7611 public void copyFrom(PackageSettingBase base) {
7612 grantedPermissions = base.grantedPermissions;
7613 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007615 timeStamp = base.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 signatures = base.signatures;
7617 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007618 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007619 disabledComponents = base.disabledComponents;
7620 enabledComponents = base.enabledComponents;
7621 enabled = base.enabled;
7622 installStatus = base.installStatus;
7623 }
7624
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007625 boolean enableComponentLP(String componentClassName) {
7626 boolean changed = disabledComponents.remove(componentClassName);
7627 changed |= enabledComponents.add(componentClassName);
7628 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 }
7630
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007631 boolean disableComponentLP(String componentClassName) {
7632 boolean changed = enabledComponents.remove(componentClassName);
7633 changed |= disabledComponents.add(componentClassName);
7634 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007635 }
7636
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007637 boolean restoreComponentLP(String componentClassName) {
7638 boolean changed = enabledComponents.remove(componentClassName);
7639 changed |= disabledComponents.remove(componentClassName);
7640 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 }
7642
7643 int currentEnabledStateLP(String componentName) {
7644 if (enabledComponents.contains(componentName)) {
7645 return COMPONENT_ENABLED_STATE_ENABLED;
7646 } else if (disabledComponents.contains(componentName)) {
7647 return COMPONENT_ENABLED_STATE_DISABLED;
7648 } else {
7649 return COMPONENT_ENABLED_STATE_DEFAULT;
7650 }
7651 }
7652 }
7653
7654 /**
7655 * Settings data for a particular package we know about.
7656 */
7657 static final class PackageSetting extends PackageSettingBase {
7658 int userId;
7659 PackageParser.Package pkg;
7660 SharedUserSetting sharedUser;
7661
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007662 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007663 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7664 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7665 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007666 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 @Override
7669 public String toString() {
7670 return "PackageSetting{"
7671 + Integer.toHexString(System.identityHashCode(this))
7672 + " " + name + "/" + userId + "}";
7673 }
7674 }
7675
7676 /**
7677 * Settings data for a particular shared user ID we know about.
7678 */
7679 static final class SharedUserSetting extends GrantedPermissions {
7680 final String name;
7681 int userId;
7682 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7683 final PackageSignatures signatures = new PackageSignatures();
7684
7685 SharedUserSetting(String _name, int _pkgFlags) {
7686 super(_pkgFlags);
7687 name = _name;
7688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 @Override
7691 public String toString() {
7692 return "SharedUserSetting{"
7693 + Integer.toHexString(System.identityHashCode(this))
7694 + " " + name + "/" + userId + "}";
7695 }
7696 }
7697
7698 /**
7699 * Holds information about dynamic settings.
7700 */
7701 private static final class Settings {
7702 private final File mSettingsFilename;
7703 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007704 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007705 private final HashMap<String, PackageSetting> mPackages =
7706 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 // List of replaced system applications
7708 final HashMap<String, PackageSetting> mDisabledSysPackages =
7709 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007710
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007711 // These are the last platform API version we were using for
7712 // the apps installed on internal and external storage. It is
7713 // used to grant newer permissions one time during a system upgrade.
7714 int mInternalSdkPlatform;
7715 int mExternalSdkPlatform;
7716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717 // The user's preferred activities associated with particular intent
7718 // filters.
7719 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7720 new IntentResolver<PreferredActivity, PreferredActivity>() {
7721 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007722 protected String packageForFilter(PreferredActivity filter) {
7723 return filter.mActivity.getPackageName();
7724 }
7725 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007726 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007728 out.print(prefix); out.print(
7729 Integer.toHexString(System.identityHashCode(filter)));
7730 out.print(' ');
7731 out.print(filter.mActivity.flattenToShortString());
7732 out.print(" match=0x");
7733 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007734 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007735 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007737 out.print(prefix); out.print(" ");
7738 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 }
7740 }
7741 }
7742 };
7743 private final HashMap<String, SharedUserSetting> mSharedUsers =
7744 new HashMap<String, SharedUserSetting>();
7745 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7746 private final SparseArray<Object> mOtherUserIds =
7747 new SparseArray<Object>();
7748
7749 // For reading/writing settings file.
7750 private final ArrayList<Signature> mPastSignatures =
7751 new ArrayList<Signature>();
7752
7753 // Mapping from permission names to info about them.
7754 final HashMap<String, BasePermission> mPermissions =
7755 new HashMap<String, BasePermission>();
7756
7757 // Mapping from permission tree names to info about them.
7758 final HashMap<String, BasePermission> mPermissionTrees =
7759 new HashMap<String, BasePermission>();
7760
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007761 // Packages that have been uninstalled and still need their external
7762 // storage data deleted.
7763 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7764
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007765 // Packages that have been renamed since they were first installed.
7766 // Keys are the new names of the packages, values are the original
7767 // names. The packages appear everwhere else under their original
7768 // names.
7769 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 private final StringBuilder mReadMessages = new StringBuilder();
7772
7773 private static final class PendingPackage extends PackageSettingBase {
7774 final int sharedId;
7775
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007776 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007777 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7778 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7779 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 this.sharedId = sharedId;
7781 }
7782 }
7783 private final ArrayList<PendingPackage> mPendingPackages
7784 = new ArrayList<PendingPackage>();
7785
7786 Settings() {
7787 File dataDir = Environment.getDataDirectory();
7788 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007789 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7790 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007791 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007792 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 FileUtils.setPermissions(systemDir.toString(),
7794 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7795 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7796 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007797 FileUtils.setPermissions(systemSecureDir.toString(),
7798 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7799 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7800 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 mSettingsFilename = new File(systemDir, "packages.xml");
7802 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007803 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 }
7805
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007806 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007807 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007808 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007810 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007811 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812 return p;
7813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007814
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007815 PackageSetting peekPackageLP(String name) {
7816 return mPackages.get(name);
7817 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 PackageSetting p = mPackages.get(name);
7819 if (p != null && p.codePath.getPath().equals(codePath)) {
7820 return p;
7821 }
7822 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007823 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 void setInstallStatus(String pkgName, int status) {
7827 PackageSetting p = mPackages.get(pkgName);
7828 if(p != null) {
7829 if(p.getInstallStatus() != status) {
7830 p.setInstallStatus(status);
7831 }
7832 }
7833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007834
Jacek Surazski65e13172009-04-28 15:26:38 +02007835 void setInstallerPackageName(String pkgName,
7836 String installerPkgName) {
7837 PackageSetting p = mPackages.get(pkgName);
7838 if(p != null) {
7839 p.setInstallerPackageName(installerPkgName);
7840 }
7841 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007842
Jacek Surazski65e13172009-04-28 15:26:38 +02007843 String getInstallerPackageName(String pkgName) {
7844 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007845 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007846 }
7847
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 int getInstallStatus(String pkgName) {
7849 PackageSetting p = mPackages.get(pkgName);
7850 if(p != null) {
7851 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007853 return -1;
7854 }
7855
7856 SharedUserSetting getSharedUserLP(String name,
7857 int pkgFlags, boolean create) {
7858 SharedUserSetting s = mSharedUsers.get(name);
7859 if (s == null) {
7860 if (!create) {
7861 return null;
7862 }
7863 s = new SharedUserSetting(name, pkgFlags);
7864 if (MULTIPLE_APPLICATION_UIDS) {
7865 s.userId = newUserIdLP(s);
7866 } else {
7867 s.userId = FIRST_APPLICATION_UID;
7868 }
7869 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7870 // < 0 means we couldn't assign a userid; fall out and return
7871 // s, which is currently null
7872 if (s.userId >= 0) {
7873 mSharedUsers.put(name, s);
7874 }
7875 }
7876
7877 return s;
7878 }
7879
7880 int disableSystemPackageLP(String name) {
7881 PackageSetting p = mPackages.get(name);
7882 if(p == null) {
7883 Log.w(TAG, "Package:"+name+" is not an installed package");
7884 return -1;
7885 }
7886 PackageSetting dp = mDisabledSysPackages.get(name);
7887 // always make sure the system package code and resource paths dont change
7888 if(dp == null) {
7889 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7890 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7891 }
7892 mDisabledSysPackages.put(name, p);
7893 }
7894 return removePackageLP(name);
7895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007896
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007897 PackageSetting enableSystemPackageLP(String name) {
7898 PackageSetting p = mDisabledSysPackages.get(name);
7899 if(p == null) {
7900 Log.w(TAG, "Package:"+name+" is not disabled");
7901 return null;
7902 }
7903 // Reset flag in ApplicationInfo object
7904 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7905 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7906 }
Kenny Root806cc132010-09-12 08:34:19 -07007907 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
7908 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 mDisabledSysPackages.remove(name);
7910 return ret;
7911 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007912
Kenny Root806cc132010-09-12 08:34:19 -07007913 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
7914 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007915 PackageSetting p = mPackages.get(name);
7916 if (p != null) {
7917 if (p.userId == uid) {
7918 return p;
7919 }
7920 reportSettingsProblem(Log.ERROR,
7921 "Adding duplicate package, keeping first: " + name);
7922 return null;
7923 }
Kenny Root806cc132010-09-12 08:34:19 -07007924 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
7925 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007926 p.userId = uid;
7927 if (addUserIdLP(uid, p, name)) {
7928 mPackages.put(name, p);
7929 return p;
7930 }
7931 return null;
7932 }
7933
7934 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7935 SharedUserSetting s = mSharedUsers.get(name);
7936 if (s != null) {
7937 if (s.userId == uid) {
7938 return s;
7939 }
7940 reportSettingsProblem(Log.ERROR,
7941 "Adding duplicate shared user, keeping first: " + name);
7942 return null;
7943 }
7944 s = new SharedUserSetting(name, pkgFlags);
7945 s.userId = uid;
7946 if (addUserIdLP(uid, s, name)) {
7947 mSharedUsers.put(name, s);
7948 return s;
7949 }
7950 return null;
7951 }
7952
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007953 // Transfer ownership of permissions from one package to another.
7954 private void transferPermissions(String origPkg, String newPkg) {
7955 // Transfer ownership of permissions to the new package.
7956 for (int i=0; i<2; i++) {
7957 HashMap<String, BasePermission> permissions =
7958 i == 0 ? mPermissionTrees : mPermissions;
7959 for (BasePermission bp : permissions.values()) {
7960 if (origPkg.equals(bp.sourcePackage)) {
7961 if (DEBUG_UPGRADE) Log.v(TAG,
7962 "Moving permission " + bp.name
7963 + " from pkg " + bp.sourcePackage
7964 + " to " + newPkg);
7965 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007966 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007967 bp.perm = null;
7968 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007969 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007970 }
7971 bp.uid = 0;
7972 bp.gids = null;
7973 }
7974 }
7975 }
7976 }
7977
7978 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007979 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007980 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007981 PackageSetting p = mPackages.get(name);
7982 if (p != null) {
7983 if (!p.codePath.equals(codePath)) {
7984 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007985 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007986 // This is an updated system app with versions in both system
7987 // and data partition. Just let the most recent version
7988 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007989 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007990 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007991 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007992 // Just a change in the code path is not an issue, but
7993 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007994 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007995 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007997 }
7998 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007999 reportSettingsProblem(Log.WARN,
8000 "Package " + name + " shared user changed from "
8001 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8002 + " to "
8003 + (sharedUser != null ? sharedUser.name : "<nothing>")
8004 + "; replacing with new");
8005 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008006 } else {
8007 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8008 // If what we are scanning is a system package, then
8009 // make it so, regardless of whether it was previously
8010 // installed only in the data partition.
8011 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008013 }
8014 }
8015 if (p == null) {
8016 // Create a new PackageSettings entry. this can end up here because
8017 // of code path mismatch or user id mismatch of an updated system partition
8018 if (!create) {
8019 return null;
8020 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008021 if (origPackage != null) {
8022 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008023 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8024 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008025 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8026 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008027 // Note that we will retain the new package's signature so
8028 // that we can keep its data.
8029 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008030 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008031 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008032 p.sharedUser = origPackage.sharedUser;
8033 p.userId = origPackage.userId;
8034 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008035 mRenamedPackages.put(name, origPackage.name);
8036 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008037 // Update new package state.
8038 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008039 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008040 p = new PackageSetting(name, realName, codePath, resourcePath,
8041 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008042 p.setTimeStamp(codePath.lastModified());
8043 p.sharedUser = sharedUser;
8044 if (sharedUser != null) {
8045 p.userId = sharedUser.userId;
8046 } else if (MULTIPLE_APPLICATION_UIDS) {
8047 // Clone the setting here for disabled system packages
8048 PackageSetting dis = mDisabledSysPackages.get(name);
8049 if (dis != null) {
8050 // For disabled packages a new setting is created
8051 // from the existing user id. This still has to be
8052 // added to list of user id's
8053 // Copy signatures from previous setting
8054 if (dis.signatures.mSignatures != null) {
8055 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8056 }
8057 p.userId = dis.userId;
8058 // Clone permissions
8059 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008060 // Clone component info
8061 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8062 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8063 // Add new setting to list of user ids
8064 addUserIdLP(p.userId, p, name);
8065 } else {
8066 // Assign new user id
8067 p.userId = newUserIdLP(p);
8068 }
8069 } else {
8070 p.userId = FIRST_APPLICATION_UID;
8071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008072 }
8073 if (p.userId < 0) {
8074 reportSettingsProblem(Log.WARN,
8075 "Package " + name + " could not be assigned a valid uid");
8076 return null;
8077 }
8078 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008079 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008080 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008081 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 }
8083 }
8084 return p;
8085 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008086
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008087 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008088 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008089 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008090 final String codePath = pkg.applicationInfo.sourceDir;
8091 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008092 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008093 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008094 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008095 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008096 p.codePath = new File(codePath);
8097 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008098 }
8099 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008100 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008101 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008102 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008103 p.resourcePath = new File(resourcePath);
8104 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008105 }
Kenny Root85387d72010-08-26 10:13:11 -07008106 // Update the native library path if needed
8107 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8108 if (nativeLibraryPath != null
8109 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8110 p.nativeLibraryPathString = nativeLibraryPath;
8111 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008112 // Update version code if needed
8113 if (pkg.mVersionCode != p.versionCode) {
8114 p.versionCode = pkg.mVersionCode;
8115 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008116 // Update signatures if needed.
8117 if (p.signatures.mSignatures == null) {
8118 p.signatures.assignSignatures(pkg.mSignatures);
8119 }
8120 // If this app defines a shared user id initialize
8121 // the shared user signatures as well.
8122 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8123 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8124 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008125 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8126 }
8127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008128 // Utility method that adds a PackageSetting to mPackages and
8129 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008130 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008131 SharedUserSetting sharedUser) {
8132 mPackages.put(name, p);
8133 if (sharedUser != null) {
8134 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8135 reportSettingsProblem(Log.ERROR,
8136 "Package " + p.name + " was user "
8137 + p.sharedUser + " but is now " + sharedUser
8138 + "; I am not changing its files so it will probably fail!");
8139 p.sharedUser.packages.remove(p);
8140 } else if (p.userId != sharedUser.userId) {
8141 reportSettingsProblem(Log.ERROR,
8142 "Package " + p.name + " was user id " + p.userId
8143 + " but is now user " + sharedUser
8144 + " with id " + sharedUser.userId
8145 + "; I am not changing its files so it will probably fail!");
8146 }
8147
8148 sharedUser.packages.add(p);
8149 p.sharedUser = sharedUser;
8150 p.userId = sharedUser.userId;
8151 }
8152 }
8153
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008154 /*
8155 * Update the shared user setting when a package using
8156 * specifying the shared user id is removed. The gids
8157 * associated with each permission of the deleted package
8158 * are removed from the shared user's gid list only if its
8159 * not in use by other permissions of packages in the
8160 * shared user setting.
8161 */
8162 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008163 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008164 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 return;
8166 }
8167 // No sharedUserId
8168 if (deletedPs.sharedUser == null) {
8169 return;
8170 }
8171 SharedUserSetting sus = deletedPs.sharedUser;
8172 // Update permissions
8173 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8174 boolean used = false;
8175 if (!sus.grantedPermissions.contains (eachPerm)) {
8176 continue;
8177 }
8178 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008179 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008180 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008181 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 used = true;
8183 break;
8184 }
8185 }
8186 if (!used) {
8187 // can safely delete this permission from list
8188 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008189 }
8190 }
8191 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008192 int newGids[] = globalGids;
8193 for (String eachPerm : sus.grantedPermissions) {
8194 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008195 if (bp != null) {
8196 newGids = appendInts(newGids, bp.gids);
8197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008198 }
8199 sus.gids = newGids;
8200 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008202 private int removePackageLP(String name) {
8203 PackageSetting p = mPackages.get(name);
8204 if (p != null) {
8205 mPackages.remove(name);
8206 if (p.sharedUser != null) {
8207 p.sharedUser.packages.remove(p);
8208 if (p.sharedUser.packages.size() == 0) {
8209 mSharedUsers.remove(p.sharedUser.name);
8210 removeUserIdLP(p.sharedUser.userId);
8211 return p.sharedUser.userId;
8212 }
8213 } else {
8214 removeUserIdLP(p.userId);
8215 return p.userId;
8216 }
8217 }
8218 return -1;
8219 }
8220
8221 private boolean addUserIdLP(int uid, Object obj, Object name) {
8222 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8223 return false;
8224 }
8225
8226 if (uid >= FIRST_APPLICATION_UID) {
8227 int N = mUserIds.size();
8228 final int index = uid - FIRST_APPLICATION_UID;
8229 while (index >= N) {
8230 mUserIds.add(null);
8231 N++;
8232 }
8233 if (mUserIds.get(index) != null) {
8234 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008235 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008236 + " name=" + name);
8237 return false;
8238 }
8239 mUserIds.set(index, obj);
8240 } else {
8241 if (mOtherUserIds.get(uid) != null) {
8242 reportSettingsProblem(Log.ERROR,
8243 "Adding duplicate shared id: " + uid
8244 + " name=" + name);
8245 return false;
8246 }
8247 mOtherUserIds.put(uid, obj);
8248 }
8249 return true;
8250 }
8251
8252 public Object getUserIdLP(int uid) {
8253 if (uid >= FIRST_APPLICATION_UID) {
8254 int N = mUserIds.size();
8255 final int index = uid - FIRST_APPLICATION_UID;
8256 return index < N ? mUserIds.get(index) : null;
8257 } else {
8258 return mOtherUserIds.get(uid);
8259 }
8260 }
8261
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008262 private Set<String> findPackagesWithFlag(int flag) {
8263 Set<String> ret = new HashSet<String>();
8264 for (PackageSetting ps : mPackages.values()) {
8265 // Has to match atleast all the flag bits set on flag
8266 if ((ps.pkgFlags & flag) == flag) {
8267 ret.add(ps.name);
8268 }
8269 }
8270 return ret;
8271 }
8272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008273 private void removeUserIdLP(int uid) {
8274 if (uid >= FIRST_APPLICATION_UID) {
8275 int N = mUserIds.size();
8276 final int index = uid - FIRST_APPLICATION_UID;
8277 if (index < N) mUserIds.set(index, null);
8278 } else {
8279 mOtherUserIds.remove(uid);
8280 }
8281 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008282
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 void writeLP() {
8284 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8285
8286 // Keep the old settings around until we know the new ones have
8287 // been successfully written.
8288 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008289 // Presence of backup settings file indicates that we failed
8290 // to persist settings earlier. So preserve the older
8291 // backup for future reference since the current settings
8292 // might have been corrupted.
8293 if (!mBackupSettingsFilename.exists()) {
8294 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008295 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008296 return;
8297 }
8298 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008299 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008300 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008301 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 }
8303
8304 mPastSignatures.clear();
8305
8306 try {
8307 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8308
8309 //XmlSerializer serializer = XmlUtils.serializerInstance();
8310 XmlSerializer serializer = new FastXmlSerializer();
8311 serializer.setOutput(str, "utf-8");
8312 serializer.startDocument(null, true);
8313 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8314
8315 serializer.startTag(null, "packages");
8316
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008317 serializer.startTag(null, "last-platform-version");
8318 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8319 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8320 serializer.endTag(null, "last-platform-version");
8321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008322 serializer.startTag(null, "permission-trees");
8323 for (BasePermission bp : mPermissionTrees.values()) {
8324 writePermission(serializer, bp);
8325 }
8326 serializer.endTag(null, "permission-trees");
8327
8328 serializer.startTag(null, "permissions");
8329 for (BasePermission bp : mPermissions.values()) {
8330 writePermission(serializer, bp);
8331 }
8332 serializer.endTag(null, "permissions");
8333
8334 for (PackageSetting pkg : mPackages.values()) {
8335 writePackage(serializer, pkg);
8336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8339 writeDisabledSysPackage(serializer, pkg);
8340 }
8341
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008342 serializer.startTag(null, "preferred-activities");
8343 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8344 serializer.startTag(null, "item");
8345 pa.writeToXml(serializer);
8346 serializer.endTag(null, "item");
8347 }
8348 serializer.endTag(null, "preferred-activities");
8349
8350 for (SharedUserSetting usr : mSharedUsers.values()) {
8351 serializer.startTag(null, "shared-user");
8352 serializer.attribute(null, "name", usr.name);
8353 serializer.attribute(null, "userId",
8354 Integer.toString(usr.userId));
8355 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8356 serializer.startTag(null, "perms");
8357 for (String name : usr.grantedPermissions) {
8358 serializer.startTag(null, "item");
8359 serializer.attribute(null, "name", name);
8360 serializer.endTag(null, "item");
8361 }
8362 serializer.endTag(null, "perms");
8363 serializer.endTag(null, "shared-user");
8364 }
8365
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008366 if (mPackagesToBeCleaned.size() > 0) {
8367 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8368 serializer.startTag(null, "cleaning-package");
8369 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8370 serializer.endTag(null, "cleaning-package");
8371 }
8372 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008373
8374 if (mRenamedPackages.size() > 0) {
8375 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8376 serializer.startTag(null, "renamed-package");
8377 serializer.attribute(null, "new", e.getKey());
8378 serializer.attribute(null, "old", e.getValue());
8379 serializer.endTag(null, "renamed-package");
8380 }
8381 }
8382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008383 serializer.endTag(null, "packages");
8384
8385 serializer.endDocument();
8386
8387 str.flush();
8388 str.close();
8389
8390 // New settings successfully written, old ones are no longer
8391 // needed.
8392 mBackupSettingsFilename.delete();
8393 FileUtils.setPermissions(mSettingsFilename.toString(),
8394 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8395 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8396 |FileUtils.S_IROTH,
8397 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008398
8399 // Write package list file now, use a JournaledFile.
8400 //
8401 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8402 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8403
8404 str = new FileOutputStream(journal.chooseForWrite());
8405 try {
8406 StringBuilder sb = new StringBuilder();
8407 for (PackageSetting pkg : mPackages.values()) {
8408 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008409 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008410 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8411
8412 // Avoid any application that has a space in its path
8413 // or that is handled by the system.
8414 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8415 continue;
8416
8417 // we store on each line the following information for now:
8418 //
8419 // pkgName - package name
8420 // userId - application-specific user id
8421 // debugFlag - 0 or 1 if the package is debuggable.
8422 // dataPath - path to package's data path
8423 //
8424 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8425 //
8426 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8427 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8428 // system/core/run-as/run-as.c
8429 //
8430 sb.setLength(0);
8431 sb.append(ai.packageName);
8432 sb.append(" ");
8433 sb.append((int)ai.uid);
8434 sb.append(isDebug ? " 1 " : " 0 ");
8435 sb.append(dataPath);
8436 sb.append("\n");
8437 str.write(sb.toString().getBytes());
8438 }
8439 str.flush();
8440 str.close();
8441 journal.commit();
8442 }
8443 catch (Exception e) {
8444 journal.rollback();
8445 }
8446
8447 FileUtils.setPermissions(mPackageListFilename.toString(),
8448 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8449 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8450 |FileUtils.S_IROTH,
8451 -1, -1);
8452
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008453 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008454
8455 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008456 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 -08008457 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008458 Slog.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008459 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008460 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008461 if (mSettingsFilename.exists()) {
8462 if (!mSettingsFilename.delete()) {
8463 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8464 }
8465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 //Debug.stopMethodTracing();
8467 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008468
8469 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008470 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008471 serializer.startTag(null, "updated-package");
8472 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008473 if (pkg.realName != null) {
8474 serializer.attribute(null, "realName", pkg.realName);
8475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 serializer.attribute(null, "codePath", pkg.codePathString);
Kenny Root7d794fb2010-09-13 16:29:49 -07008477 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008478 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008479 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8480 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8481 }
Kenny Root85387d72010-08-26 10:13:11 -07008482 if (pkg.nativeLibraryPathString != null) {
8483 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008485 if (pkg.sharedUser == null) {
8486 serializer.attribute(null, "userId",
8487 Integer.toString(pkg.userId));
8488 } else {
8489 serializer.attribute(null, "sharedUserId",
8490 Integer.toString(pkg.userId));
8491 }
8492 serializer.startTag(null, "perms");
8493 if (pkg.sharedUser == null) {
8494 // If this is a shared user, the permissions will
8495 // be written there. We still need to write an
8496 // empty permissions list so permissionsFixed will
8497 // be set.
8498 for (final String name : pkg.grantedPermissions) {
8499 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008500 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008501 // We only need to write signature or system permissions but this wont
8502 // match the semantics of grantedPermissions. So write all permissions.
8503 serializer.startTag(null, "item");
8504 serializer.attribute(null, "name", name);
8505 serializer.endTag(null, "item");
8506 }
8507 }
8508 }
8509 serializer.endTag(null, "perms");
8510 serializer.endTag(null, "updated-package");
8511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008512
8513 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008514 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008515 serializer.startTag(null, "package");
8516 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008517 if (pkg.realName != null) {
8518 serializer.attribute(null, "realName", pkg.realName);
8519 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008520 serializer.attribute(null, "codePath", pkg.codePathString);
8521 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8522 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8523 }
Kenny Root85387d72010-08-26 10:13:11 -07008524 if (pkg.nativeLibraryPathString != null) {
8525 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8526 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008527 serializer.attribute(null, "flags",
8528 Integer.toString(pkg.pkgFlags));
Kenny Root7d794fb2010-09-13 16:29:49 -07008529 serializer.attribute(null, "ts", String.valueOf(pkg.timeStamp));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008530 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 if (pkg.sharedUser == null) {
8532 serializer.attribute(null, "userId",
8533 Integer.toString(pkg.userId));
8534 } else {
8535 serializer.attribute(null, "sharedUserId",
8536 Integer.toString(pkg.userId));
8537 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008538 if (pkg.uidError) {
8539 serializer.attribute(null, "uidError", "true");
8540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008541 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8542 serializer.attribute(null, "enabled",
8543 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8544 ? "true" : "false");
8545 }
8546 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8547 serializer.attribute(null, "installStatus", "false");
8548 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008549 if (pkg.installerPackageName != null) {
8550 serializer.attribute(null, "installer", pkg.installerPackageName);
8551 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008552 if (pkg.obbPathString != null) {
8553 serializer.attribute(null, "obbPath", pkg.obbPathString);
8554 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008555 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8556 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8557 serializer.startTag(null, "perms");
8558 if (pkg.sharedUser == null) {
8559 // If this is a shared user, the permissions will
8560 // be written there. We still need to write an
8561 // empty permissions list so permissionsFixed will
8562 // be set.
8563 for (final String name : pkg.grantedPermissions) {
8564 serializer.startTag(null, "item");
8565 serializer.attribute(null, "name", name);
8566 serializer.endTag(null, "item");
8567 }
8568 }
8569 serializer.endTag(null, "perms");
8570 }
8571 if (pkg.disabledComponents.size() > 0) {
8572 serializer.startTag(null, "disabled-components");
8573 for (final String name : pkg.disabledComponents) {
8574 serializer.startTag(null, "item");
8575 serializer.attribute(null, "name", name);
8576 serializer.endTag(null, "item");
8577 }
8578 serializer.endTag(null, "disabled-components");
8579 }
8580 if (pkg.enabledComponents.size() > 0) {
8581 serializer.startTag(null, "enabled-components");
8582 for (final String name : pkg.enabledComponents) {
8583 serializer.startTag(null, "item");
8584 serializer.attribute(null, "name", name);
8585 serializer.endTag(null, "item");
8586 }
8587 serializer.endTag(null, "enabled-components");
8588 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 serializer.endTag(null, "package");
8591 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008592
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008593 void writePermission(XmlSerializer serializer, BasePermission bp)
8594 throws XmlPullParserException, java.io.IOException {
8595 if (bp.type != BasePermission.TYPE_BUILTIN
8596 && bp.sourcePackage != null) {
8597 serializer.startTag(null, "item");
8598 serializer.attribute(null, "name", bp.name);
8599 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008600 if (bp.protectionLevel !=
8601 PermissionInfo.PROTECTION_NORMAL) {
8602 serializer.attribute(null, "protection",
8603 Integer.toString(bp.protectionLevel));
8604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008605 if (DEBUG_SETTINGS) Log.v(TAG,
8606 "Writing perm: name=" + bp.name + " type=" + bp.type);
8607 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8608 PermissionInfo pi = bp.perm != null ? bp.perm.info
8609 : bp.pendingInfo;
8610 if (pi != null) {
8611 serializer.attribute(null, "type", "dynamic");
8612 if (pi.icon != 0) {
8613 serializer.attribute(null, "icon",
8614 Integer.toString(pi.icon));
8615 }
8616 if (pi.nonLocalizedLabel != null) {
8617 serializer.attribute(null, "label",
8618 pi.nonLocalizedLabel.toString());
8619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008620 }
8621 }
8622 serializer.endTag(null, "item");
8623 }
8624 }
8625
8626 String getReadMessagesLP() {
8627 return mReadMessages.toString();
8628 }
8629
Oscar Montemayora8529f62009-11-18 10:14:20 -08008630 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008631 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8632 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008633 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008634 while(its.hasNext()) {
8635 String key = its.next();
8636 PackageSetting ps = mPackages.get(key);
8637 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008638 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639 }
8640 }
8641 return ret;
8642 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008643
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 boolean readLP() {
8645 FileInputStream str = null;
8646 if (mBackupSettingsFilename.exists()) {
8647 try {
8648 str = new FileInputStream(mBackupSettingsFilename);
8649 mReadMessages.append("Reading from backup settings file\n");
8650 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008651 if (mSettingsFilename.exists()) {
8652 // If both the backup and settings file exist, we
8653 // ignore the settings since it might have been
8654 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008655 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008656 mSettingsFilename.delete();
8657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658 } catch (java.io.IOException e) {
8659 // We'll try for the normal settings file.
8660 }
8661 }
8662
8663 mPastSignatures.clear();
8664
8665 try {
8666 if (str == null) {
8667 if (!mSettingsFilename.exists()) {
8668 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008669 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008670 return false;
8671 }
8672 str = new FileInputStream(mSettingsFilename);
8673 }
8674 XmlPullParser parser = Xml.newPullParser();
8675 parser.setInput(str, null);
8676
8677 int type;
8678 while ((type=parser.next()) != XmlPullParser.START_TAG
8679 && type != XmlPullParser.END_DOCUMENT) {
8680 ;
8681 }
8682
8683 if (type != XmlPullParser.START_TAG) {
8684 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008685 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008686 return false;
8687 }
8688
8689 int outerDepth = parser.getDepth();
8690 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8691 && (type != XmlPullParser.END_TAG
8692 || parser.getDepth() > outerDepth)) {
8693 if (type == XmlPullParser.END_TAG
8694 || type == XmlPullParser.TEXT) {
8695 continue;
8696 }
8697
8698 String tagName = parser.getName();
8699 if (tagName.equals("package")) {
8700 readPackageLP(parser);
8701 } else if (tagName.equals("permissions")) {
8702 readPermissionsLP(mPermissions, parser);
8703 } else if (tagName.equals("permission-trees")) {
8704 readPermissionsLP(mPermissionTrees, parser);
8705 } else if (tagName.equals("shared-user")) {
8706 readSharedUserLP(parser);
8707 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008708 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 } else if (tagName.equals("preferred-activities")) {
8710 readPreferredActivitiesLP(parser);
8711 } else if(tagName.equals("updated-package")) {
8712 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008713 } else if (tagName.equals("cleaning-package")) {
8714 String name = parser.getAttributeValue(null, "name");
8715 if (name != null) {
8716 mPackagesToBeCleaned.add(name);
8717 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008718 } else if (tagName.equals("renamed-package")) {
8719 String nname = parser.getAttributeValue(null, "new");
8720 String oname = parser.getAttributeValue(null, "old");
8721 if (nname != null && oname != null) {
8722 mRenamedPackages.put(nname, oname);
8723 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008724 } else if (tagName.equals("last-platform-version")) {
8725 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8726 try {
8727 String internal = parser.getAttributeValue(null, "internal");
8728 if (internal != null) {
8729 mInternalSdkPlatform = Integer.parseInt(internal);
8730 }
8731 String external = parser.getAttributeValue(null, "external");
8732 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008733 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008734 }
8735 } catch (NumberFormatException e) {
8736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008737 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008738 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 + parser.getName());
8740 XmlUtils.skipCurrentTag(parser);
8741 }
8742 }
8743
8744 str.close();
8745
8746 } catch(XmlPullParserException e) {
8747 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008748 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008749
8750 } catch(java.io.IOException e) {
8751 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008752 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008753
8754 }
8755
8756 int N = mPendingPackages.size();
8757 for (int i=0; i<N; i++) {
8758 final PendingPackage pp = mPendingPackages.get(i);
8759 Object idObj = getUserIdLP(pp.sharedId);
8760 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008761 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008762 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8763 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008764 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008765 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 + pp.name);
8767 continue;
8768 }
8769 p.copyFrom(pp);
8770 } else if (idObj != null) {
8771 String msg = "Bad package setting: package " + pp.name
8772 + " has shared uid " + pp.sharedId
8773 + " that is not a shared uid\n";
8774 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008775 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776 } else {
8777 String msg = "Bad package setting: package " + pp.name
8778 + " has shared uid " + pp.sharedId
8779 + " that is not defined\n";
8780 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008781 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 }
8783 }
8784 mPendingPackages.clear();
8785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786 mReadMessages.append("Read completed successfully: "
8787 + mPackages.size() + " packages, "
8788 + mSharedUsers.size() + " shared uids\n");
8789
8790 return true;
8791 }
8792
8793 private int readInt(XmlPullParser parser, String ns, String name,
8794 int defValue) {
8795 String v = parser.getAttributeValue(ns, name);
8796 try {
8797 if (v == null) {
8798 return defValue;
8799 }
8800 return Integer.parseInt(v);
8801 } catch (NumberFormatException e) {
8802 reportSettingsProblem(Log.WARN,
8803 "Error in package manager settings: attribute " +
8804 name + " has bad integer value " + v + " at "
8805 + parser.getPositionDescription());
8806 }
8807 return defValue;
8808 }
8809
8810 private void readPermissionsLP(HashMap<String, BasePermission> out,
8811 XmlPullParser parser)
8812 throws IOException, XmlPullParserException {
8813 int outerDepth = parser.getDepth();
8814 int type;
8815 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8816 && (type != XmlPullParser.END_TAG
8817 || parser.getDepth() > outerDepth)) {
8818 if (type == XmlPullParser.END_TAG
8819 || type == XmlPullParser.TEXT) {
8820 continue;
8821 }
8822
8823 String tagName = parser.getName();
8824 if (tagName.equals("item")) {
8825 String name = parser.getAttributeValue(null, "name");
8826 String sourcePackage = parser.getAttributeValue(null, "package");
8827 String ptype = parser.getAttributeValue(null, "type");
8828 if (name != null && sourcePackage != null) {
8829 boolean dynamic = "dynamic".equals(ptype);
8830 BasePermission bp = new BasePermission(name, sourcePackage,
8831 dynamic
8832 ? BasePermission.TYPE_DYNAMIC
8833 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008834 bp.protectionLevel = readInt(parser, null, "protection",
8835 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 if (dynamic) {
8837 PermissionInfo pi = new PermissionInfo();
8838 pi.packageName = sourcePackage.intern();
8839 pi.name = name.intern();
8840 pi.icon = readInt(parser, null, "icon", 0);
8841 pi.nonLocalizedLabel = parser.getAttributeValue(
8842 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008843 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008844 bp.pendingInfo = pi;
8845 }
8846 out.put(bp.name, bp);
8847 } else {
8848 reportSettingsProblem(Log.WARN,
8849 "Error in package manager settings: permissions has"
8850 + " no name at " + parser.getPositionDescription());
8851 }
8852 } else {
8853 reportSettingsProblem(Log.WARN,
8854 "Unknown element reading permissions: "
8855 + parser.getName() + " at "
8856 + parser.getPositionDescription());
8857 }
8858 XmlUtils.skipCurrentTag(parser);
8859 }
8860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008862 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008863 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008865 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 String codePathStr = parser.getAttributeValue(null, "codePath");
8867 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07008868 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008869 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 resourcePathStr = codePathStr;
8871 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008872 String version = parser.getAttributeValue(null, "version");
8873 int versionCode = 0;
8874 if (version != null) {
8875 try {
8876 versionCode = Integer.parseInt(version);
8877 } catch (NumberFormatException e) {
8878 }
8879 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008881 int pkgFlags = 0;
8882 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07008883 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
8884 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 String timeStampStr = parser.getAttributeValue(null, "ts");
8886 if (timeStampStr != null) {
8887 try {
8888 long timeStamp = Long.parseLong(timeStampStr);
Kenny Root7d794fb2010-09-13 16:29:49 -07008889 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008890 } catch (NumberFormatException e) {
8891 }
8892 }
8893 String idStr = parser.getAttributeValue(null, "userId");
8894 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8895 if(ps.userId <= 0) {
8896 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8897 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8898 }
8899 int outerDepth = parser.getDepth();
8900 int type;
8901 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8902 && (type != XmlPullParser.END_TAG
8903 || parser.getDepth() > outerDepth)) {
8904 if (type == XmlPullParser.END_TAG
8905 || type == XmlPullParser.TEXT) {
8906 continue;
8907 }
8908
8909 String tagName = parser.getName();
8910 if (tagName.equals("perms")) {
8911 readGrantedPermissionsLP(parser,
8912 ps.grantedPermissions);
8913 } else {
8914 reportSettingsProblem(Log.WARN,
8915 "Unknown element under <updated-package>: "
8916 + parser.getName());
8917 XmlUtils.skipCurrentTag(parser);
8918 }
8919 }
8920 mDisabledSysPackages.put(name, ps);
8921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008923 private void readPackageLP(XmlPullParser parser)
8924 throws XmlPullParserException, IOException {
8925 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008926 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008927 String idStr = null;
8928 String sharedIdStr = null;
8929 String codePathStr = null;
8930 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07008931 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07008932 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008934 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008935 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008936 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008937 long timeStamp = 0;
8938 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008939 String version = null;
8940 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008941 try {
8942 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008943 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008945 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8947 codePathStr = parser.getAttributeValue(null, "codePath");
8948 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07008949 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07008950 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008951 version = parser.getAttributeValue(null, "version");
8952 if (version != null) {
8953 try {
8954 versionCode = Integer.parseInt(version);
8955 } catch (NumberFormatException e) {
8956 }
8957 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008958 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008959
8960 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008962 try {
8963 pkgFlags = Integer.parseInt(systemStr);
8964 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 }
8966 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008967 // For backward compatibility
8968 systemStr = parser.getAttributeValue(null, "system");
8969 if (systemStr != null) {
8970 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8971 } else {
8972 // Old settings that don't specify system... just treat
8973 // them as system, good enough.
8974 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008976 }
Kenny Root7d794fb2010-09-13 16:29:49 -07008977 final String timeStampStr = parser.getAttributeValue(null, "ts");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008978 if (timeStampStr != null) {
8979 try {
8980 timeStamp = Long.parseLong(timeStampStr);
8981 } catch (NumberFormatException e) {
8982 }
8983 }
8984 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8985 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8986 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8987 if (resourcePathStr == null) {
8988 resourcePathStr = codePathStr;
8989 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008990 if (realName != null) {
8991 realName = realName.intern();
8992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008993 if (name == null) {
8994 reportSettingsProblem(Log.WARN,
8995 "Error in package manager settings: <package> has no name at "
8996 + parser.getPositionDescription());
8997 } else if (codePathStr == null) {
8998 reportSettingsProblem(Log.WARN,
8999 "Error in package manager settings: <package> has no codePath at "
9000 + parser.getPositionDescription());
9001 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009002 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9003 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9004 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009005 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9006 + ": userId=" + userId + " pkg=" + packageSetting);
9007 if (packageSetting == null) {
9008 reportSettingsProblem(Log.ERROR,
9009 "Failure adding uid " + userId
9010 + " while parsing settings at "
9011 + parser.getPositionDescription());
9012 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009013 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009014 }
9015 } else if (sharedIdStr != null) {
9016 userId = sharedIdStr != null
9017 ? Integer.parseInt(sharedIdStr) : 0;
9018 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009019 packageSetting = new PendingPackage(name.intern(), realName,
9020 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009021 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009022 packageSetting.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 mPendingPackages.add((PendingPackage) packageSetting);
9024 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9025 + ": sharedUserId=" + userId + " pkg="
9026 + packageSetting);
9027 } else {
9028 reportSettingsProblem(Log.WARN,
9029 "Error in package manager settings: package "
9030 + name + " has bad sharedId " + sharedIdStr
9031 + " at " + parser.getPositionDescription());
9032 }
9033 } else {
9034 reportSettingsProblem(Log.WARN,
9035 "Error in package manager settings: package "
9036 + name + " has bad userId " + idStr + " at "
9037 + parser.getPositionDescription());
9038 }
9039 } catch (NumberFormatException e) {
9040 reportSettingsProblem(Log.WARN,
9041 "Error in package manager settings: package "
9042 + name + " has bad userId " + idStr + " at "
9043 + parser.getPositionDescription());
9044 }
9045 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009046 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009047 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009048 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009049 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050 final String enabledStr = parser.getAttributeValue(null, "enabled");
9051 if (enabledStr != null) {
9052 if (enabledStr.equalsIgnoreCase("true")) {
9053 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9054 } else if (enabledStr.equalsIgnoreCase("false")) {
9055 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9056 } else if (enabledStr.equalsIgnoreCase("default")) {
9057 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9058 } else {
9059 reportSettingsProblem(Log.WARN,
9060 "Error in package manager settings: package "
9061 + name + " has bad enabled value: " + idStr
9062 + " at " + parser.getPositionDescription());
9063 }
9064 } else {
9065 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9066 }
9067 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9068 if (installStatusStr != null) {
9069 if (installStatusStr.equalsIgnoreCase("false")) {
9070 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9071 } else {
9072 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9073 }
9074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009076 int outerDepth = parser.getDepth();
9077 int type;
9078 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9079 && (type != XmlPullParser.END_TAG
9080 || parser.getDepth() > outerDepth)) {
9081 if (type == XmlPullParser.END_TAG
9082 || type == XmlPullParser.TEXT) {
9083 continue;
9084 }
9085
9086 String tagName = parser.getName();
9087 if (tagName.equals("disabled-components")) {
9088 readDisabledComponentsLP(packageSetting, parser);
9089 } else if (tagName.equals("enabled-components")) {
9090 readEnabledComponentsLP(packageSetting, parser);
9091 } else if (tagName.equals("sigs")) {
9092 packageSetting.signatures.readXml(parser, mPastSignatures);
9093 } else if (tagName.equals("perms")) {
9094 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009095 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 packageSetting.permissionsFixed = true;
9097 } else {
9098 reportSettingsProblem(Log.WARN,
9099 "Unknown element under <package>: "
9100 + parser.getName());
9101 XmlUtils.skipCurrentTag(parser);
9102 }
9103 }
9104 } else {
9105 XmlUtils.skipCurrentTag(parser);
9106 }
9107 }
9108
9109 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9110 XmlPullParser parser)
9111 throws IOException, XmlPullParserException {
9112 int outerDepth = parser.getDepth();
9113 int type;
9114 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9115 && (type != XmlPullParser.END_TAG
9116 || parser.getDepth() > outerDepth)) {
9117 if (type == XmlPullParser.END_TAG
9118 || type == XmlPullParser.TEXT) {
9119 continue;
9120 }
9121
9122 String tagName = parser.getName();
9123 if (tagName.equals("item")) {
9124 String name = parser.getAttributeValue(null, "name");
9125 if (name != null) {
9126 packageSetting.disabledComponents.add(name.intern());
9127 } else {
9128 reportSettingsProblem(Log.WARN,
9129 "Error in package manager settings: <disabled-components> has"
9130 + " no name at " + parser.getPositionDescription());
9131 }
9132 } else {
9133 reportSettingsProblem(Log.WARN,
9134 "Unknown element under <disabled-components>: "
9135 + parser.getName());
9136 }
9137 XmlUtils.skipCurrentTag(parser);
9138 }
9139 }
9140
9141 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9142 XmlPullParser parser)
9143 throws IOException, XmlPullParserException {
9144 int outerDepth = parser.getDepth();
9145 int type;
9146 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9147 && (type != XmlPullParser.END_TAG
9148 || parser.getDepth() > outerDepth)) {
9149 if (type == XmlPullParser.END_TAG
9150 || type == XmlPullParser.TEXT) {
9151 continue;
9152 }
9153
9154 String tagName = parser.getName();
9155 if (tagName.equals("item")) {
9156 String name = parser.getAttributeValue(null, "name");
9157 if (name != null) {
9158 packageSetting.enabledComponents.add(name.intern());
9159 } else {
9160 reportSettingsProblem(Log.WARN,
9161 "Error in package manager settings: <enabled-components> has"
9162 + " no name at " + parser.getPositionDescription());
9163 }
9164 } else {
9165 reportSettingsProblem(Log.WARN,
9166 "Unknown element under <enabled-components>: "
9167 + parser.getName());
9168 }
9169 XmlUtils.skipCurrentTag(parser);
9170 }
9171 }
9172
9173 private void readSharedUserLP(XmlPullParser parser)
9174 throws XmlPullParserException, IOException {
9175 String name = null;
9176 String idStr = null;
9177 int pkgFlags = 0;
9178 SharedUserSetting su = null;
9179 try {
9180 name = parser.getAttributeValue(null, "name");
9181 idStr = parser.getAttributeValue(null, "userId");
9182 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9183 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9184 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9185 }
9186 if (name == null) {
9187 reportSettingsProblem(Log.WARN,
9188 "Error in package manager settings: <shared-user> has no name at "
9189 + parser.getPositionDescription());
9190 } else if (userId == 0) {
9191 reportSettingsProblem(Log.WARN,
9192 "Error in package manager settings: shared-user "
9193 + name + " has bad userId " + idStr + " at "
9194 + parser.getPositionDescription());
9195 } else {
9196 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9197 reportSettingsProblem(Log.ERROR,
9198 "Occurred while parsing settings at "
9199 + parser.getPositionDescription());
9200 }
9201 }
9202 } catch (NumberFormatException e) {
9203 reportSettingsProblem(Log.WARN,
9204 "Error in package manager settings: package "
9205 + name + " has bad userId " + idStr + " at "
9206 + parser.getPositionDescription());
9207 };
9208
9209 if (su != null) {
9210 int outerDepth = parser.getDepth();
9211 int type;
9212 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9213 && (type != XmlPullParser.END_TAG
9214 || parser.getDepth() > outerDepth)) {
9215 if (type == XmlPullParser.END_TAG
9216 || type == XmlPullParser.TEXT) {
9217 continue;
9218 }
9219
9220 String tagName = parser.getName();
9221 if (tagName.equals("sigs")) {
9222 su.signatures.readXml(parser, mPastSignatures);
9223 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009224 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009225 } else {
9226 reportSettingsProblem(Log.WARN,
9227 "Unknown element under <shared-user>: "
9228 + parser.getName());
9229 XmlUtils.skipCurrentTag(parser);
9230 }
9231 }
9232
9233 } else {
9234 XmlUtils.skipCurrentTag(parser);
9235 }
9236 }
9237
9238 private void readGrantedPermissionsLP(XmlPullParser parser,
9239 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9240 int outerDepth = parser.getDepth();
9241 int type;
9242 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9243 && (type != XmlPullParser.END_TAG
9244 || parser.getDepth() > outerDepth)) {
9245 if (type == XmlPullParser.END_TAG
9246 || type == XmlPullParser.TEXT) {
9247 continue;
9248 }
9249
9250 String tagName = parser.getName();
9251 if (tagName.equals("item")) {
9252 String name = parser.getAttributeValue(null, "name");
9253 if (name != null) {
9254 outPerms.add(name.intern());
9255 } else {
9256 reportSettingsProblem(Log.WARN,
9257 "Error in package manager settings: <perms> has"
9258 + " no name at " + parser.getPositionDescription());
9259 }
9260 } else {
9261 reportSettingsProblem(Log.WARN,
9262 "Unknown element under <perms>: "
9263 + parser.getName());
9264 }
9265 XmlUtils.skipCurrentTag(parser);
9266 }
9267 }
9268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009269 private void readPreferredActivitiesLP(XmlPullParser parser)
9270 throws XmlPullParserException, IOException {
9271 int outerDepth = parser.getDepth();
9272 int type;
9273 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9274 && (type != XmlPullParser.END_TAG
9275 || parser.getDepth() > outerDepth)) {
9276 if (type == XmlPullParser.END_TAG
9277 || type == XmlPullParser.TEXT) {
9278 continue;
9279 }
9280
9281 String tagName = parser.getName();
9282 if (tagName.equals("item")) {
9283 PreferredActivity pa = new PreferredActivity(parser);
9284 if (pa.mParseError == null) {
9285 mPreferredActivities.addFilter(pa);
9286 } else {
9287 reportSettingsProblem(Log.WARN,
9288 "Error in package manager settings: <preferred-activity> "
9289 + pa.mParseError + " at "
9290 + parser.getPositionDescription());
9291 }
9292 } else {
9293 reportSettingsProblem(Log.WARN,
9294 "Unknown element under <preferred-activities>: "
9295 + parser.getName());
9296 XmlUtils.skipCurrentTag(parser);
9297 }
9298 }
9299 }
9300
9301 // Returns -1 if we could not find an available UserId to assign
9302 private int newUserIdLP(Object obj) {
9303 // Let's be stupidly inefficient for now...
9304 final int N = mUserIds.size();
9305 for (int i=0; i<N; i++) {
9306 if (mUserIds.get(i) == null) {
9307 mUserIds.set(i, obj);
9308 return FIRST_APPLICATION_UID + i;
9309 }
9310 }
9311
9312 // None left?
9313 if (N >= MAX_APPLICATION_UIDS) {
9314 return -1;
9315 }
9316
9317 mUserIds.add(obj);
9318 return FIRST_APPLICATION_UID + N;
9319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009321 public PackageSetting getDisabledSystemPkg(String name) {
9322 synchronized(mPackages) {
9323 PackageSetting ps = mDisabledSysPackages.get(name);
9324 return ps;
9325 }
9326 }
9327
9328 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009329 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9330 return true;
9331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009332 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9333 if (Config.LOGV) {
9334 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9335 + " componentName = " + componentInfo.name);
9336 Log.v(TAG, "enabledComponents: "
9337 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9338 Log.v(TAG, "disabledComponents: "
9339 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9340 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009341 if (packageSettings == null) {
9342 if (false) {
9343 Log.w(TAG, "WAITING FOR DEBUGGER");
9344 Debug.waitForDebugger();
9345 Log.i(TAG, "We will crash!");
9346 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009347 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009348 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009349 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9350 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9351 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9352 return false;
9353 }
9354 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9355 return true;
9356 }
9357 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9358 return false;
9359 }
9360 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009361 }
9362 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009363
9364 // ------- apps on sdcard specific code -------
9365 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009366 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9367 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9368 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009369 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009370
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009371 private String getEncryptKey() {
9372 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009373 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9374 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009375 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009376 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9377 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009378 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009379 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009380 return null;
9381 }
9382 }
9383 return sdEncKey;
9384 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009385 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009386 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009387 } catch (IOException ioe) {
9388 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9389 + ioe);
9390 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009391 }
Rich Cannings8d578832010-09-09 15:12:40 -07009392
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009393 }
9394
Kenny Rootc78a8072010-07-27 15:18:38 -07009395 /* package */ static String getTempContainerId() {
9396 int tmpIdx = 1;
9397 String list[] = PackageHelper.getSecureContainerList();
9398 if (list != null) {
9399 for (final String name : list) {
9400 // Ignore null and non-temporary container entries
9401 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9402 continue;
9403 }
9404
9405 String subStr = name.substring(mTempContainerPrefix.length());
9406 try {
9407 int cid = Integer.parseInt(subStr);
9408 if (cid >= tmpIdx) {
9409 tmpIdx = cid + 1;
9410 }
9411 } catch (NumberFormatException e) {
9412 }
9413 }
9414 }
9415 return mTempContainerPrefix + tmpIdx;
9416 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009417
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009418 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009419 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009420 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009421 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9422 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9423 throw new SecurityException("Media status can only be updated by the system");
9424 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009425 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009426 Log.i(TAG, "Updating external media status from " +
9427 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9428 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009429 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9430 mediaStatus+", mMediaMounted=" + mMediaMounted);
9431 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009432 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9433 reportStatus ? 1 : 0, -1);
9434 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009435 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009436 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009437 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009438 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009439 // Queue up an async operation since the package installation may take a little while.
9440 mHandler.post(new Runnable() {
9441 public void run() {
9442 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009443 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009444 }
9445 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009446 }
9447
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009448 /*
9449 * Collect information of applications on external media, map them
9450 * against existing containers and update information based on current
9451 * mount status. Please note that we always have to report status
9452 * if reportStatus has been set to true especially when unloading packages.
9453 */
9454 private void updateExternalMediaStatusInner(boolean mediaStatus,
9455 boolean reportStatus) {
9456 // Collection of uids
9457 int uidArr[] = null;
9458 // Collection of stale containers
9459 HashSet<String> removeCids = new HashSet<String>();
9460 // Collection of packages on external media with valid containers.
9461 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9462 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009463 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009464 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009465 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009466 } else {
9467 // Process list of secure containers and categorize them
9468 // as active or stale based on their package internal state.
9469 int uidList[] = new int[list.length];
9470 int num = 0;
9471 synchronized (mPackages) {
9472 for (String cid : list) {
9473 SdInstallArgs args = new SdInstallArgs(cid);
9474 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009475 String pkgName = args.getPackageName();
9476 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009477 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9478 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009479 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009480 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009481 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9482 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009483 // The package status is changed only if the code path
9484 // matches between settings and the container id.
9485 if (ps != null && ps.codePathString != null &&
9486 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009487 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9488 " corresponds to pkg : " + pkgName +
9489 " at code path: " + ps.codePathString);
9490 // We do have a valid package installed on sdcard
9491 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009492 int uid = ps.userId;
9493 if (uid != -1) {
9494 uidList[num++] = uid;
9495 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009496 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009497 // Stale container on sdcard. Just delete
9498 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9499 removeCids.add(cid);
9500 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009501 }
9502 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009503
9504 if (num > 0) {
9505 // Sort uid list
9506 Arrays.sort(uidList, 0, num);
9507 // Throw away duplicates
9508 uidArr = new int[num];
9509 uidArr[0] = uidList[0];
9510 int di = 0;
9511 for (int i = 1; i < num; i++) {
9512 if (uidList[i-1] != uidList[i]) {
9513 uidArr[di++] = uidList[i];
9514 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009515 }
9516 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009517 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009518 // Process packages with valid entries.
9519 if (mediaStatus) {
9520 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009521 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009522 startCleaningPackages();
9523 } else {
9524 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009525 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009526 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009527 }
9528
9529 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009530 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009531 int size = pkgList.size();
9532 if (size > 0) {
9533 // Send broadcasts here
9534 Bundle extras = new Bundle();
9535 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9536 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009537 if (uidArr != null) {
9538 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9539 }
9540 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9541 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009542 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009543 }
9544 }
9545
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009546 /*
9547 * Look at potentially valid container ids from processCids
9548 * If package information doesn't match the one on record
9549 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009550 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009551 */
9552 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009553 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009554 ArrayList<String> pkgList = new ArrayList<String>();
9555 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009556 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009557 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009558 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009559 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9560 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009561 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009562 try {
9563 // Make sure there are no container errors first.
9564 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9565 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009566 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009567 " when installing from sdcard");
9568 continue;
9569 }
9570 // Check code path here.
9571 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009572 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009573 " does not match one in settings " + codePath);
9574 continue;
9575 }
9576 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009577 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009578 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009579 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009580 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9581 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009582 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009583 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009584 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009585 retCode = PackageManager.INSTALL_SUCCEEDED;
9586 pkgList.add(pkg.packageName);
9587 // Post process args
9588 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9589 }
9590 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009591 Slog.i(TAG, "Failed to install pkg from " +
9592 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009593 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009594 }
9595
9596 } finally {
9597 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9598 // Don't destroy container here. Wait till gc clears things up.
9599 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009600 }
9601 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009602 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009603 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009604 // If the platform SDK has changed since the last time we booted,
9605 // we need to re-grant app permission to catch any new ones that
9606 // appear. This is really a hack, and means that apps can in some
9607 // cases get permissions that the user didn't initially explicitly
9608 // allow... it would be nice to have some better way to handle
9609 // this situation.
9610 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9611 != mSdkVersion;
9612 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9613 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9614 + "; regranting permissions for external storage");
9615 mSettings.mExternalSdkPlatform = mSdkVersion;
9616
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009617 // Make sure group IDs have been assigned, and any permission
9618 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009619 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009620 // Persist settings
9621 mSettings.writeLP();
9622 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009623 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009624 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009625 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009626 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009627 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009628 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009629 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009630 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009631 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009632 if (removeCids != null) {
9633 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009634 if (cid.startsWith(mTempContainerPrefix)) {
9635 Log.i(TAG, "Destroying stale temporary container " + cid);
9636 PackageHelper.destroySdDir(cid);
9637 } else {
9638 Log.w(TAG, "Container " + cid + " is stale");
9639 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009640 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009641 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009642 }
9643
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009644 /*
9645 * Utility method to unload a list of specified containers
9646 */
9647 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9648 // Just unmount all valid containers.
9649 for (SdInstallArgs arg : cidArgs) {
9650 synchronized (mInstallLock) {
9651 arg.doPostDeleteLI(false);
9652 }
9653 }
9654 }
9655
9656 /*
9657 * Unload packages mounted on external media. This involves deleting
9658 * package data from internal structures, sending broadcasts about
9659 * diabled packages, gc'ing to free up references, unmounting all
9660 * secure containers corresponding to packages on external media, and
9661 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9662 * Please note that we always have to post this message if status has
9663 * been requested no matter what.
9664 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009665 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009666 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009667 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009668 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009669 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009670 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009671 for (SdInstallArgs args : keys) {
9672 String cid = args.cid;
9673 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009674 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009675 // Delete package internally
9676 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9677 synchronized (mInstallLock) {
9678 boolean res = deletePackageLI(pkgName, false,
9679 PackageManager.DONT_DELETE_DATA, outInfo);
9680 if (res) {
9681 pkgList.add(pkgName);
9682 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009683 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009684 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009685 }
9686 }
9687 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009688 // We have to absolutely send UPDATED_MEDIA_STATUS only
9689 // after confirming that all the receivers processed the ordered
9690 // broadcast when packages get disabled, force a gc to clean things up.
9691 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009692 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009693 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9694 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9695 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009696 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9697 reportStatus ? 1 : 0, 1, keys);
9698 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009699 }
9700 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009701 } else {
9702 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9703 reportStatus ? 1 : 0, -1, keys);
9704 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009705 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009706 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009707
9708 public void movePackage(final String packageName,
9709 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009710 mContext.enforceCallingOrSelfPermission(
9711 android.Manifest.permission.MOVE_PACKAGE, null);
9712 int returnCode = PackageManager.MOVE_SUCCEEDED;
9713 int currFlags = 0;
9714 int newFlags = 0;
9715 synchronized (mPackages) {
9716 PackageParser.Package pkg = mPackages.get(packageName);
9717 if (pkg == null) {
9718 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009719 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009720 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009721 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009722 Slog.w(TAG, "Cannot move system application");
9723 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009724 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009725 Slog.w(TAG, "Cannot move forward locked app.");
9726 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009727 } else if (pkg.mOperationPending) {
9728 Slog.w(TAG, "Attempt to move package which has pending operations");
9729 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009730 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009731 // Find install location first
9732 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9733 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9734 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009735 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009736 } else {
9737 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9738 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009739 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9740 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009741 if (newFlags == currFlags) {
9742 Slog.w(TAG, "No move required. Trying to move to same location");
9743 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9744 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009745 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009746 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9747 pkg.mOperationPending = true;
9748 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009749 }
9750 }
9751 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009752 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009753 } else {
9754 Message msg = mHandler.obtainMessage(INIT_COPY);
9755 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009756 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9757 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9758 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009759 msg.obj = mp;
9760 mHandler.sendMessage(msg);
9761 }
9762 }
9763 }
9764
9765 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9766 // Queue up an async operation since the package deletion may take a little while.
9767 mHandler.post(new Runnable() {
9768 public void run() {
9769 mHandler.removeCallbacks(this);
9770 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009771 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9772 int uidArr[] = null;
9773 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009774 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009775 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009776 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009777 Slog.w(TAG, " Package " + mp.packageName +
9778 " doesn't exist. Aborting move");
9779 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9780 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9781 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9782 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9783 " Aborting move and returning error");
9784 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9785 } else {
9786 uidArr = new int[] { pkg.applicationInfo.uid };
9787 pkgList = new ArrayList<String>();
9788 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009789 }
9790 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009791 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9792 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009793 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009794 // Update package code and resource paths
9795 synchronized (mInstallLock) {
9796 synchronized (mPackages) {
9797 PackageParser.Package pkg = mPackages.get(mp.packageName);
9798 // Recheck for package again.
9799 if (pkg == null ) {
9800 Slog.w(TAG, " Package " + mp.packageName +
9801 " doesn't exist. Aborting move");
9802 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9803 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9804 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9805 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9806 " Aborting move and returning error");
9807 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9808 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009809 final String oldCodePath = pkg.mPath;
9810 final String newCodePath = mp.targetArgs.getCodePath();
9811 final String newResPath = mp.targetArgs.getResourcePath();
9812 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009813 pkg.mPath = newCodePath;
9814 // Move dex files around
9815 if (moveDexFilesLI(pkg)
9816 != PackageManager.INSTALL_SUCCEEDED) {
9817 // Moving of dex files failed. Set
9818 // error code and abort move.
9819 pkg.mPath = pkg.mScanPath;
9820 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9821 } else {
9822 pkg.mScanPath = newCodePath;
9823 pkg.applicationInfo.sourceDir = newCodePath;
9824 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009825 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009826 PackageSetting ps = (PackageSetting) pkg.mExtras;
9827 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9828 ps.codePathString = ps.codePath.getPath();
9829 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9830 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009831 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009832 // Set the application info flag correctly.
9833 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9834 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9835 } else {
9836 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9837 }
9838 ps.setFlags(pkg.applicationInfo.flags);
9839 mAppDirs.remove(oldCodePath);
9840 mAppDirs.put(newCodePath, pkg);
9841 // Persist settings
9842 mSettings.writeLP();
9843 }
9844 }
9845 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009846 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009847 // Send resources available broadcast
9848 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009849 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009850 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009851 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009852 // Clean up failed installation
9853 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009854 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009855 }
9856 } else {
9857 // Force a gc to clear things up.
9858 Runtime.getRuntime().gc();
9859 // Delete older code
9860 synchronized (mInstallLock) {
9861 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009862 }
9863 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009864
9865 // Allow more operations on this file if we didn't fail because
9866 // an operation was already pending for this package.
9867 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9868 synchronized (mPackages) {
9869 PackageParser.Package pkg = mPackages.get(mp.packageName);
9870 if (pkg != null) {
9871 pkg.mOperationPending = false;
9872 }
9873 }
9874 }
9875
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009876 IPackageMoveObserver observer = mp.observer;
9877 if (observer != null) {
9878 try {
9879 observer.packageMoved(mp.packageName, returnCode);
9880 } catch (RemoteException e) {
9881 Log.i(TAG, "Observer no longer exists.");
9882 }
9883 }
9884 }
9885 });
9886 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009887
9888 public boolean setInstallLocation(int loc) {
9889 mContext.enforceCallingOrSelfPermission(
9890 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9891 if (getInstallLocation() == loc) {
9892 return true;
9893 }
9894 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9895 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9896 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9897 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9898 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9899 return true;
9900 }
9901 return false;
9902 }
9903
9904 public int getInstallLocation() {
9905 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9906 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009908}