blob: 6c1b145663d8b2d88de6b77d911e63fc220eb628 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
57import android.content.pm.PackageStats;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
Kenny Root9f306d72010-09-26 11:19:47 -070094import java.io.BufferedOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.io.File;
96import java.io.FileDescriptor;
97import java.io.FileInputStream;
98import java.io.FileNotFoundException;
99import java.io.FileOutputStream;
100import java.io.FileReader;
101import java.io.FilenameFilter;
102import java.io.IOException;
103import java.io.InputStream;
104import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800105import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800106import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.ArrayList;
108import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700109import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.Collections;
111import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800112import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.Enumeration;
114import java.util.HashMap;
115import java.util.HashSet;
116import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700117import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118import java.util.List;
119import java.util.Map;
120import java.util.Set;
121import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800122import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123import java.util.zip.ZipFile;
124import java.util.zip.ZipOutputStream;
125
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700126/**
127 * Keep track of all those .apks everywhere.
128 *
129 * This is very central to the platform's security; please run the unit
130 * tests whenever making modifications here:
131 *
132mmm frameworks/base/tests/AndroidTests
133adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
134adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
135 *
136 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137class PackageManagerService extends IPackageManager.Stub {
138 private static final String TAG = "PackageManager";
139 private static final boolean DEBUG_SETTINGS = false;
140 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800141 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800142 private static final boolean DEBUG_INSTALL = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
145 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400146 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 private static final int FIRST_APPLICATION_UID =
148 Process.FIRST_APPLICATION_UID;
149 private static final int MAX_APPLICATION_UIDS = 1000;
150
151 private static final boolean SHOW_INFO = false;
152
153 private static final boolean GET_CERTIFICATES = true;
154
Oscar Montemayora8529f62009-11-18 10:14:20 -0800155 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private static final int REMOVE_EVENTS =
158 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
159 private static final int ADD_EVENTS =
160 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
161
162 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800163 // Suffix used during package installation when copying/moving
164 // package apks to install directory.
165 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800167 /**
168 * Indicates the state of installation. Used by PackageManager to
169 * figure out incomplete installations. Say a package is being installed
170 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
171 * the package installation is successful or unsuccesful lin which case
172 * the PackageManager will no longer maintain state information associated
173 * with the package. If some exception(like device freeze or battery being
174 * pulled out) occurs during installation of a package, the PackageManager
175 * needs this information to clean up the previously failed installation.
176 */
177 private static final int PKG_INSTALL_INCOMPLETE = 0;
178 private static final int PKG_INSTALL_COMPLETE = 1;
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final int SCAN_MONITOR = 1<<0;
181 static final int SCAN_NO_DEX = 1<<1;
182 static final int SCAN_FORCE_DEX = 1<<2;
183 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800184 static final int SCAN_NEW_INSTALL = 1<<4;
185 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700186 static final int SCAN_UPDATE_TIME = 1<<6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700188 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700189
190 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
191
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800192 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700193 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800194 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700195
Kenny Root85387d72010-08-26 10:13:11 -0700196 private static final String LIB_DIR_NAME = "lib";
197
Kenny Rootc78a8072010-07-27 15:18:38 -0700198 static final String mTempContainerPrefix = "smdl2tmp";
199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
201 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700202 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Dianne Hackborn851a5412009-05-08 12:06:44 -0700204 final int mSdkVersion = Build.VERSION.SDK_INT;
205 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
206 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 final Context mContext;
209 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700210 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 final DisplayMetrics mMetrics;
212 final int mDefParseFlags;
213 final String[] mSeparateProcesses;
214
215 // This is where all application persistent data goes.
216 final File mAppDataDir;
217
Oscar Montemayora8529f62009-11-18 10:14:20 -0800218 // If Encrypted File System feature is enabled, all application persistent data
219 // should go here instead.
220 final File mSecureAppDataDir;
221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222 // This is the object monitoring the framework dir.
223 final FileObserver mFrameworkInstallObserver;
224
225 // This is the object monitoring the system app dir.
226 final FileObserver mSystemInstallObserver;
227
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700228 // This is the object monitoring the system app dir.
229 final FileObserver mVendorInstallObserver;
230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 // This is the object monitoring mAppInstallDir.
232 final FileObserver mAppInstallObserver;
233
234 // This is the object monitoring mDrmAppPrivateInstallDir.
235 final FileObserver mDrmAppInstallObserver;
236
237 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
238 // LOCK HELD. Can be called with mInstallLock held.
239 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 final File mFrameworkDir;
242 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700243 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700245 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246
247 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
248 // apps.
249 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 // Lock for state used when installing and doing other long running
254 // operations. Methods that must be called with this lock held have
255 // the prefix "LI".
256 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 // These are the directories in the 3rd party applications installed dir
259 // that we have currently loaded packages from. Keys are the application's
260 // installed zip file (absolute codePath), and values are Package.
261 final HashMap<String, PackageParser.Package> mAppDirs =
262 new HashMap<String, PackageParser.Package>();
263
264 // Information for the parser to write more useful error messages.
265 File mScanningPath;
266 int mLastScanError;
267
268 final int[] mOutPermissions = new int[3];
269
270 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800272 // Keys are String (package name), values are Package. This also serves
273 // as the lock for the global state. Methods that must be called with
274 // this lock held have the prefix "LP".
275 final HashMap<String, PackageParser.Package> mPackages =
276 new HashMap<String, PackageParser.Package>();
277
278 final Settings mSettings;
279 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800280
281 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
282 int[] mGlobalGids;
283
284 // These are the built-in uid -> permission mappings that were read from the
285 // etc/permissions.xml file.
286 final SparseArray<HashSet<String>> mSystemPermissions =
287 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 // These are the built-in shared libraries that were read from the
290 // etc/permissions.xml file.
291 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800292
Dianne Hackborn49237342009-08-27 20:08:01 -0700293 // Temporary for building the final shared libraries for an .apk.
294 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800295
Dianne Hackborn49237342009-08-27 20:08:01 -0700296 // These are the features this devices supports that were read from the
297 // etc/permissions.xml file.
298 final HashMap<String, FeatureInfo> mAvailableFeatures =
299 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 // All available activities, for your resolving pleasure.
302 final ActivityIntentResolver mActivities =
303 new ActivityIntentResolver();
304
305 // All available receivers, for your resolving pleasure.
306 final ActivityIntentResolver mReceivers =
307 new ActivityIntentResolver();
308
309 // All available services, for your resolving pleasure.
310 final ServiceIntentResolver mServices = new ServiceIntentResolver();
311
312 // Keys are String (provider class name), values are Provider.
313 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
314 new HashMap<ComponentName, PackageParser.Provider>();
315
316 // Mapping from provider base names (first directory in content URI codePath)
317 // to the provider information.
318 final HashMap<String, PackageParser.Provider> mProviders =
319 new HashMap<String, PackageParser.Provider>();
320
321 // Mapping from instrumentation class names to info about them.
322 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
323 new HashMap<ComponentName, PackageParser.Instrumentation>();
324
325 // Mapping from permission names to info about them.
326 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
327 new HashMap<String, PackageParser.PermissionGroup>();
328
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800329 // Packages whose data we have transfered into another package, thus
330 // should no longer exist.
331 final HashSet<String> mTransferedPackages = new HashSet<String>();
332
Dianne Hackborn854060af2009-07-09 18:14:31 -0700333 // Broadcast actions that are only available to the system.
334 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 boolean mSystemReady;
337 boolean mSafeMode;
338 boolean mHasSystemUidErrors;
339
340 ApplicationInfo mAndroidApplication;
341 final ActivityInfo mResolveActivity = new ActivityInfo();
342 final ResolveInfo mResolveInfo = new ResolveInfo();
343 ComponentName mResolveComponentName;
344 PackageParser.Package mPlatformPackage;
345
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700346 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800347 final HashMap<String, ArrayList<String>> mPendingBroadcasts
348 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800349 // Service Connection to remote media container service to copy
350 // package uri's from external media onto secure containers
351 // or internal storage.
352 private IMediaContainerService mContainerService = null;
353
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700354 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800355 static final int MCS_BOUND = 3;
356 static final int END_COPY = 4;
357 static final int INIT_COPY = 5;
358 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800359 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800360 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800361 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800362 static final int MCS_RECONNECT = 10;
363 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700364 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700365 static final int WRITE_SETTINGS = 13;
366
367 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800368
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700369 // Delay time in millisecs
370 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800371 final private DefaultContainerConnection mDefContainerConn =
372 new DefaultContainerConnection();
373 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800374 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 IMediaContainerService imcs =
377 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800378 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800379 }
380
381 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800382 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800383 }
384 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700385
Christopher Tate1bb69062010-02-19 17:02:12 -0800386 // Recordkeeping of restore-after-install operations that are currently in flight
387 // between the Package Manager and the Backup Manager
388 class PostInstallData {
389 public InstallArgs args;
390 public PackageInstalledInfo res;
391
392 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
393 args = _a;
394 res = _r;
395 }
396 };
397 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
398 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
399
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700400 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800401 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800402 final ArrayList<HandlerParams> mPendingInstalls =
403 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800404
405 private boolean connectToService() {
406 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
407 " DefaultContainerService");
408 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 if (mContext.bindService(service, mDefContainerConn,
411 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700412 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800413 mBound = true;
414 return true;
415 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700416 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800417 return false;
418 }
419
420 private void disconnectService() {
421 mContainerService = null;
422 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700423 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800424 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700425 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800426 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800427
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700428 PackageHandler(Looper looper) {
429 super(looper);
430 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700431
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700432 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700433 try {
434 doHandleMessage(msg);
435 } finally {
436 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
437 }
438 }
439
440 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700441 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800442 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800443 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800444 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800445 int idx = mPendingInstalls.size();
446 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
447 // If a bind was already initiated we dont really
448 // need to do anything. The pending install
449 // will be processed later on.
450 if (!mBound) {
451 // If this is the only one pending we might
452 // have to bind to the service again.
453 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800454 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800455 params.serviceError();
456 return;
457 } else {
458 // Once we bind to the service, the first
459 // pending request will be processed.
460 mPendingInstalls.add(idx, params);
461 }
462 } else {
463 mPendingInstalls.add(idx, params);
464 // Already bound to the service. Just make
465 // sure we trigger off processing the first request.
466 if (idx == 0) {
467 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800468 }
469 }
470 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800471 }
472 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800473 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800474 if (msg.obj != null) {
475 mContainerService = (IMediaContainerService) msg.obj;
476 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800477 if (mContainerService == null) {
478 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800479 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800480 for (HandlerParams params : mPendingInstalls) {
481 mPendingInstalls.remove(0);
482 // Indicate service bind error
483 params.serviceError();
484 }
485 mPendingInstalls.clear();
486 } else if (mPendingInstalls.size() > 0) {
487 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800488 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800489 params.startCopy();
490 }
491 } else {
492 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800493 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800494 }
495 break;
496 }
497 case MCS_RECONNECT : {
498 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
499 if (mPendingInstalls.size() > 0) {
500 if (mBound) {
501 disconnectService();
502 }
503 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800504 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800505 for (HandlerParams params : mPendingInstalls) {
506 mPendingInstalls.remove(0);
507 // Indicate service bind error
508 params.serviceError();
509 }
510 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800511 }
512 }
513 break;
514 }
515 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800516 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
517 // Delete pending install
518 if (mPendingInstalls.size() > 0) {
519 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800520 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800521 if (mPendingInstalls.size() == 0) {
522 if (mBound) {
523 disconnectService();
524 }
525 } else {
526 // There are more pending requests in queue.
527 // Just post MCS_BOUND message to trigger processing
528 // of next pending install.
529 mHandler.sendEmptyMessage(MCS_BOUND);
530 }
531 break;
532 }
533 case MCS_GIVE_UP: {
534 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
535 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800536 break;
537 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700538 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800539 String packages[];
540 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700543 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700544 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800545 if (mPendingBroadcasts == null) {
546 return;
547 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700548 size = mPendingBroadcasts.size();
549 if (size <= 0) {
550 // Nothing to be done. Just return
551 return;
552 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800553 packages = new String[size];
554 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700555 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800556 Iterator<HashMap.Entry<String, ArrayList<String>>>
557 it = mPendingBroadcasts.entrySet().iterator();
558 int i = 0;
559 while (it.hasNext() && i < size) {
560 HashMap.Entry<String, ArrayList<String>> ent = it.next();
561 packages[i] = ent.getKey();
562 components[i] = ent.getValue();
563 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700564 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800565 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700566 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800567 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700568 mPendingBroadcasts.clear();
569 }
570 // Send broadcasts
571 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800572 sendPackageChangedBroadcast(packages[i], true,
573 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700574 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700575 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700576 break;
577 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800578 case START_CLEANING_PACKAGE: {
579 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700580 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800581 synchronized (mPackages) {
582 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
583 mSettings.mPackagesToBeCleaned.add(packageName);
584 }
585 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700586 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800587 startCleaningPackages();
588 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800589 case POST_INSTALL: {
590 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
591 PostInstallData data = mRunningInstalls.get(msg.arg1);
592 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700593 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800594
595 if (data != null) {
596 InstallArgs args = data.args;
597 PackageInstalledInfo res = data.res;
598
599 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700600 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800601 Bundle extras = new Bundle(1);
602 extras.putInt(Intent.EXTRA_UID, res.uid);
603 final boolean update = res.removedInfo.removedPackage != null;
604 if (update) {
605 extras.putBoolean(Intent.EXTRA_REPLACING, true);
606 }
607 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
608 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700609 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800610 if (update) {
611 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
612 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700613 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800614 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700615 if (res.removedInfo.args != null) {
616 // Remove the replaced package's older resources safely now
617 deleteOld = true;
618 }
619 }
620 // Force a gc to clear up things
621 Runtime.getRuntime().gc();
622 // We delete after a gc for applications on sdcard.
623 if (deleteOld) {
624 synchronized (mInstallLock) {
625 res.removedInfo.args.doPostDeleteLI(true);
626 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800627 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800628 if (args.observer != null) {
629 try {
630 args.observer.packageInstalled(res.name, res.returnCode);
631 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800632 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800633 }
634 }
635 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800636 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800637 }
638 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700639 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
641 boolean reportStatus = msg.arg1 == 1;
642 boolean doGc = msg.arg2 == 1;
643 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
644 if (doGc) {
645 // Force a gc to clear up stale containers.
646 Runtime.getRuntime().gc();
647 }
648 if (msg.obj != null) {
649 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
650 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
651 // Unload containers
652 unloadAllContainers(args);
653 }
654 if (reportStatus) {
655 try {
656 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
657 PackageHelper.getMountService().finishMediaUpdate();
658 } catch (RemoteException e) {
659 Log.e(TAG, "MountService not running?");
660 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700661 }
662 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700663 case WRITE_SETTINGS: {
664 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
665 synchronized (mPackages) {
666 removeMessages(WRITE_SETTINGS);
667 mSettings.writeLP();
668 }
669 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
670 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700671 }
672 }
673 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800674
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700675 void scheduleWriteSettingsLocked() {
676 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
677 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
678 }
679 }
680
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800681 static boolean installOnSd(int flags) {
682 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700683 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800684 return false;
685 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700686 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
687 return true;
688 }
689 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800690 }
691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692 public static final IPackageManager main(Context context, boolean factoryTest) {
693 PackageManagerService m = new PackageManagerService(context, factoryTest);
694 ServiceManager.addService("package", m);
695 return m;
696 }
697
698 static String[] splitString(String str, char sep) {
699 int count = 1;
700 int i = 0;
701 while ((i=str.indexOf(sep, i)) >= 0) {
702 count++;
703 i++;
704 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 String[] res = new String[count];
707 i=0;
708 count = 0;
709 int lastI=0;
710 while ((i=str.indexOf(sep, i)) >= 0) {
711 res[count] = str.substring(lastI, i);
712 count++;
713 i++;
714 lastI = i;
715 }
716 res[count] = str.substring(lastI, str.length());
717 return res;
718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800721 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800725 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 mContext = context;
729 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700730 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 mMetrics = new DisplayMetrics();
732 mSettings = new Settings();
733 mSettings.addSharedUserLP("android.uid.system",
734 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
735 mSettings.addSharedUserLP("android.uid.phone",
736 MULTIPLE_APPLICATION_UIDS
737 ? RADIO_UID : FIRST_APPLICATION_UID,
738 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400739 mSettings.addSharedUserLP("android.uid.log",
740 MULTIPLE_APPLICATION_UIDS
741 ? LOG_UID : FIRST_APPLICATION_UID,
742 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743
744 String separateProcesses = SystemProperties.get("debug.separate_processes");
745 if (separateProcesses != null && separateProcesses.length() > 0) {
746 if ("*".equals(separateProcesses)) {
747 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
748 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800749 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 } else {
751 mDefParseFlags = 0;
752 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800753 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 + separateProcesses);
755 }
756 } else {
757 mDefParseFlags = 0;
758 mSeparateProcesses = null;
759 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 Installer installer = new Installer();
762 // Little hacky thing to check if installd is here, to determine
763 // whether we are running on the simulator and thus need to take
764 // care of building the /data file structure ourself.
765 // (apparently the sim now has a working installer)
766 if (installer.ping() && Process.supportsProcesses()) {
767 mInstaller = installer;
768 } else {
769 mInstaller = null;
770 }
771
772 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
773 Display d = wm.getDefaultDisplay();
774 d.getMetrics(mMetrics);
775
776 synchronized (mInstallLock) {
777 synchronized (mPackages) {
778 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700779 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800780
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 File dataDir = Environment.getDataDirectory();
782 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800783 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
785
786 if (mInstaller == null) {
787 // Make sure these dirs exist, when we are running in
788 // the simulator.
789 // Make a wide-open directory for random misc stuff.
790 File miscDir = new File(dataDir, "misc");
791 miscDir.mkdirs();
792 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800793 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 mDrmAppPrivateInstallDir.mkdirs();
795 }
796
797 readPermissions();
798
799 mRestoredSettings = mSettings.readLP();
800 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800801
802 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800804
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800805 // Set flag to monitor and not change apk file paths when
806 // scanning install directories.
807 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700808 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800809 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700811 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800813 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700816 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700819 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 /**
822 * Out of paranoia, ensure that everything in the boot class
823 * path has been dexed.
824 */
825 String bootClassPath = System.getProperty("java.boot.class.path");
826 if (bootClassPath != null) {
827 String[] paths = splitString(bootClassPath, ':');
828 for (int i=0; i<paths.length; i++) {
829 try {
830 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
831 libFiles.add(paths[i]);
832 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700833 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800836 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800837 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800838 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
840 }
841 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800842 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 /**
846 * Also ensure all external libraries have had dexopt run on them.
847 */
848 if (mSharedLibraries.size() > 0) {
849 Iterator<String> libs = mSharedLibraries.values().iterator();
850 while (libs.hasNext()) {
851 String lib = libs.next();
852 try {
853 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
854 libFiles.add(lib);
855 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700856 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 }
858 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800859 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800861 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
863 }
864 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 // Gross hack for now: we know this file doesn't contain any
867 // code, so don't dexopt it to avoid the resulting log spew.
868 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 /**
871 * And there are a number of commands implemented in Java, which
872 * we currently need to do the dexopt on so that they can be
873 * run from a non-root shell.
874 */
875 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700876 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800877 for (int i=0; i<frameworkFiles.length; i++) {
878 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
879 String path = libPath.getPath();
880 // Skip the file if we alrady did it.
881 if (libFiles.contains(path)) {
882 continue;
883 }
884 // Skip the file if it is not a type we want to dexopt.
885 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
886 continue;
887 }
888 try {
889 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
890 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700891 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800892 }
893 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800894 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800895 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800896 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 }
898 }
899 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800900
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700901 if (didDexOpt) {
902 // If we had to do a dexopt of one of the previous
903 // things, then something on the system has changed.
904 // Consider this significant, and wipe away all other
905 // existing dexopt files to ensure we don't leave any
906 // dangling around.
907 String[] files = mDalvikCacheDir.list();
908 if (files != null) {
909 for (int i=0; i<files.length; i++) {
910 String fn = files[i];
911 if (fn.startsWith("data@app@")
912 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800913 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700914 (new File(mDalvikCacheDir, fn)).delete();
915 }
916 }
917 }
918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800920
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800921 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 mFrameworkInstallObserver = new AppDirObserver(
923 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
924 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700925 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
926 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700927 scanMode | SCAN_NO_DEX, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800928
929 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
931 mSystemInstallObserver = new AppDirObserver(
932 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
933 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700934 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700935 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800936
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700937 // Collect all vendor packages.
938 mVendorAppDir = new File("/vendor/app");
939 mVendorInstallObserver = new AppDirObserver(
940 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
941 mVendorInstallObserver.startWatching();
942 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700943 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700944
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800945 if (mInstaller != null) {
946 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
947 mInstaller.moveFiles();
948 }
949
950 // Prune any system packages that no longer exist.
951 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
952 while (psit.hasNext()) {
953 PackageSetting ps = psit.next();
954 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800955 && !mPackages.containsKey(ps.name)
956 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800957 psit.remove();
958 String msg = "System package " + ps.name
959 + " no longer exists; wiping its data";
960 reportSettingsProblem(Log.WARN, msg);
961 if (mInstaller != null) {
962 // XXX how to set useEncryptedFSDir for packages that
963 // are not encrypted?
964 mInstaller.remove(ps.name, true);
965 }
966 }
967 }
968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 mAppInstallDir = new File(dataDir, "app");
970 if (mInstaller == null) {
971 // Make sure these dirs exist, when we are running in
972 // the simulator.
973 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
974 }
975 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800976 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977 //clean up list
978 for(int i = 0; i < deletePkgsList.size(); i++) {
979 //clean up here
980 cleanupInstallFailedPackage(deletePkgsList.get(i));
981 }
982 //delete tmp files
983 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800984
985 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 SystemClock.uptimeMillis());
987 mAppInstallObserver = new AppDirObserver(
988 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
989 mAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700990 scanDirLI(mAppInstallDir, 0, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991
992 mDrmAppInstallObserver = new AppDirObserver(
993 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
994 mDrmAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700995 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
996 scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800998 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001000 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1002 + " seconds");
1003
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001004 // If the platform SDK has changed since the last time we booted,
1005 // we need to re-grant app permission to catch any new ones that
1006 // appear. This is really a hack, and means that apps can in some
1007 // cases get permissions that the user didn't initially explicitly
1008 // allow... it would be nice to have some better way to handle
1009 // this situation.
1010 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1011 != mSdkVersion;
1012 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1013 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1014 + "; regranting permissions for internal storage");
1015 mSettings.mInternalSdkPlatform = mSdkVersion;
1016
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001017 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018
1019 mSettings.writeLP();
1020
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001021 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 // Now after opening every single application zip, make sure they
1025 // are all flushed. Not really needed, but keeps things nice and
1026 // tidy.
1027 Runtime.getRuntime().gc();
1028 } // synchronized (mPackages)
1029 } // synchronized (mInstallLock)
1030 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001031
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 @Override
1033 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1034 throws RemoteException {
1035 try {
1036 return super.onTransact(code, data, reply, flags);
1037 } catch (RuntimeException e) {
1038 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001039 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
1041 throw e;
1042 }
1043 }
1044
Dianne Hackborne6620b22010-01-22 14:46:21 -08001045 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001046 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001048 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1049 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001052 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
1054 } else {
1055 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001056 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 File dataDir = new File(pkg.applicationInfo.dataDir);
1058 dataDir.delete();
1059 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001060 if (ps.codePath != null) {
1061 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001062 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001063 }
1064 }
1065 if (ps.resourcePath != null) {
1066 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001067 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001068 }
1069 }
1070 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 }
1072
1073 void readPermissions() {
1074 // Read permissions from .../etc/permission directory.
1075 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1076 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001077 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 return;
1079 }
1080 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001081 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 return;
1083 }
1084
1085 // Iterate over the files in the directory and scan .xml files
1086 for (File f : libraryDir.listFiles()) {
1087 // We'll read platform.xml last
1088 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1089 continue;
1090 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001093 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 continue;
1095 }
1096 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001097 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098 continue;
1099 }
1100
1101 readPermissionsFromXml(f);
1102 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1105 final File permFile = new File(Environment.getRootDirectory(),
1106 "etc/permissions/platform.xml");
1107 readPermissionsFromXml(permFile);
1108 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001109
1110 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 FileReader permReader = null;
1112 try {
1113 permReader = new FileReader(permFile);
1114 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001115 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 return;
1117 }
1118
1119 try {
1120 XmlPullParser parser = Xml.newPullParser();
1121 parser.setInput(permReader);
1122
1123 XmlUtils.beginDocument(parser, "permissions");
1124
1125 while (true) {
1126 XmlUtils.nextElement(parser);
1127 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1128 break;
1129 }
1130
1131 String name = parser.getName();
1132 if ("group".equals(name)) {
1133 String gidStr = parser.getAttributeValue(null, "gid");
1134 if (gidStr != null) {
1135 int gid = Integer.parseInt(gidStr);
1136 mGlobalGids = appendInt(mGlobalGids, gid);
1137 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001138 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 + parser.getPositionDescription());
1140 }
1141
1142 XmlUtils.skipCurrentTag(parser);
1143 continue;
1144 } else if ("permission".equals(name)) {
1145 String perm = parser.getAttributeValue(null, "name");
1146 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001147 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 + parser.getPositionDescription());
1149 XmlUtils.skipCurrentTag(parser);
1150 continue;
1151 }
1152 perm = perm.intern();
1153 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 } else if ("assign-permission".equals(name)) {
1156 String perm = parser.getAttributeValue(null, "name");
1157 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001158 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001159 + parser.getPositionDescription());
1160 XmlUtils.skipCurrentTag(parser);
1161 continue;
1162 }
1163 String uidStr = parser.getAttributeValue(null, "uid");
1164 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001165 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 + parser.getPositionDescription());
1167 XmlUtils.skipCurrentTag(parser);
1168 continue;
1169 }
1170 int uid = Process.getUidForName(uidStr);
1171 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001172 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 + uidStr + "\" at "
1174 + parser.getPositionDescription());
1175 XmlUtils.skipCurrentTag(parser);
1176 continue;
1177 }
1178 perm = perm.intern();
1179 HashSet<String> perms = mSystemPermissions.get(uid);
1180 if (perms == null) {
1181 perms = new HashSet<String>();
1182 mSystemPermissions.put(uid, perms);
1183 }
1184 perms.add(perm);
1185 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 } else if ("library".equals(name)) {
1188 String lname = parser.getAttributeValue(null, "name");
1189 String lfile = parser.getAttributeValue(null, "file");
1190 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001191 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 + parser.getPositionDescription());
1193 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001194 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 + parser.getPositionDescription());
1196 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001197 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001198 mSharedLibraries.put(lname, lfile);
1199 }
1200 XmlUtils.skipCurrentTag(parser);
1201 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001202
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 } else if ("feature".equals(name)) {
1204 String fname = parser.getAttributeValue(null, "name");
1205 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001206 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001207 + parser.getPositionDescription());
1208 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001209 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001210 FeatureInfo fi = new FeatureInfo();
1211 fi.name = fname;
1212 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001213 }
1214 XmlUtils.skipCurrentTag(parser);
1215 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 } else {
1218 XmlUtils.skipCurrentTag(parser);
1219 continue;
1220 }
1221
1222 }
1223 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001224 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001226 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 }
1228 }
1229
1230 void readPermission(XmlPullParser parser, String name)
1231 throws IOException, XmlPullParserException {
1232
1233 name = name.intern();
1234
1235 BasePermission bp = mSettings.mPermissions.get(name);
1236 if (bp == null) {
1237 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1238 mSettings.mPermissions.put(name, bp);
1239 }
1240 int outerDepth = parser.getDepth();
1241 int type;
1242 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1243 && (type != XmlPullParser.END_TAG
1244 || parser.getDepth() > outerDepth)) {
1245 if (type == XmlPullParser.END_TAG
1246 || type == XmlPullParser.TEXT) {
1247 continue;
1248 }
1249
1250 String tagName = parser.getName();
1251 if ("group".equals(tagName)) {
1252 String gidStr = parser.getAttributeValue(null, "gid");
1253 if (gidStr != null) {
1254 int gid = Process.getGidForName(gidStr);
1255 bp.gids = appendInt(bp.gids, gid);
1256 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001257 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 + parser.getPositionDescription());
1259 }
1260 }
1261 XmlUtils.skipCurrentTag(parser);
1262 }
1263 }
1264
1265 static int[] appendInt(int[] cur, int val) {
1266 if (cur == null) {
1267 return new int[] { val };
1268 }
1269 final int N = cur.length;
1270 for (int i=0; i<N; i++) {
1271 if (cur[i] == val) {
1272 return cur;
1273 }
1274 }
1275 int[] ret = new int[N+1];
1276 System.arraycopy(cur, 0, ret, 0, N);
1277 ret[N] = val;
1278 return ret;
1279 }
1280
1281 static int[] appendInts(int[] cur, int[] add) {
1282 if (add == null) return cur;
1283 if (cur == null) return add;
1284 final int N = add.length;
1285 for (int i=0; i<N; i++) {
1286 cur = appendInt(cur, add[i]);
1287 }
1288 return cur;
1289 }
1290
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001291 static int[] removeInt(int[] cur, int val) {
1292 if (cur == null) {
1293 return null;
1294 }
1295 final int N = cur.length;
1296 for (int i=0; i<N; i++) {
1297 if (cur[i] == val) {
1298 int[] ret = new int[N-1];
1299 if (i > 0) {
1300 System.arraycopy(cur, 0, ret, 0, i);
1301 }
1302 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001303 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001304 }
1305 return ret;
1306 }
1307 }
1308 return cur;
1309 }
1310
1311 static int[] removeInts(int[] cur, int[] rem) {
1312 if (rem == null) return cur;
1313 if (cur == null) return cur;
1314 final int N = rem.length;
1315 for (int i=0; i<N; i++) {
1316 cur = removeInt(cur, rem[i]);
1317 }
1318 return cur;
1319 }
1320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001322 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1323 // The package has been uninstalled but has retained data and resources.
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001324 return PackageParser.generatePackageInfo(p, null, flags, 0, 0);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 final PackageSetting ps = (PackageSetting)p.mExtras;
1327 if (ps == null) {
1328 return null;
1329 }
1330 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001331 return PackageParser.generatePackageInfo(p, gp.gids, flags,
1332 ps.firstInstallTime, ps.lastUpdateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
1334
1335 public PackageInfo getPackageInfo(String packageName, int flags) {
1336 synchronized (mPackages) {
1337 PackageParser.Package p = mPackages.get(packageName);
1338 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001339 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 + ": " + p);
1341 if (p != null) {
1342 return generatePackageInfo(p, flags);
1343 }
1344 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1345 return generatePackageInfoFromSettingsLP(packageName, flags);
1346 }
1347 }
1348 return null;
1349 }
1350
Dianne Hackborn47096932010-02-11 15:57:09 -08001351 public String[] currentToCanonicalPackageNames(String[] names) {
1352 String[] out = new String[names.length];
1353 synchronized (mPackages) {
1354 for (int i=names.length-1; i>=0; i--) {
1355 PackageSetting ps = mSettings.mPackages.get(names[i]);
1356 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1357 }
1358 }
1359 return out;
1360 }
1361
1362 public String[] canonicalToCurrentPackageNames(String[] names) {
1363 String[] out = new String[names.length];
1364 synchronized (mPackages) {
1365 for (int i=names.length-1; i>=0; i--) {
1366 String cur = mSettings.mRenamedPackages.get(names[i]);
1367 out[i] = cur != null ? cur : names[i];
1368 }
1369 }
1370 return out;
1371 }
1372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 public int getPackageUid(String packageName) {
1374 synchronized (mPackages) {
1375 PackageParser.Package p = mPackages.get(packageName);
1376 if(p != null) {
1377 return p.applicationInfo.uid;
1378 }
1379 PackageSetting ps = mSettings.mPackages.get(packageName);
1380 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1381 return -1;
1382 }
1383 p = ps.pkg;
1384 return p != null ? p.applicationInfo.uid : -1;
1385 }
1386 }
1387
1388 public int[] getPackageGids(String packageName) {
1389 synchronized (mPackages) {
1390 PackageParser.Package p = mPackages.get(packageName);
1391 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001392 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 + ": " + p);
1394 if (p != null) {
1395 final PackageSetting ps = (PackageSetting)p.mExtras;
1396 final SharedUserSetting suid = ps.sharedUser;
1397 return suid != null ? suid.gids : ps.gids;
1398 }
1399 }
1400 // stupid thing to indicate an error.
1401 return new int[0];
1402 }
1403
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001404 static final PermissionInfo generatePermissionInfo(
1405 BasePermission bp, int flags) {
1406 if (bp.perm != null) {
1407 return PackageParser.generatePermissionInfo(bp.perm, flags);
1408 }
1409 PermissionInfo pi = new PermissionInfo();
1410 pi.name = bp.name;
1411 pi.packageName = bp.sourcePackage;
1412 pi.nonLocalizedLabel = bp.name;
1413 pi.protectionLevel = bp.protectionLevel;
1414 return pi;
1415 }
1416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 public PermissionInfo getPermissionInfo(String name, int flags) {
1418 synchronized (mPackages) {
1419 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001420 if (p != null) {
1421 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 }
1423 return null;
1424 }
1425 }
1426
1427 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1428 synchronized (mPackages) {
1429 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1430 for (BasePermission p : mSettings.mPermissions.values()) {
1431 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001432 if (p.perm == null || p.perm.info.group == null) {
1433 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001436 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1438 }
1439 }
1440 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 if (out.size() > 0) {
1443 return out;
1444 }
1445 return mPermissionGroups.containsKey(group) ? out : null;
1446 }
1447 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1450 synchronized (mPackages) {
1451 return PackageParser.generatePermissionGroupInfo(
1452 mPermissionGroups.get(name), flags);
1453 }
1454 }
1455
1456 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1457 synchronized (mPackages) {
1458 final int N = mPermissionGroups.size();
1459 ArrayList<PermissionGroupInfo> out
1460 = new ArrayList<PermissionGroupInfo>(N);
1461 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1462 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1463 }
1464 return out;
1465 }
1466 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001467
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1469 PackageSetting ps = mSettings.mPackages.get(packageName);
1470 if(ps != null) {
1471 if(ps.pkg == null) {
1472 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1473 if(pInfo != null) {
1474 return pInfo.applicationInfo;
1475 }
1476 return null;
1477 }
1478 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1479 }
1480 return null;
1481 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1484 PackageSetting ps = mSettings.mPackages.get(packageName);
1485 if(ps != null) {
1486 if(ps.pkg == null) {
1487 ps.pkg = new PackageParser.Package(packageName);
1488 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001489 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1490 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1491 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1492 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001493 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001494 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496 return generatePackageInfo(ps.pkg, flags);
1497 }
1498 return null;
1499 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1502 synchronized (mPackages) {
1503 PackageParser.Package p = mPackages.get(packageName);
1504 if (Config.LOGV) Log.v(
1505 TAG, "getApplicationInfo " + packageName
1506 + ": " + p);
1507 if (p != null) {
1508 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001509 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 }
1511 if ("android".equals(packageName)||"system".equals(packageName)) {
1512 return mAndroidApplication;
1513 }
1514 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1515 return generateApplicationInfoFromSettingsLP(packageName, flags);
1516 }
1517 }
1518 return null;
1519 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001520
1521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1523 mContext.enforceCallingOrSelfPermission(
1524 android.Manifest.permission.CLEAR_APP_CACHE, null);
1525 // Queue up an async operation since clearing cache may take a little while.
1526 mHandler.post(new Runnable() {
1527 public void run() {
1528 mHandler.removeCallbacks(this);
1529 int retCode = -1;
1530 if (mInstaller != null) {
1531 retCode = mInstaller.freeCache(freeStorageSize);
1532 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001533 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535 } //end if mInstaller
1536 if (observer != null) {
1537 try {
1538 observer.onRemoveCompleted(null, (retCode >= 0));
1539 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001540 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542 }
1543 }
1544 });
1545 }
1546
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001547 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001548 mContext.enforceCallingOrSelfPermission(
1549 android.Manifest.permission.CLEAR_APP_CACHE, null);
1550 // Queue up an async operation since clearing cache may take a little while.
1551 mHandler.post(new Runnable() {
1552 public void run() {
1553 mHandler.removeCallbacks(this);
1554 int retCode = -1;
1555 if (mInstaller != null) {
1556 retCode = mInstaller.freeCache(freeStorageSize);
1557 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001558 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001559 }
1560 }
1561 if(pi != null) {
1562 try {
1563 // Callback via pending intent
1564 int code = (retCode >= 0) ? 1 : 0;
1565 pi.sendIntent(null, code, null,
1566 null, null);
1567 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001568 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001569 }
1570 }
1571 }
1572 });
1573 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1576 synchronized (mPackages) {
1577 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001578
1579 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001580 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001581 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583 if (mResolveComponentName.equals(component)) {
1584 return mResolveActivity;
1585 }
1586 }
1587 return null;
1588 }
1589
1590 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1591 synchronized (mPackages) {
1592 PackageParser.Activity a = mReceivers.mActivities.get(component);
1593 if (Config.LOGV) Log.v(
1594 TAG, "getReceiverInfo " + component + ": " + a);
1595 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1596 return PackageParser.generateActivityInfo(a, flags);
1597 }
1598 }
1599 return null;
1600 }
1601
1602 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1603 synchronized (mPackages) {
1604 PackageParser.Service s = mServices.mServices.get(component);
1605 if (Config.LOGV) Log.v(
1606 TAG, "getServiceInfo " + component + ": " + s);
1607 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1608 return PackageParser.generateServiceInfo(s, flags);
1609 }
1610 }
1611 return null;
1612 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001613
Dianne Hackborn361199b2010-08-30 17:42:07 -07001614 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1615 synchronized (mPackages) {
1616 PackageParser.Provider p = mProvidersByComponent.get(component);
1617 if (Config.LOGV) Log.v(
1618 TAG, "getProviderInfo " + component + ": " + p);
1619 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1620 return PackageParser.generateProviderInfo(p, flags);
1621 }
1622 }
1623 return null;
1624 }
1625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001626 public String[] getSystemSharedLibraryNames() {
1627 Set<String> libSet;
1628 synchronized (mPackages) {
1629 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001630 int size = libSet.size();
1631 if (size > 0) {
1632 String[] libs = new String[size];
1633 libSet.toArray(libs);
1634 return libs;
1635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001637 return null;
1638 }
1639
1640 public FeatureInfo[] getSystemAvailableFeatures() {
1641 Collection<FeatureInfo> featSet;
1642 synchronized (mPackages) {
1643 featSet = mAvailableFeatures.values();
1644 int size = featSet.size();
1645 if (size > 0) {
1646 FeatureInfo[] features = new FeatureInfo[size+1];
1647 featSet.toArray(features);
1648 FeatureInfo fi = new FeatureInfo();
1649 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1650 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1651 features[size] = fi;
1652 return features;
1653 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 }
1655 return null;
1656 }
1657
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001658 public boolean hasSystemFeature(String name) {
1659 synchronized (mPackages) {
1660 return mAvailableFeatures.containsKey(name);
1661 }
1662 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001663
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664 public int checkPermission(String permName, String pkgName) {
1665 synchronized (mPackages) {
1666 PackageParser.Package p = mPackages.get(pkgName);
1667 if (p != null && p.mExtras != null) {
1668 PackageSetting ps = (PackageSetting)p.mExtras;
1669 if (ps.sharedUser != null) {
1670 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1671 return PackageManager.PERMISSION_GRANTED;
1672 }
1673 } else if (ps.grantedPermissions.contains(permName)) {
1674 return PackageManager.PERMISSION_GRANTED;
1675 }
1676 }
1677 }
1678 return PackageManager.PERMISSION_DENIED;
1679 }
1680
1681 public int checkUidPermission(String permName, int uid) {
1682 synchronized (mPackages) {
1683 Object obj = mSettings.getUserIdLP(uid);
1684 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001685 GrantedPermissions gp = (GrantedPermissions)obj;
1686 if (gp.grantedPermissions.contains(permName)) {
1687 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
1689 } else {
1690 HashSet<String> perms = mSystemPermissions.get(uid);
1691 if (perms != null && perms.contains(permName)) {
1692 return PackageManager.PERMISSION_GRANTED;
1693 }
1694 }
1695 }
1696 return PackageManager.PERMISSION_DENIED;
1697 }
1698
1699 private BasePermission findPermissionTreeLP(String permName) {
1700 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1701 if (permName.startsWith(bp.name) &&
1702 permName.length() > bp.name.length() &&
1703 permName.charAt(bp.name.length()) == '.') {
1704 return bp;
1705 }
1706 }
1707 return null;
1708 }
1709
1710 private BasePermission checkPermissionTreeLP(String permName) {
1711 if (permName != null) {
1712 BasePermission bp = findPermissionTreeLP(permName);
1713 if (bp != null) {
1714 if (bp.uid == Binder.getCallingUid()) {
1715 return bp;
1716 }
1717 throw new SecurityException("Calling uid "
1718 + Binder.getCallingUid()
1719 + " is not allowed to add to permission tree "
1720 + bp.name + " owned by uid " + bp.uid);
1721 }
1722 }
1723 throw new SecurityException("No permission tree found for " + permName);
1724 }
1725
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001726 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1727 if (s1 == null) {
1728 return s2 == null;
1729 }
1730 if (s2 == null) {
1731 return false;
1732 }
1733 if (s1.getClass() != s2.getClass()) {
1734 return false;
1735 }
1736 return s1.equals(s2);
1737 }
1738
1739 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1740 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001741 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001742 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1743 if (!compareStrings(pi1.name, pi2.name)) return false;
1744 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1745 // We'll take care of setting this one.
1746 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1747 // These are not currently stored in settings.
1748 //if (!compareStrings(pi1.group, pi2.group)) return false;
1749 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1750 //if (pi1.labelRes != pi2.labelRes) return false;
1751 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1752 return true;
1753 }
1754
1755 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1756 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1757 throw new SecurityException("Label must be specified in permission");
1758 }
1759 BasePermission tree = checkPermissionTreeLP(info.name);
1760 BasePermission bp = mSettings.mPermissions.get(info.name);
1761 boolean added = bp == null;
1762 boolean changed = true;
1763 if (added) {
1764 bp = new BasePermission(info.name, tree.sourcePackage,
1765 BasePermission.TYPE_DYNAMIC);
1766 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1767 throw new SecurityException(
1768 "Not allowed to modify non-dynamic permission "
1769 + info.name);
1770 } else {
1771 if (bp.protectionLevel == info.protectionLevel
1772 && bp.perm.owner.equals(tree.perm.owner)
1773 && bp.uid == tree.uid
1774 && comparePermissionInfos(bp.perm.info, info)) {
1775 changed = false;
1776 }
1777 }
1778 bp.protectionLevel = info.protectionLevel;
1779 bp.perm = new PackageParser.Permission(tree.perm.owner,
1780 new PermissionInfo(info));
1781 bp.perm.info.packageName = tree.perm.info.packageName;
1782 bp.uid = tree.uid;
1783 if (added) {
1784 mSettings.mPermissions.put(info.name, bp);
1785 }
1786 if (changed) {
1787 if (!async) {
1788 mSettings.writeLP();
1789 } else {
1790 scheduleWriteSettingsLocked();
1791 }
1792 }
1793 return added;
1794 }
1795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 public boolean addPermission(PermissionInfo info) {
1797 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001798 return addPermissionLocked(info, false);
1799 }
1800 }
1801
1802 public boolean addPermissionAsync(PermissionInfo info) {
1803 synchronized (mPackages) {
1804 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 }
1806 }
1807
1808 public void removePermission(String name) {
1809 synchronized (mPackages) {
1810 checkPermissionTreeLP(name);
1811 BasePermission bp = mSettings.mPermissions.get(name);
1812 if (bp != null) {
1813 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1814 throw new SecurityException(
1815 "Not allowed to modify non-dynamic permission "
1816 + name);
1817 }
1818 mSettings.mPermissions.remove(name);
1819 mSettings.writeLP();
1820 }
1821 }
1822 }
1823
Dianne Hackborn854060af2009-07-09 18:14:31 -07001824 public boolean isProtectedBroadcast(String actionName) {
1825 synchronized (mPackages) {
1826 return mProtectedBroadcasts.contains(actionName);
1827 }
1828 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001830 public int checkSignatures(String pkg1, String pkg2) {
1831 synchronized (mPackages) {
1832 PackageParser.Package p1 = mPackages.get(pkg1);
1833 PackageParser.Package p2 = mPackages.get(pkg2);
1834 if (p1 == null || p1.mExtras == null
1835 || p2 == null || p2.mExtras == null) {
1836 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1837 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001838 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 }
1840 }
1841
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001842 public int checkUidSignatures(int uid1, int uid2) {
1843 synchronized (mPackages) {
1844 Signature[] s1;
1845 Signature[] s2;
1846 Object obj = mSettings.getUserIdLP(uid1);
1847 if (obj != null) {
1848 if (obj instanceof SharedUserSetting) {
1849 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1850 } else if (obj instanceof PackageSetting) {
1851 s1 = ((PackageSetting)obj).signatures.mSignatures;
1852 } else {
1853 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1854 }
1855 } else {
1856 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1857 }
1858 obj = mSettings.getUserIdLP(uid2);
1859 if (obj != null) {
1860 if (obj instanceof SharedUserSetting) {
1861 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1862 } else if (obj instanceof PackageSetting) {
1863 s2 = ((PackageSetting)obj).signatures.mSignatures;
1864 } else {
1865 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1866 }
1867 } else {
1868 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1869 }
1870 return checkSignaturesLP(s1, s2);
1871 }
1872 }
1873
1874 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1875 if (s1 == null) {
1876 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1878 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1879 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001880 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1882 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001883 HashSet<Signature> set1 = new HashSet<Signature>();
1884 for (Signature sig : s1) {
1885 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001886 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001887 HashSet<Signature> set2 = new HashSet<Signature>();
1888 for (Signature sig : s2) {
1889 set2.add(sig);
1890 }
1891 // Make sure s2 contains all signatures in s1.
1892 if (set1.equals(set2)) {
1893 return PackageManager.SIGNATURE_MATCH;
1894 }
1895 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001896 }
1897
1898 public String[] getPackagesForUid(int uid) {
1899 synchronized (mPackages) {
1900 Object obj = mSettings.getUserIdLP(uid);
1901 if (obj instanceof SharedUserSetting) {
1902 SharedUserSetting sus = (SharedUserSetting)obj;
1903 final int N = sus.packages.size();
1904 String[] res = new String[N];
1905 Iterator<PackageSetting> it = sus.packages.iterator();
1906 int i=0;
1907 while (it.hasNext()) {
1908 res[i++] = it.next().name;
1909 }
1910 return res;
1911 } else if (obj instanceof PackageSetting) {
1912 PackageSetting ps = (PackageSetting)obj;
1913 return new String[] { ps.name };
1914 }
1915 }
1916 return null;
1917 }
1918
1919 public String getNameForUid(int uid) {
1920 synchronized (mPackages) {
1921 Object obj = mSettings.getUserIdLP(uid);
1922 if (obj instanceof SharedUserSetting) {
1923 SharedUserSetting sus = (SharedUserSetting)obj;
1924 return sus.name + ":" + sus.userId;
1925 } else if (obj instanceof PackageSetting) {
1926 PackageSetting ps = (PackageSetting)obj;
1927 return ps.name;
1928 }
1929 }
1930 return null;
1931 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001932
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 public int getUidForSharedUser(String sharedUserName) {
1934 if(sharedUserName == null) {
1935 return -1;
1936 }
1937 synchronized (mPackages) {
1938 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1939 if(suid == null) {
1940 return -1;
1941 }
1942 return suid.userId;
1943 }
1944 }
1945
1946 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1947 int flags) {
1948 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001949 return chooseBestActivity(intent, resolvedType, flags, query);
1950 }
1951
Mihai Predaeae850c2009-05-13 10:13:48 +02001952 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1953 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001954 if (query != null) {
1955 final int N = query.size();
1956 if (N == 1) {
1957 return query.get(0);
1958 } else if (N > 1) {
1959 // If there is more than one activity with the same priority,
1960 // then let the user decide between them.
1961 ResolveInfo r0 = query.get(0);
1962 ResolveInfo r1 = query.get(1);
1963 if (false) {
1964 System.out.println(r0.activityInfo.name +
1965 "=" + r0.priority + " vs " +
1966 r1.activityInfo.name +
1967 "=" + r1.priority);
1968 }
1969 // If the first activity has a higher priority, or a different
1970 // default, then it is always desireable to pick it.
1971 if (r0.priority != r1.priority
1972 || r0.preferredOrder != r1.preferredOrder
1973 || r0.isDefault != r1.isDefault) {
1974 return query.get(0);
1975 }
1976 // If we have saved a preference for a preferred activity for
1977 // this Intent, use that.
1978 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1979 flags, query, r0.priority);
1980 if (ri != null) {
1981 return ri;
1982 }
1983 return mResolveInfo;
1984 }
1985 }
1986 return null;
1987 }
1988
1989 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1990 int flags, List<ResolveInfo> query, int priority) {
1991 synchronized (mPackages) {
1992 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1993 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001994 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1996 if (prefs != null && prefs.size() > 0) {
1997 // First figure out how good the original match set is.
1998 // We will only allow preferred activities that came
1999 // from the same match quality.
2000 int match = 0;
2001 final int N = query.size();
2002 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2003 for (int j=0; j<N; j++) {
2004 ResolveInfo ri = query.get(j);
2005 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2006 + ": 0x" + Integer.toHexString(match));
2007 if (ri.match > match) match = ri.match;
2008 }
2009 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2010 + Integer.toHexString(match));
2011 match &= IntentFilter.MATCH_CATEGORY_MASK;
2012 final int M = prefs.size();
2013 for (int i=0; i<M; i++) {
2014 PreferredActivity pa = prefs.get(i);
2015 if (pa.mMatch != match) {
2016 continue;
2017 }
2018 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2019 if (DEBUG_PREFERRED) {
2020 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002021 if (ai != null) {
2022 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2023 } else {
2024 Log.v(TAG, " null");
2025 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 }
2027 if (ai != null) {
2028 for (int j=0; j<N; j++) {
2029 ResolveInfo ri = query.get(j);
2030 if (!ri.activityInfo.applicationInfo.packageName
2031 .equals(ai.applicationInfo.packageName)) {
2032 continue;
2033 }
2034 if (!ri.activityInfo.name.equals(ai.name)) {
2035 continue;
2036 }
2037
2038 // Okay we found a previously set preferred app.
2039 // If the result set is different from when this
2040 // was created, we need to clear it and re-ask the
2041 // user their preference.
2042 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002043 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 + intent + " type " + resolvedType);
2045 mSettings.mPreferredActivities.removeFilter(pa);
2046 return null;
2047 }
2048
2049 // Yay!
2050 return ri;
2051 }
2052 }
2053 }
2054 }
2055 }
2056 return null;
2057 }
2058
2059 public List<ResolveInfo> queryIntentActivities(Intent intent,
2060 String resolvedType, int flags) {
2061 ComponentName comp = intent.getComponent();
2062 if (comp != null) {
2063 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2064 ActivityInfo ai = getActivityInfo(comp, flags);
2065 if (ai != null) {
2066 ResolveInfo ri = new ResolveInfo();
2067 ri.activityInfo = ai;
2068 list.add(ri);
2069 }
2070 return list;
2071 }
2072
2073 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002074 String pkgName = intent.getPackage();
2075 if (pkgName == null) {
2076 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2077 resolvedType, flags);
2078 }
2079 PackageParser.Package pkg = mPackages.get(pkgName);
2080 if (pkg != null) {
2081 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2082 resolvedType, flags, pkg.activities);
2083 }
2084 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 }
2086 }
2087
2088 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2089 Intent[] specifics, String[] specificTypes, Intent intent,
2090 String resolvedType, int flags) {
2091 final String resultsAction = intent.getAction();
2092
2093 List<ResolveInfo> results = queryIntentActivities(
2094 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2095 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2096
2097 int specificsPos = 0;
2098 int N;
2099
2100 // todo: note that the algorithm used here is O(N^2). This
2101 // isn't a problem in our current environment, but if we start running
2102 // into situations where we have more than 5 or 10 matches then this
2103 // should probably be changed to something smarter...
2104
2105 // First we go through and resolve each of the specific items
2106 // that were supplied, taking care of removing any corresponding
2107 // duplicate items in the generic resolve list.
2108 if (specifics != null) {
2109 for (int i=0; i<specifics.length; i++) {
2110 final Intent sintent = specifics[i];
2111 if (sintent == null) {
2112 continue;
2113 }
2114
2115 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2116 String action = sintent.getAction();
2117 if (resultsAction != null && resultsAction.equals(action)) {
2118 // If this action was explicitly requested, then don't
2119 // remove things that have it.
2120 action = null;
2121 }
2122 ComponentName comp = sintent.getComponent();
2123 ResolveInfo ri = null;
2124 ActivityInfo ai = null;
2125 if (comp == null) {
2126 ri = resolveIntent(
2127 sintent,
2128 specificTypes != null ? specificTypes[i] : null,
2129 flags);
2130 if (ri == null) {
2131 continue;
2132 }
2133 if (ri == mResolveInfo) {
2134 // ACK! Must do something better with this.
2135 }
2136 ai = ri.activityInfo;
2137 comp = new ComponentName(ai.applicationInfo.packageName,
2138 ai.name);
2139 } else {
2140 ai = getActivityInfo(comp, flags);
2141 if (ai == null) {
2142 continue;
2143 }
2144 }
2145
2146 // Look for any generic query activities that are duplicates
2147 // of this specific one, and remove them from the results.
2148 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2149 N = results.size();
2150 int j;
2151 for (j=specificsPos; j<N; j++) {
2152 ResolveInfo sri = results.get(j);
2153 if ((sri.activityInfo.name.equals(comp.getClassName())
2154 && sri.activityInfo.applicationInfo.packageName.equals(
2155 comp.getPackageName()))
2156 || (action != null && sri.filter.matchAction(action))) {
2157 results.remove(j);
2158 if (Config.LOGV) Log.v(
2159 TAG, "Removing duplicate item from " + j
2160 + " due to specific " + specificsPos);
2161 if (ri == null) {
2162 ri = sri;
2163 }
2164 j--;
2165 N--;
2166 }
2167 }
2168
2169 // Add this specific item to its proper place.
2170 if (ri == null) {
2171 ri = new ResolveInfo();
2172 ri.activityInfo = ai;
2173 }
2174 results.add(specificsPos, ri);
2175 ri.specificIndex = i;
2176 specificsPos++;
2177 }
2178 }
2179
2180 // Now we go through the remaining generic results and remove any
2181 // duplicate actions that are found here.
2182 N = results.size();
2183 for (int i=specificsPos; i<N-1; i++) {
2184 final ResolveInfo rii = results.get(i);
2185 if (rii.filter == null) {
2186 continue;
2187 }
2188
2189 // Iterate over all of the actions of this result's intent
2190 // filter... typically this should be just one.
2191 final Iterator<String> it = rii.filter.actionsIterator();
2192 if (it == null) {
2193 continue;
2194 }
2195 while (it.hasNext()) {
2196 final String action = it.next();
2197 if (resultsAction != null && resultsAction.equals(action)) {
2198 // If this action was explicitly requested, then don't
2199 // remove things that have it.
2200 continue;
2201 }
2202 for (int j=i+1; j<N; j++) {
2203 final ResolveInfo rij = results.get(j);
2204 if (rij.filter != null && rij.filter.hasAction(action)) {
2205 results.remove(j);
2206 if (Config.LOGV) Log.v(
2207 TAG, "Removing duplicate item from " + j
2208 + " due to action " + action + " at " + i);
2209 j--;
2210 N--;
2211 }
2212 }
2213 }
2214
2215 // If the caller didn't request filter information, drop it now
2216 // so we don't have to marshall/unmarshall it.
2217 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2218 rii.filter = null;
2219 }
2220 }
2221
2222 // Filter out the caller activity if so requested.
2223 if (caller != null) {
2224 N = results.size();
2225 for (int i=0; i<N; i++) {
2226 ActivityInfo ainfo = results.get(i).activityInfo;
2227 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2228 && caller.getClassName().equals(ainfo.name)) {
2229 results.remove(i);
2230 break;
2231 }
2232 }
2233 }
2234
2235 // If the caller didn't request filter information,
2236 // drop them now so we don't have to
2237 // marshall/unmarshall it.
2238 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2239 N = results.size();
2240 for (int i=0; i<N; i++) {
2241 results.get(i).filter = null;
2242 }
2243 }
2244
2245 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2246 return results;
2247 }
2248
2249 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2250 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002251 ComponentName comp = intent.getComponent();
2252 if (comp != null) {
2253 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2254 ActivityInfo ai = getReceiverInfo(comp, flags);
2255 if (ai != null) {
2256 ResolveInfo ri = new ResolveInfo();
2257 ri.activityInfo = ai;
2258 list.add(ri);
2259 }
2260 return list;
2261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002264 String pkgName = intent.getPackage();
2265 if (pkgName == null) {
2266 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2267 resolvedType, flags);
2268 }
2269 PackageParser.Package pkg = mPackages.get(pkgName);
2270 if (pkg != null) {
2271 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2272 resolvedType, flags, pkg.receivers);
2273 }
2274 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 }
2276 }
2277
2278 public ResolveInfo resolveService(Intent intent, String resolvedType,
2279 int flags) {
2280 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2281 flags);
2282 if (query != null) {
2283 if (query.size() >= 1) {
2284 // If there is more than one service with the same priority,
2285 // just arbitrarily pick the first one.
2286 return query.get(0);
2287 }
2288 }
2289 return null;
2290 }
2291
2292 public List<ResolveInfo> queryIntentServices(Intent intent,
2293 String resolvedType, int flags) {
2294 ComponentName comp = intent.getComponent();
2295 if (comp != null) {
2296 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2297 ServiceInfo si = getServiceInfo(comp, flags);
2298 if (si != null) {
2299 ResolveInfo ri = new ResolveInfo();
2300 ri.serviceInfo = si;
2301 list.add(ri);
2302 }
2303 return list;
2304 }
2305
2306 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002307 String pkgName = intent.getPackage();
2308 if (pkgName == null) {
2309 return (List<ResolveInfo>)mServices.queryIntent(intent,
2310 resolvedType, flags);
2311 }
2312 PackageParser.Package pkg = mPackages.get(pkgName);
2313 if (pkg != null) {
2314 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2315 resolvedType, flags, pkg.services);
2316 }
2317 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
2319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 public List<PackageInfo> getInstalledPackages(int flags) {
2322 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2323
2324 synchronized (mPackages) {
2325 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2326 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2327 while (i.hasNext()) {
2328 final PackageSetting ps = i.next();
2329 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2330 if(psPkg != null) {
2331 finalList.add(psPkg);
2332 }
2333 }
2334 }
2335 else {
2336 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2337 while (i.hasNext()) {
2338 final PackageParser.Package p = i.next();
2339 if (p.applicationInfo != null) {
2340 PackageInfo pi = generatePackageInfo(p, flags);
2341 if(pi != null) {
2342 finalList.add(pi);
2343 }
2344 }
2345 }
2346 }
2347 }
2348 return finalList;
2349 }
2350
2351 public List<ApplicationInfo> getInstalledApplications(int flags) {
2352 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2353 synchronized(mPackages) {
2354 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2355 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2356 while (i.hasNext()) {
2357 final PackageSetting ps = i.next();
2358 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2359 if(ai != null) {
2360 finalList.add(ai);
2361 }
2362 }
2363 }
2364 else {
2365 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2366 while (i.hasNext()) {
2367 final PackageParser.Package p = i.next();
2368 if (p.applicationInfo != null) {
2369 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2370 if(ai != null) {
2371 finalList.add(ai);
2372 }
2373 }
2374 }
2375 }
2376 }
2377 return finalList;
2378 }
2379
2380 public List<ApplicationInfo> getPersistentApplications(int flags) {
2381 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2382
2383 synchronized (mPackages) {
2384 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2385 while (i.hasNext()) {
2386 PackageParser.Package p = i.next();
2387 if (p.applicationInfo != null
2388 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002389 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002390 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 }
2392 }
2393 }
2394
2395 return finalList;
2396 }
2397
2398 public ProviderInfo resolveContentProvider(String name, int flags) {
2399 synchronized (mPackages) {
2400 final PackageParser.Provider provider = mProviders.get(name);
2401 return provider != null
2402 && mSettings.isEnabledLP(provider.info, flags)
2403 && (!mSafeMode || (provider.info.applicationInfo.flags
2404 &ApplicationInfo.FLAG_SYSTEM) != 0)
2405 ? PackageParser.generateProviderInfo(provider, flags)
2406 : null;
2407 }
2408 }
2409
Fred Quintana718d8a22009-04-29 17:53:20 -07002410 /**
2411 * @deprecated
2412 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 public void querySyncProviders(List outNames, List outInfo) {
2414 synchronized (mPackages) {
2415 Iterator<Map.Entry<String, PackageParser.Provider>> i
2416 = mProviders.entrySet().iterator();
2417
2418 while (i.hasNext()) {
2419 Map.Entry<String, PackageParser.Provider> entry = i.next();
2420 PackageParser.Provider p = entry.getValue();
2421
2422 if (p.syncable
2423 && (!mSafeMode || (p.info.applicationInfo.flags
2424 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2425 outNames.add(entry.getKey());
2426 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2427 }
2428 }
2429 }
2430 }
2431
2432 public List<ProviderInfo> queryContentProviders(String processName,
2433 int uid, int flags) {
2434 ArrayList<ProviderInfo> finalList = null;
2435
2436 synchronized (mPackages) {
2437 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2438 while (i.hasNext()) {
2439 PackageParser.Provider p = i.next();
2440 if (p.info.authority != null
2441 && (processName == null ||
2442 (p.info.processName.equals(processName)
2443 && p.info.applicationInfo.uid == uid))
2444 && mSettings.isEnabledLP(p.info, flags)
2445 && (!mSafeMode || (p.info.applicationInfo.flags
2446 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2447 if (finalList == null) {
2448 finalList = new ArrayList<ProviderInfo>(3);
2449 }
2450 finalList.add(PackageParser.generateProviderInfo(p,
2451 flags));
2452 }
2453 }
2454 }
2455
2456 if (finalList != null) {
2457 Collections.sort(finalList, mProviderInitOrderSorter);
2458 }
2459
2460 return finalList;
2461 }
2462
2463 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2464 int flags) {
2465 synchronized (mPackages) {
2466 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2467 return PackageParser.generateInstrumentationInfo(i, flags);
2468 }
2469 }
2470
2471 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2472 int flags) {
2473 ArrayList<InstrumentationInfo> finalList =
2474 new ArrayList<InstrumentationInfo>();
2475
2476 synchronized (mPackages) {
2477 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2478 while (i.hasNext()) {
2479 PackageParser.Instrumentation p = i.next();
2480 if (targetPackage == null
2481 || targetPackage.equals(p.info.targetPackage)) {
2482 finalList.add(PackageParser.generateInstrumentationInfo(p,
2483 flags));
2484 }
2485 }
2486 }
2487
2488 return finalList;
2489 }
2490
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002491 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002492 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002493 if (files == null) {
2494 Log.d(TAG, "No files in app dir " + dir);
2495 return;
2496 }
2497
2498 Log.d(TAG, "Scanning app dir " + dir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499
2500 int i;
2501 for (i=0; i<files.length; i++) {
2502 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002503 if (!isPackageFilename(files[i])) {
2504 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002505 continue;
2506 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002507 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002508 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002509 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002510 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2511 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002512 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002513 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002514 file.delete();
2515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517 }
2518
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002519 private static File getSettingsProblemFile() {
2520 File dataDir = Environment.getDataDirectory();
2521 File systemDir = new File(dataDir, "system");
2522 File fname = new File(systemDir, "uiderrors.txt");
2523 return fname;
2524 }
2525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 private static void reportSettingsProblem(int priority, String msg) {
2527 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002528 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 FileOutputStream out = new FileOutputStream(fname, true);
2530 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002531 SimpleDateFormat formatter = new SimpleDateFormat();
2532 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2533 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 pw.close();
2535 FileUtils.setPermissions(
2536 fname.toString(),
2537 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2538 -1, -1);
2539 } catch (java.io.IOException e) {
2540 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002541 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 }
2543
2544 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2545 PackageParser.Package pkg, File srcFile, int parseFlags) {
2546 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002547 if (ps != null
2548 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002549 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002550 if (ps.signatures.mSignatures != null
2551 && ps.signatures.mSignatures.length != 0) {
2552 // Optimization: reuse the existing cached certificates
2553 // if the package appears to be unchanged.
2554 pkg.mSignatures = ps.signatures.mSignatures;
2555 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 }
Jeff Browne7600722010-04-07 18:28:23 -07002557
2558 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002559 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002560 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2561 }
2562
2563 if (!pp.collectCertificates(pkg, parseFlags)) {
2564 mLastScanError = pp.getParseError();
2565 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 }
2567 }
2568 return true;
2569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 /*
2572 * Scan a package and return the newly parsed package.
2573 * Returns null in case of errors and the error code is stored in mLastScanError
2574 */
2575 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002576 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002578 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002580 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002583 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 if (pkg == null) {
2585 mLastScanError = pp.getParseError();
2586 return null;
2587 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002588 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 PackageSetting updatedPkg;
2590 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 // Look to see if we already know about this package.
2592 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002593 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002594 // This package has been renamed to its original name. Let's
2595 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002596 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002597 }
2598 // If there was no original package, see one for the real package name.
2599 if (ps == null) {
2600 ps = mSettings.peekPackageLP(pkg.packageName);
2601 }
2602 // Check to see if this package could be hiding/updating a system
2603 // package. Must look for it either under the original or real
2604 // package name depending on our state.
2605 updatedPkg = mSettings.mDisabledSysPackages.get(
2606 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002608 // First check if this is a system package that may involve an update
2609 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002610 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002611 // The path has changed from what was last scanned... check the
2612 // version of the new path against what we have stored to determine
2613 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002614 if (pkg.mVersionCode < ps.versionCode) {
2615 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 // Ignore entry. Skip it.
2617 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002618 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002620 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2621 return null;
2622 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002623 // The current app on the system partion is better than
2624 // what we have updated to on the data partition; switch
2625 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002626 // At this point, its safely assumed that package installation for
2627 // apps in system partition will go through. If not there won't be a working
2628 // version of the app
2629 synchronized (mPackages) {
2630 // Just remove the loaded entries from package lists.
2631 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002632 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002633 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002634 + "reverting from " + ps.codePathString
2635 + ": new version " + pkg.mVersionCode
2636 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002637 InstallArgs args = new FileInstallArgs(ps.codePathString,
2638 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002639 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002640 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
2643 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002644 if (updatedPkg != null) {
2645 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2646 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2647 }
2648 // Verify certificates against what was last scanned
2649 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002650 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002651 return null;
2652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 // The apk is forward locked (not public) if its code and resources
2654 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002655 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002657 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002658 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002659
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002660 String codePath = null;
2661 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002662 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2663 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002664 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002665 } else {
2666 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002667 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002668 }
2669 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002670 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002671 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002672 codePath = pkg.mScanPath;
2673 // Set application objects path explicitly.
2674 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002676 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 }
2678
Kenny Root85387d72010-08-26 10:13:11 -07002679 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2680 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002681 pkg.mPath = pkg.mScanPath = destCodePath;
2682 pkg.applicationInfo.sourceDir = destCodePath;
2683 pkg.applicationInfo.publicSourceDir = destResPath;
2684 }
2685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 private static String fixProcessName(String defProcessName,
2687 String processName, int uid) {
2688 if (processName == null) {
2689 return defProcessName;
2690 }
2691 return processName;
2692 }
2693
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002694 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002695 PackageParser.Package pkg) {
2696 if (pkgSetting.signatures.mSignatures != null) {
2697 // Already existing package. Make sure signatures match
2698 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2699 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002700 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002701 + " signatures do not match the previously installed version; ignoring!");
2702 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 return false;
2704 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002705 }
2706 // Check for shared user signatures
2707 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2708 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2709 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2710 Slog.e(TAG, "Package " + pkg.packageName
2711 + " has no signatures that match those in shared user "
2712 + pkgSetting.sharedUser.name + "; ignoring!");
2713 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2714 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717 return true;
2718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002719
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002720 public boolean performDexOpt(String packageName) {
2721 if (!mNoDexOpt) {
2722 return false;
2723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002724
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002725 PackageParser.Package p;
2726 synchronized (mPackages) {
2727 p = mPackages.get(packageName);
2728 if (p == null || p.mDidDexOpt) {
2729 return false;
2730 }
2731 }
2732 synchronized (mInstallLock) {
2733 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2734 }
2735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 static final int DEX_OPT_SKIPPED = 0;
2738 static final int DEX_OPT_PERFORMED = 1;
2739 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002740
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002741 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2742 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002743 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002744 String path = pkg.mScanPath;
2745 int ret = 0;
2746 try {
2747 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002748 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002749 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002750 pkg.mDidDexOpt = true;
2751 performed = true;
2752 }
2753 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002754 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002755 ret = -1;
2756 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002757 Slog.w(TAG, "IOException reading apk: " + path, e);
2758 ret = -1;
2759 } catch (dalvik.system.StaleDexCacheError e) {
2760 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2761 ret = -1;
2762 } catch (Exception e) {
2763 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002764 ret = -1;
2765 }
2766 if (ret < 0) {
2767 //error from installer
2768 return DEX_OPT_FAILED;
2769 }
2770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002771
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002772 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2773 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002774
2775 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2776 return Environment.isEncryptedFilesystemEnabled() &&
2777 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2778 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002779
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002780 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2781 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002782 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002783 + " to " + newPkg.packageName
2784 + ": old package not in system partition");
2785 return false;
2786 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002787 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002788 + " to " + newPkg.packageName
2789 + ": old package still exists");
2790 return false;
2791 }
2792 return true;
2793 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002794
2795 private File getDataPathForPackage(PackageParser.Package pkg) {
2796 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2797 File dataPath;
2798 if (useEncryptedFSDir) {
2799 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2800 } else {
2801 dataPath = new File(mAppDataDir, pkg.packageName);
2802 }
2803 return dataPath;
2804 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002805
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002806 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002807 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002808 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002809 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2810 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002811 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002812 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002813 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2814 return null;
2815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 mScanningPath = scanFile;
2817 if (pkg == null) {
2818 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2819 return null;
2820 }
2821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2823 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2824 }
2825
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002826 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 synchronized (mPackages) {
2828 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002829 Slog.w(TAG, "*************************************************");
2830 Slog.w(TAG, "Core android package being redefined. Skipping.");
2831 Slog.w(TAG, " file=" + mScanningPath);
2832 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2834 return null;
2835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 // Set up information for our fall-back user intent resolution
2838 // activity.
2839 mPlatformPackage = pkg;
2840 pkg.mVersionCode = mSdkVersion;
2841 mAndroidApplication = pkg.applicationInfo;
2842 mResolveActivity.applicationInfo = mAndroidApplication;
2843 mResolveActivity.name = ResolverActivity.class.getName();
2844 mResolveActivity.packageName = mAndroidApplication.packageName;
2845 mResolveActivity.processName = mAndroidApplication.processName;
2846 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2847 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2848 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2849 mResolveActivity.exported = true;
2850 mResolveActivity.enabled = true;
2851 mResolveInfo.activityInfo = mResolveActivity;
2852 mResolveInfo.priority = 0;
2853 mResolveInfo.preferredOrder = 0;
2854 mResolveInfo.match = 0;
2855 mResolveComponentName = new ComponentName(
2856 mAndroidApplication.packageName, mResolveActivity.name);
2857 }
2858 }
2859
2860 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002861 TAG, "Scanning package " + pkg.packageName);
2862 if (mPackages.containsKey(pkg.packageName)
2863 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002864 Slog.w(TAG, "*************************************************");
2865 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002867 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2869 return null;
2870 }
2871
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002872 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002873 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2874 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 SharedUserSetting suid = null;
2877 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002878
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002879 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2880 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002881 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002882 pkg.mRealPackage = null;
2883 pkg.mAdoptPermissions = null;
2884 }
2885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 synchronized (mPackages) {
2887 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002888 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2889 if (mTmpSharedLibraries == null ||
2890 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2891 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2892 }
2893 int num = 0;
2894 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2895 for (int i=0; i<N; i++) {
2896 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002898 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002900 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2902 return null;
2903 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002904 mTmpSharedLibraries[num] = file;
2905 num++;
2906 }
2907 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2908 for (int i=0; i<N; i++) {
2909 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2910 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002911 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002912 + " desires unavailable shared library "
2913 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2914 } else {
2915 mTmpSharedLibraries[num] = file;
2916 num++;
2917 }
2918 }
2919 if (num > 0) {
2920 pkg.usesLibraryFiles = new String[num];
2921 System.arraycopy(mTmpSharedLibraries, 0,
2922 pkg.usesLibraryFiles, 0, num);
2923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002924
Dianne Hackborn49237342009-08-27 20:08:01 -07002925 if (pkg.reqFeatures != null) {
2926 N = pkg.reqFeatures.size();
2927 for (int i=0; i<N; i++) {
2928 FeatureInfo fi = pkg.reqFeatures.get(i);
2929 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2930 // Don't care.
2931 continue;
2932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002933
Dianne Hackborn49237342009-08-27 20:08:01 -07002934 if (fi.name != null) {
2935 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002936 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002937 + " requires unavailable feature "
2938 + fi.name + "; failing!");
2939 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2940 return null;
2941 }
2942 }
2943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 }
2945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 if (pkg.mSharedUserId != null) {
2948 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2949 pkg.applicationInfo.flags, true);
2950 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002951 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 + " for shared user failed");
2953 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2954 return null;
2955 }
2956 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2957 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2958 + suid.userId + "): packages=" + suid.packages);
2959 }
2960 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002961
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002962 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002963 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002964 Log.w(TAG, "WAITING FOR DEBUGGER");
2965 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002966 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2967 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002968 }
2969 }
2970
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002971 // Check if we are renaming from an original package name.
2972 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002974 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 // This package may need to be renamed to a previously
2976 // installed name. Let's check on that...
2977 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002978 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002979 // This package had originally been installed as the
2980 // original name, and we have already taken care of
2981 // transitioning to the new one. Just update the new
2982 // one to continue using the old name.
2983 realName = pkg.mRealPackage;
2984 if (!pkg.packageName.equals(renamed)) {
2985 // Callers into this function may have already taken
2986 // care of renaming the package; only do it here if
2987 // it is not already done.
2988 pkg.setPackageName(renamed);
2989 }
2990
Dianne Hackbornc1552392010-03-03 16:19:01 -08002991 } else {
2992 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2993 if ((origPackage=mSettings.peekPackageLP(
2994 pkg.mOriginalPackages.get(i))) != null) {
2995 // We do have the package already installed under its
2996 // original name... should we use it?
2997 if (!verifyPackageUpdate(origPackage, pkg)) {
2998 // New package is not compatible with original.
2999 origPackage = null;
3000 continue;
3001 } else if (origPackage.sharedUser != null) {
3002 // Make sure uid is compatible between packages.
3003 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003004 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003005 + " to " + pkg.packageName + ": old uid "
3006 + origPackage.sharedUser.name
3007 + " differs from " + pkg.mSharedUserId);
3008 origPackage = null;
3009 continue;
3010 }
3011 } else {
3012 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3013 + pkg.packageName + " to old name " + origPackage.name);
3014 }
3015 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003016 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003017 }
3018 }
3019 }
3020
3021 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003022 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003023 + " was transferred to another, but its .apk remains");
3024 }
3025
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003026 // Just create the setting, don't add it yet. For already existing packages
3027 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003028 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003029 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3030 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003032 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3034 return null;
3035 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003036
3037 if (pkgSetting.origPackage != null) {
3038 // If we are first transitioning from an original package,
3039 // fix up the new package's name now. We need to do this after
3040 // looking up the package under its new name, so getPackageLP
3041 // can take care of fiddling things correctly.
3042 pkg.setPackageName(origPackage.name);
3043
3044 // File a report about this.
3045 String msg = "New package " + pkgSetting.realName
3046 + " renamed to replace old package " + pkgSetting.name;
3047 reportSettingsProblem(Log.WARN, msg);
3048
3049 // Make a note of it.
3050 mTransferedPackages.add(origPackage.name);
3051
3052 // No longer need to retain this.
3053 pkgSetting.origPackage = null;
3054 }
3055
3056 if (realName != null) {
3057 // Make a note of it.
3058 mTransferedPackages.add(pkg.packageName);
3059 }
3060
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003061 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 pkg.applicationInfo.uid = pkgSetting.userId;
3066 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003067
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003068 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003069 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 return null;
3071 }
3072 // The signature has changed, but this package is in the system
3073 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003074 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 // However... if this package is part of a shared user, but it
3076 // doesn't match the signature of the shared user, let's fail.
3077 // What this means is that you can't change the signatures
3078 // associated with an overall shared user, which doesn't seem all
3079 // that unreasonable.
3080 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003081 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3082 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3083 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3085 return null;
3086 }
3087 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003088 // File a report about this.
3089 String msg = "System package " + pkg.packageName
3090 + " signature changed; retaining data.";
3091 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003093
The Android Open Source Project10592532009-03-18 17:39:46 -07003094 // Verify that this new package doesn't have any content providers
3095 // that conflict with existing packages. Only do this if the
3096 // package isn't already installed, since we don't want to break
3097 // things that are installed.
3098 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3099 int N = pkg.providers.size();
3100 int i;
3101 for (i=0; i<N; i++) {
3102 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003103 if (p.info.authority != null) {
3104 String names[] = p.info.authority.split(";");
3105 for (int j = 0; j < names.length; j++) {
3106 if (mProviders.containsKey(names[j])) {
3107 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003108 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003109 " (in package " + pkg.applicationInfo.packageName +
3110 ") is already used by "
3111 + ((other != null && other.getComponentName() != null)
3112 ? other.getComponentName().getPackageName() : "?"));
3113 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3114 return null;
3115 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003116 }
3117 }
3118 }
3119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 }
3121
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003122 final String pkgName = pkg.packageName;
3123
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003124 if (pkg.mAdoptPermissions != null) {
3125 // This package wants to adopt ownership of permissions from
3126 // another package.
3127 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3128 String origName = pkg.mAdoptPermissions.get(i);
3129 PackageSetting orig = mSettings.peekPackageLP(origName);
3130 if (orig != null) {
3131 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003132 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003133 + origName + " to " + pkg.packageName);
3134 mSettings.transferPermissions(origName, pkg.packageName);
3135 }
3136 }
3137 }
3138 }
3139
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003140 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003142 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 pkg.applicationInfo.processName = fixProcessName(
3144 pkg.applicationInfo.packageName,
3145 pkg.applicationInfo.processName,
3146 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147
3148 File dataPath;
3149 if (mPlatformPackage == pkg) {
3150 // The system package is special.
3151 dataPath = new File (Environment.getDataDirectory(), "system");
3152 pkg.applicationInfo.dataDir = dataPath.getPath();
3153 } else {
3154 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003155 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003156 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003157
3158 boolean uidError = false;
3159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 if (dataPath.exists()) {
3161 mOutPermissions[1] = 0;
3162 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003163
3164 // If we have mismatched owners for the data path, we have a
3165 // problem (unless we're running in the simulator.)
3166 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 boolean recovered = false;
3168 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3169 // If this is a system app, we can at least delete its
3170 // current data so the application will still work.
3171 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003172 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003173 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 // Old data gone!
3175 String msg = "System package " + pkg.packageName
3176 + " has changed from uid: "
3177 + mOutPermissions[1] + " to "
3178 + pkg.applicationInfo.uid + "; old data erased";
3179 reportSettingsProblem(Log.WARN, msg);
3180 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003183 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 pkg.applicationInfo.uid);
3185 if (ret == -1) {
3186 // Ack should not happen!
3187 msg = "System package " + pkg.packageName
3188 + " could not have data directory re-created after delete.";
3189 reportSettingsProblem(Log.WARN, msg);
3190 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3191 return null;
3192 }
3193 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 if (!recovered) {
3196 mHasSystemUidErrors = true;
3197 }
3198 }
3199 if (!recovered) {
3200 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3201 + pkg.applicationInfo.uid + "/fs_"
3202 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003203 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 String msg = "Package " + pkg.packageName
3205 + " has mismatched uid: "
3206 + mOutPermissions[1] + " on disk, "
3207 + pkg.applicationInfo.uid + " in settings";
3208 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003209 mSettings.mReadMessages.append(msg);
3210 mSettings.mReadMessages.append('\n');
3211 uidError = true;
3212 if (!pkgSetting.uidError) {
3213 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 }
3216 }
3217 }
3218 pkg.applicationInfo.dataDir = dataPath.getPath();
3219 } else {
3220 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3221 Log.v(TAG, "Want this data dir: " + dataPath);
3222 //invoke installer to do the actual installation
3223 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003224 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 pkg.applicationInfo.uid);
3226 if(ret < 0) {
3227 // Error from installer
3228 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3229 return null;
3230 }
3231 } else {
3232 dataPath.mkdirs();
3233 if (dataPath.exists()) {
3234 FileUtils.setPermissions(
3235 dataPath.toString(),
3236 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3237 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3238 }
3239 }
3240 if (dataPath.exists()) {
3241 pkg.applicationInfo.dataDir = dataPath.getPath();
3242 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003243 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 pkg.applicationInfo.dataDir = null;
3245 }
3246 }
Kenny Root85387d72010-08-26 10:13:11 -07003247
3248 /*
3249 * Set the data dir to the default "/data/data/<package name>/lib"
3250 * if we got here without anyone telling us different (e.g., apps
3251 * stored on SD card have their native libraries stored in the ASEC
3252 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003253 *
3254 * This happens during an upgrade from a package settings file that
3255 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003256 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003257 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3258 if (pkgSetting.nativeLibraryPathString == null) {
3259 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3260 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3261 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3262 } else {
3263 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3264 }
Kenny Root85387d72010-08-26 10:13:11 -07003265 }
3266
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003267 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 }
3269
Kenny Root85387d72010-08-26 10:13:11 -07003270 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 if (mInstaller != null) {
3272 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003273 /* Note: We don't want to unpack the native binaries for
3274 * system applications, unless they have been updated
3275 * (the binaries are already under /system/lib).
3276 * Also, don't unpack libs for apps on the external card
3277 * since they should have their libraries in the ASEC
3278 * container already.
3279 *
3280 * In other words, we're going to unpack the binaries
3281 * only for non-system apps and system app upgrades.
3282 */
Kenny Root831baa22010-10-05 12:29:25 -07003283 if (pkg.applicationInfo.nativeLibraryDir != null) {
3284 final File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3285 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3286 /*
3287 * Upgrading from a previous version of the OS sometimes
3288 * leaves native libraries in the /data/data/<app>/lib
3289 * directory for system apps even when they shouldn't be.
3290 * Recent changes in the JNI library search path
3291 * necessitates we remove those to match previous behavior.
3292 */
3293 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(sharedLibraryDir)) {
3294 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3295 }
3296 } else if (!isExternal(pkg)) {
3297 Log.i(TAG, path + " changed; unpacking");
Kenny Root6a6b0072010-10-07 16:46:10 -07003298 mInstaller.unlinkNativeLibraryDirectory(dataPath.getPath());
Kenny Root831baa22010-10-05 12:29:25 -07003299 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003300 } else {
3301 mInstaller.linkNativeLibraryDirectory(dataPath.getPath(),
3302 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003304 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003305 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003306
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003307 if ((scanMode&SCAN_NO_DEX) == 0) {
3308 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3310 return null;
3311 }
3312 }
3313 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 if (mFactoryTest && pkg.requestedPermissions.contains(
3316 android.Manifest.permission.FACTORY_TEST)) {
3317 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3318 }
3319
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003320 // Request the ActivityManager to kill the process(only for existing packages)
3321 // so that we do not end up in a confused state while the user is still using the older
3322 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003323 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003324 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003325 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003326 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003329 // We don't expect installation to fail beyond this point,
3330 if ((scanMode&SCAN_MONITOR) != 0) {
3331 mAppDirs.put(pkg.mPath, pkg);
3332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003334 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003336 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003337 // Make sure we don't accidentally delete its data.
3338 mSettings.mPackagesToBeCleaned.remove(pkgName);
3339
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003340 // Take care of first install / last update times.
3341 if (currentTime != 0) {
3342 if (pkgSetting.firstInstallTime == 0) {
3343 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3344 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3345 pkgSetting.lastUpdateTime = currentTime;
3346 }
3347 } else if (pkgSetting.firstInstallTime == 0) {
3348 // We need *something*. Take time time stamp of the file.
3349 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3350 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3351 if (scanFileTime != pkgSetting.timeStamp) {
3352 // A package on the system image has changed; consider this
3353 // to be an update.
3354 pkgSetting.lastUpdateTime = scanFileTime;
3355 }
3356 }
3357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 int N = pkg.providers.size();
3359 StringBuilder r = null;
3360 int i;
3361 for (i=0; i<N; i++) {
3362 PackageParser.Provider p = pkg.providers.get(i);
3363 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3364 p.info.processName, pkg.applicationInfo.uid);
3365 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3366 p.info.name), p);
3367 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003368 if (p.info.authority != null) {
3369 String names[] = p.info.authority.split(";");
3370 p.info.authority = null;
3371 for (int j = 0; j < names.length; j++) {
3372 if (j == 1 && p.syncable) {
3373 // We only want the first authority for a provider to possibly be
3374 // syncable, so if we already added this provider using a different
3375 // authority clear the syncable flag. We copy the provider before
3376 // changing it because the mProviders object contains a reference
3377 // to a provider that we don't want to change.
3378 // Only do this for the second authority since the resulting provider
3379 // object can be the same for all future authorities for this provider.
3380 p = new PackageParser.Provider(p);
3381 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003383 if (!mProviders.containsKey(names[j])) {
3384 mProviders.put(names[j], p);
3385 if (p.info.authority == null) {
3386 p.info.authority = names[j];
3387 } else {
3388 p.info.authority = p.info.authority + ";" + names[j];
3389 }
3390 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3391 Log.d(TAG, "Registered content provider: " + names[j] +
3392 ", className = " + p.info.name +
3393 ", isSyncable = " + p.info.isSyncable);
3394 } else {
3395 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003396 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003397 " (in package " + pkg.applicationInfo.packageName +
3398 "): name already used by "
3399 + ((other != null && other.getComponentName() != null)
3400 ? other.getComponentName().getPackageName() : "?"));
3401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 }
3403 }
3404 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3405 if (r == null) {
3406 r = new StringBuilder(256);
3407 } else {
3408 r.append(' ');
3409 }
3410 r.append(p.info.name);
3411 }
3412 }
3413 if (r != null) {
3414 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3415 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 N = pkg.services.size();
3418 r = null;
3419 for (i=0; i<N; i++) {
3420 PackageParser.Service s = pkg.services.get(i);
3421 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3422 s.info.processName, pkg.applicationInfo.uid);
3423 mServices.addService(s);
3424 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3425 if (r == null) {
3426 r = new StringBuilder(256);
3427 } else {
3428 r.append(' ');
3429 }
3430 r.append(s.info.name);
3431 }
3432 }
3433 if (r != null) {
3434 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3435 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 N = pkg.receivers.size();
3438 r = null;
3439 for (i=0; i<N; i++) {
3440 PackageParser.Activity a = pkg.receivers.get(i);
3441 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3442 a.info.processName, pkg.applicationInfo.uid);
3443 mReceivers.addActivity(a, "receiver");
3444 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3445 if (r == null) {
3446 r = new StringBuilder(256);
3447 } else {
3448 r.append(' ');
3449 }
3450 r.append(a.info.name);
3451 }
3452 }
3453 if (r != null) {
3454 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3455 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 N = pkg.activities.size();
3458 r = null;
3459 for (i=0; i<N; i++) {
3460 PackageParser.Activity a = pkg.activities.get(i);
3461 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3462 a.info.processName, pkg.applicationInfo.uid);
3463 mActivities.addActivity(a, "activity");
3464 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3465 if (r == null) {
3466 r = new StringBuilder(256);
3467 } else {
3468 r.append(' ');
3469 }
3470 r.append(a.info.name);
3471 }
3472 }
3473 if (r != null) {
3474 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3475 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003477 N = pkg.permissionGroups.size();
3478 r = null;
3479 for (i=0; i<N; i++) {
3480 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3481 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3482 if (cur == null) {
3483 mPermissionGroups.put(pg.info.name, pg);
3484 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3485 if (r == null) {
3486 r = new StringBuilder(256);
3487 } else {
3488 r.append(' ');
3489 }
3490 r.append(pg.info.name);
3491 }
3492 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003493 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 + pg.info.packageName + " ignored: original from "
3495 + cur.info.packageName);
3496 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3497 if (r == null) {
3498 r = new StringBuilder(256);
3499 } else {
3500 r.append(' ');
3501 }
3502 r.append("DUP:");
3503 r.append(pg.info.name);
3504 }
3505 }
3506 }
3507 if (r != null) {
3508 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3509 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 N = pkg.permissions.size();
3512 r = null;
3513 for (i=0; i<N; i++) {
3514 PackageParser.Permission p = pkg.permissions.get(i);
3515 HashMap<String, BasePermission> permissionMap =
3516 p.tree ? mSettings.mPermissionTrees
3517 : mSettings.mPermissions;
3518 p.group = mPermissionGroups.get(p.info.group);
3519 if (p.info.group == null || p.group != null) {
3520 BasePermission bp = permissionMap.get(p.info.name);
3521 if (bp == null) {
3522 bp = new BasePermission(p.info.name, p.info.packageName,
3523 BasePermission.TYPE_NORMAL);
3524 permissionMap.put(p.info.name, bp);
3525 }
3526 if (bp.perm == null) {
3527 if (bp.sourcePackage == null
3528 || bp.sourcePackage.equals(p.info.packageName)) {
3529 BasePermission tree = findPermissionTreeLP(p.info.name);
3530 if (tree == null
3531 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003532 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 bp.perm = p;
3534 bp.uid = pkg.applicationInfo.uid;
3535 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3536 if (r == null) {
3537 r = new StringBuilder(256);
3538 } else {
3539 r.append(' ');
3540 }
3541 r.append(p.info.name);
3542 }
3543 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003544 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 + p.info.packageName + " ignored: base tree "
3546 + tree.name + " is from package "
3547 + tree.sourcePackage);
3548 }
3549 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003550 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 + p.info.packageName + " ignored: original from "
3552 + bp.sourcePackage);
3553 }
3554 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3555 if (r == null) {
3556 r = new StringBuilder(256);
3557 } else {
3558 r.append(' ');
3559 }
3560 r.append("DUP:");
3561 r.append(p.info.name);
3562 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003563 if (bp.perm == p) {
3564 bp.protectionLevel = p.info.protectionLevel;
3565 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003566 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003567 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003568 + p.info.packageName + " ignored: no group "
3569 + p.group);
3570 }
3571 }
3572 if (r != null) {
3573 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3574 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 N = pkg.instrumentation.size();
3577 r = null;
3578 for (i=0; i<N; i++) {
3579 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3580 a.info.packageName = pkg.applicationInfo.packageName;
3581 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3582 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3583 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003584 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003585 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3587 if (r == null) {
3588 r = new StringBuilder(256);
3589 } else {
3590 r.append(' ');
3591 }
3592 r.append(a.info.name);
3593 }
3594 }
3595 if (r != null) {
3596 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3597 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003598
Dianne Hackborn854060af2009-07-09 18:14:31 -07003599 if (pkg.protectedBroadcasts != null) {
3600 N = pkg.protectedBroadcasts.size();
3601 for (i=0; i<N; i++) {
3602 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3603 }
3604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606 pkgSetting.setTimeStamp(scanFileTime);
3607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 return pkg;
3610 }
3611
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003612 private void killApplication(String pkgName, int uid) {
3613 // Request the ActivityManager to kill the process(only for existing packages)
3614 // so that we do not end up in a confused state while the user is still using the older
3615 // version of the application while the new one gets installed.
3616 IActivityManager am = ActivityManagerNative.getDefault();
3617 if (am != null) {
3618 try {
3619 am.killApplicationWithUid(pkgName, uid);
3620 } catch (RemoteException e) {
3621 }
3622 }
3623 }
3624
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003625 // Return the path of the directory that will contain the native binaries
3626 // of a given installed package. This is relative to the data path.
3627 //
Kenny Root85387d72010-08-26 10:13:11 -07003628 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3629 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3630 if (nativeLibraryDir != null) {
3631 return new File(nativeLibraryDir);
3632 } else {
3633 // Fall back for old packages
3634 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3635 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003636 }
3637
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3639 if (chatty && Config.LOGD) Log.d(
3640 TAG, "Removing package " + pkg.applicationInfo.packageName );
3641
3642 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 mPackages.remove(pkg.applicationInfo.packageName);
3646 if (pkg.mPath != null) {
3647 mAppDirs.remove(pkg.mPath);
3648 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 PackageSetting ps = (PackageSetting)pkg.mExtras;
3651 if (ps != null && ps.sharedUser != null) {
3652 // XXX don't do this until the data is removed.
3653 if (false) {
3654 ps.sharedUser.packages.remove(ps);
3655 if (ps.sharedUser.packages.size() == 0) {
3656 // Remove.
3657 }
3658 }
3659 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 int N = pkg.providers.size();
3662 StringBuilder r = null;
3663 int i;
3664 for (i=0; i<N; i++) {
3665 PackageParser.Provider p = pkg.providers.get(i);
3666 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3667 p.info.name));
3668 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003670 /* The is another ContentProvider with this authority when
3671 * this app was installed so this authority is null,
3672 * Ignore it as we don't have to unregister the provider.
3673 */
3674 continue;
3675 }
3676 String names[] = p.info.authority.split(";");
3677 for (int j = 0; j < names.length; j++) {
3678 if (mProviders.get(names[j]) == p) {
3679 mProviders.remove(names[j]);
3680 if (chatty && Config.LOGD) Log.d(
3681 TAG, "Unregistered content provider: " + names[j] +
3682 ", className = " + p.info.name +
3683 ", isSyncable = " + p.info.isSyncable);
3684 }
3685 }
3686 if (chatty) {
3687 if (r == null) {
3688 r = new StringBuilder(256);
3689 } else {
3690 r.append(' ');
3691 }
3692 r.append(p.info.name);
3693 }
3694 }
3695 if (r != null) {
3696 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 N = pkg.services.size();
3700 r = null;
3701 for (i=0; i<N; i++) {
3702 PackageParser.Service s = pkg.services.get(i);
3703 mServices.removeService(s);
3704 if (chatty) {
3705 if (r == null) {
3706 r = new StringBuilder(256);
3707 } else {
3708 r.append(' ');
3709 }
3710 r.append(s.info.name);
3711 }
3712 }
3713 if (r != null) {
3714 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 N = pkg.receivers.size();
3718 r = null;
3719 for (i=0; i<N; i++) {
3720 PackageParser.Activity a = pkg.receivers.get(i);
3721 mReceivers.removeActivity(a, "receiver");
3722 if (chatty) {
3723 if (r == null) {
3724 r = new StringBuilder(256);
3725 } else {
3726 r.append(' ');
3727 }
3728 r.append(a.info.name);
3729 }
3730 }
3731 if (r != null) {
3732 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3733 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 N = pkg.activities.size();
3736 r = null;
3737 for (i=0; i<N; i++) {
3738 PackageParser.Activity a = pkg.activities.get(i);
3739 mActivities.removeActivity(a, "activity");
3740 if (chatty) {
3741 if (r == null) {
3742 r = new StringBuilder(256);
3743 } else {
3744 r.append(' ');
3745 }
3746 r.append(a.info.name);
3747 }
3748 }
3749 if (r != null) {
3750 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3751 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003752
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 N = pkg.permissions.size();
3754 r = null;
3755 for (i=0; i<N; i++) {
3756 PackageParser.Permission p = pkg.permissions.get(i);
3757 boolean tree = false;
3758 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3759 if (bp == null) {
3760 tree = true;
3761 bp = mSettings.mPermissionTrees.get(p.info.name);
3762 }
3763 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003764 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 if (chatty) {
3766 if (r == null) {
3767 r = new StringBuilder(256);
3768 } else {
3769 r.append(' ');
3770 }
3771 r.append(p.info.name);
3772 }
3773 }
3774 }
3775 if (r != null) {
3776 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3777 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 N = pkg.instrumentation.size();
3780 r = null;
3781 for (i=0; i<N; i++) {
3782 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003783 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 if (chatty) {
3785 if (r == null) {
3786 r = new StringBuilder(256);
3787 } else {
3788 r.append(' ');
3789 }
3790 r.append(a.info.name);
3791 }
3792 }
3793 if (r != null) {
3794 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3795 }
3796 }
3797 }
3798
3799 private static final boolean isPackageFilename(String name) {
3800 return name != null && name.endsWith(".apk");
3801 }
3802
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003803 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3804 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3805 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3806 return true;
3807 }
3808 }
3809 return false;
3810 }
3811
3812 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003813 PackageParser.Package pkgInfo, boolean grantPermissions,
3814 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 // Make sure there are no dangling permission trees.
3816 Iterator<BasePermission> it = mSettings.mPermissionTrees
3817 .values().iterator();
3818 while (it.hasNext()) {
3819 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003820 if (bp.packageSetting == null) {
3821 // We may not yet have parsed the package, so just see if
3822 // we still know about its settings.
3823 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3824 }
3825 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003826 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 + " from package " + bp.sourcePackage);
3828 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003829 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3830 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3831 Slog.i(TAG, "Removing old permission tree: " + bp.name
3832 + " from package " + bp.sourcePackage);
3833 grantPermissions = true;
3834 it.remove();
3835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003836 }
3837 }
3838
3839 // Make sure all dynamic permissions have been assigned to a package,
3840 // and make sure there are no dangling permissions.
3841 it = mSettings.mPermissions.values().iterator();
3842 while (it.hasNext()) {
3843 BasePermission bp = it.next();
3844 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3845 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3846 + bp.name + " pkg=" + bp.sourcePackage
3847 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003848 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 BasePermission tree = findPermissionTreeLP(bp.name);
3850 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003851 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 bp.perm = new PackageParser.Permission(tree.perm.owner,
3853 new PermissionInfo(bp.pendingInfo));
3854 bp.perm.info.packageName = tree.perm.info.packageName;
3855 bp.perm.info.name = bp.name;
3856 bp.uid = tree.uid;
3857 }
3858 }
3859 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003860 if (bp.packageSetting == null) {
3861 // We may not yet have parsed the package, so just see if
3862 // we still know about its settings.
3863 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3864 }
3865 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003866 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 + " from package " + bp.sourcePackage);
3868 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003869 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3870 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3871 Slog.i(TAG, "Removing old permission: " + bp.name
3872 + " from package " + bp.sourcePackage);
3873 grantPermissions = true;
3874 it.remove();
3875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 }
3877 }
3878
3879 // Now update the permissions for all packages, in particular
3880 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003881 if (grantPermissions) {
3882 for (PackageParser.Package pkg : mPackages.values()) {
3883 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003884 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003885 }
3886 }
3887 }
3888
3889 if (pkgInfo != null) {
3890 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 }
3892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003894 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3895 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3896 if (ps == null) {
3897 return;
3898 }
3899 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003900 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 if (replace) {
3903 ps.permissionsFixed = false;
3904 if (gp == ps) {
3905 gp.grantedPermissions.clear();
3906 gp.gids = mGlobalGids;
3907 }
3908 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003910 if (gp.gids == null) {
3911 gp.gids = mGlobalGids;
3912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003914 final int N = pkg.requestedPermissions.size();
3915 for (int i=0; i<N; i++) {
3916 String name = pkg.requestedPermissions.get(i);
3917 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003918 if (false) {
3919 if (gp != ps) {
3920 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003921 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 }
3923 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003924 if (bp != null && bp.packageSetting != null) {
3925 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003926 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003927 boolean allowedSig = false;
3928 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3929 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003930 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003931 } else if (bp.packageSetting == null) {
3932 // This permission is invalid; skip it.
3933 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003934 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3935 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003936 allowed = (checkSignaturesLP(
3937 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003938 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003939 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003941 if (!allowed && bp.protectionLevel
3942 == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003943 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003944 // For updated system applications, the signatureOrSystem permission
3945 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003946 if (isUpdatedSystemApp(pkg)) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003947 PackageSetting sysPs = mSettings.getDisabledSystemPkg(
3948 pkg.packageName);
3949 final GrantedPermissions origGp = sysPs.sharedUser != null
3950 ? sysPs.sharedUser : sysPs;
3951 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 allowed = true;
3953 } else {
3954 allowed = false;
3955 }
3956 } else {
3957 allowed = true;
3958 }
3959 }
3960 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003961 if (allowed) {
3962 allowedSig = true;
3963 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 } else {
3965 allowed = false;
3966 }
3967 if (false) {
3968 if (gp != ps) {
3969 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3970 }
3971 }
3972 if (allowed) {
3973 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3974 && ps.permissionsFixed) {
3975 // If this is an existing, non-system package, then
3976 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003977 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003979 // Except... if this is a permission that was added
3980 // to the platform (note: need to only do this when
3981 // updating the platform).
3982 final int NP = PackageParser.NEW_PERMISSIONS.length;
3983 for (int ip=0; ip<NP; ip++) {
3984 final PackageParser.NewPermissionInfo npi
3985 = PackageParser.NEW_PERMISSIONS[ip];
3986 if (npi.name.equals(perm)
3987 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3988 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003989 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003990 + pkg.packageName);
3991 break;
3992 }
3993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003994 }
3995 }
3996 if (allowed) {
3997 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003998 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 gp.grantedPermissions.add(perm);
4000 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004001 } else if (!ps.haveGids) {
4002 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 }
4004 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004005 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 + " to package " + pkg.packageName
4007 + " because it was previously installed without");
4008 }
4009 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004010 if (gp.grantedPermissions.remove(perm)) {
4011 changedPermission = true;
4012 gp.gids = removeInts(gp.gids, bp.gids);
4013 Slog.i(TAG, "Un-granting permission " + perm
4014 + " from package " + pkg.packageName
4015 + " (protectionLevel=" + bp.protectionLevel
4016 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4017 + ")");
4018 } else {
4019 Slog.w(TAG, "Not granting permission " + perm
4020 + " to package " + pkg.packageName
4021 + " (protectionLevel=" + bp.protectionLevel
4022 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4023 + ")");
4024 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 }
4026 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004027 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 + " in package " + pkg.packageName);
4029 }
4030 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004031
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004032 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004033 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4034 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 // This is the first that we have heard about this package, so the
4036 // permissions we have now selected are fixed until explicitly
4037 // changed.
4038 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004039 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004040 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004041 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004042
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 private final class ActivityIntentResolver
4044 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004045 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004047 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 }
4049
Mihai Preda074edef2009-05-18 17:13:31 +02004050 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004052 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4054 }
4055
Mihai Predaeae850c2009-05-13 10:13:48 +02004056 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4057 ArrayList<PackageParser.Activity> packageActivities) {
4058 if (packageActivities == null) {
4059 return null;
4060 }
4061 mFlags = flags;
4062 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4063 int N = packageActivities.size();
4064 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4065 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004066
4067 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004068 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004069 intentFilters = packageActivities.get(i).intents;
4070 if (intentFilters != null && intentFilters.size() > 0) {
4071 listCut.add(intentFilters);
4072 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004073 }
4074 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4075 }
4076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004077 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004078 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004079 if (SHOW_INFO || Config.LOGV) Log.v(
4080 TAG, " " + type + " " +
4081 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4082 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4083 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004084 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4086 if (SHOW_INFO || Config.LOGV) {
4087 Log.v(TAG, " IntentFilter:");
4088 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4089 }
4090 if (!intent.debugCheck()) {
4091 Log.w(TAG, "==> For Activity " + a.info.name);
4092 }
4093 addFilter(intent);
4094 }
4095 }
4096
4097 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004098 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004099 if (SHOW_INFO || Config.LOGV) Log.v(
4100 TAG, " " + type + " " +
4101 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4102 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4103 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004104 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004105 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4106 if (SHOW_INFO || Config.LOGV) {
4107 Log.v(TAG, " IntentFilter:");
4108 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4109 }
4110 removeFilter(intent);
4111 }
4112 }
4113
4114 @Override
4115 protected boolean allowFilterResult(
4116 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4117 ActivityInfo filterAi = filter.activity.info;
4118 for (int i=dest.size()-1; i>=0; i--) {
4119 ActivityInfo destAi = dest.get(i).activityInfo;
4120 if (destAi.name == filterAi.name
4121 && destAi.packageName == filterAi.packageName) {
4122 return false;
4123 }
4124 }
4125 return true;
4126 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004129 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4130 return info.activity.owner.packageName;
4131 }
4132
4133 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4135 int match) {
4136 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4137 return null;
4138 }
4139 final PackageParser.Activity activity = info.activity;
4140 if (mSafeMode && (activity.info.applicationInfo.flags
4141 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4142 return null;
4143 }
4144 final ResolveInfo res = new ResolveInfo();
4145 res.activityInfo = PackageParser.generateActivityInfo(activity,
4146 mFlags);
4147 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4148 res.filter = info;
4149 }
4150 res.priority = info.getPriority();
4151 res.preferredOrder = activity.owner.mPreferredOrder;
4152 //System.out.println("Result: " + res.activityInfo.className +
4153 // " = " + res.priority);
4154 res.match = match;
4155 res.isDefault = info.hasDefault;
4156 res.labelRes = info.labelRes;
4157 res.nonLocalizedLabel = info.nonLocalizedLabel;
4158 res.icon = info.icon;
4159 return res;
4160 }
4161
4162 @Override
4163 protected void sortResults(List<ResolveInfo> results) {
4164 Collections.sort(results, mResolvePrioritySorter);
4165 }
4166
4167 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004168 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004169 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004170 out.print(prefix); out.print(
4171 Integer.toHexString(System.identityHashCode(filter.activity)));
4172 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004173 out.print(filter.activity.getComponentShortName());
4174 out.print(" filter ");
4175 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 }
4177
4178// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4179// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4180// final List<ResolveInfo> retList = Lists.newArrayList();
4181// while (i.hasNext()) {
4182// final ResolveInfo resolveInfo = i.next();
4183// if (isEnabledLP(resolveInfo.activityInfo)) {
4184// retList.add(resolveInfo);
4185// }
4186// }
4187// return retList;
4188// }
4189
4190 // Keys are String (activity class name), values are Activity.
4191 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4192 = new HashMap<ComponentName, PackageParser.Activity>();
4193 private int mFlags;
4194 }
4195
4196 private final class ServiceIntentResolver
4197 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004198 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004199 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004200 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 }
4202
Mihai Preda074edef2009-05-18 17:13:31 +02004203 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004205 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4207 }
4208
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004209 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4210 ArrayList<PackageParser.Service> packageServices) {
4211 if (packageServices == null) {
4212 return null;
4213 }
4214 mFlags = flags;
4215 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4216 int N = packageServices.size();
4217 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4218 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4219
4220 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4221 for (int i = 0; i < N; ++i) {
4222 intentFilters = packageServices.get(i).intents;
4223 if (intentFilters != null && intentFilters.size() > 0) {
4224 listCut.add(intentFilters);
4225 }
4226 }
4227 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4228 }
4229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004231 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232 if (SHOW_INFO || Config.LOGV) Log.v(
4233 TAG, " " + (s.info.nonLocalizedLabel != null
4234 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4235 if (SHOW_INFO || Config.LOGV) Log.v(
4236 TAG, " Class=" + s.info.name);
4237 int NI = s.intents.size();
4238 int j;
4239 for (j=0; j<NI; j++) {
4240 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4241 if (SHOW_INFO || Config.LOGV) {
4242 Log.v(TAG, " IntentFilter:");
4243 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4244 }
4245 if (!intent.debugCheck()) {
4246 Log.w(TAG, "==> For Service " + s.info.name);
4247 }
4248 addFilter(intent);
4249 }
4250 }
4251
4252 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004253 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004254 if (SHOW_INFO || Config.LOGV) Log.v(
4255 TAG, " " + (s.info.nonLocalizedLabel != null
4256 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4257 if (SHOW_INFO || Config.LOGV) Log.v(
4258 TAG, " Class=" + s.info.name);
4259 int NI = s.intents.size();
4260 int j;
4261 for (j=0; j<NI; j++) {
4262 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4263 if (SHOW_INFO || Config.LOGV) {
4264 Log.v(TAG, " IntentFilter:");
4265 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4266 }
4267 removeFilter(intent);
4268 }
4269 }
4270
4271 @Override
4272 protected boolean allowFilterResult(
4273 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4274 ServiceInfo filterSi = filter.service.info;
4275 for (int i=dest.size()-1; i>=0; i--) {
4276 ServiceInfo destAi = dest.get(i).serviceInfo;
4277 if (destAi.name == filterSi.name
4278 && destAi.packageName == filterSi.packageName) {
4279 return false;
4280 }
4281 }
4282 return true;
4283 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004286 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4287 return info.service.owner.packageName;
4288 }
4289
4290 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004291 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4292 int match) {
4293 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4294 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4295 return null;
4296 }
4297 final PackageParser.Service service = info.service;
4298 if (mSafeMode && (service.info.applicationInfo.flags
4299 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4300 return null;
4301 }
4302 final ResolveInfo res = new ResolveInfo();
4303 res.serviceInfo = PackageParser.generateServiceInfo(service,
4304 mFlags);
4305 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4306 res.filter = filter;
4307 }
4308 res.priority = info.getPriority();
4309 res.preferredOrder = service.owner.mPreferredOrder;
4310 //System.out.println("Result: " + res.activityInfo.className +
4311 // " = " + res.priority);
4312 res.match = match;
4313 res.isDefault = info.hasDefault;
4314 res.labelRes = info.labelRes;
4315 res.nonLocalizedLabel = info.nonLocalizedLabel;
4316 res.icon = info.icon;
4317 return res;
4318 }
4319
4320 @Override
4321 protected void sortResults(List<ResolveInfo> results) {
4322 Collections.sort(results, mResolvePrioritySorter);
4323 }
4324
4325 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004326 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004327 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004328 out.print(prefix); out.print(
4329 Integer.toHexString(System.identityHashCode(filter.service)));
4330 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004331 out.print(filter.service.getComponentShortName());
4332 out.print(" filter ");
4333 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004334 }
4335
4336// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4337// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4338// final List<ResolveInfo> retList = Lists.newArrayList();
4339// while (i.hasNext()) {
4340// final ResolveInfo resolveInfo = (ResolveInfo) i;
4341// if (isEnabledLP(resolveInfo.serviceInfo)) {
4342// retList.add(resolveInfo);
4343// }
4344// }
4345// return retList;
4346// }
4347
4348 // Keys are String (activity class name), values are Activity.
4349 private final HashMap<ComponentName, PackageParser.Service> mServices
4350 = new HashMap<ComponentName, PackageParser.Service>();
4351 private int mFlags;
4352 };
4353
4354 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4355 new Comparator<ResolveInfo>() {
4356 public int compare(ResolveInfo r1, ResolveInfo r2) {
4357 int v1 = r1.priority;
4358 int v2 = r2.priority;
4359 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4360 if (v1 != v2) {
4361 return (v1 > v2) ? -1 : 1;
4362 }
4363 v1 = r1.preferredOrder;
4364 v2 = r2.preferredOrder;
4365 if (v1 != v2) {
4366 return (v1 > v2) ? -1 : 1;
4367 }
4368 if (r1.isDefault != r2.isDefault) {
4369 return r1.isDefault ? -1 : 1;
4370 }
4371 v1 = r1.match;
4372 v2 = r2.match;
4373 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4374 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4375 }
4376 };
4377
4378 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4379 new Comparator<ProviderInfo>() {
4380 public int compare(ProviderInfo p1, ProviderInfo p2) {
4381 final int v1 = p1.initOrder;
4382 final int v2 = p2.initOrder;
4383 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4384 }
4385 };
4386
Kenny Root93565c4b2010-06-18 15:46:06 -07004387 private static final boolean DEBUG_OBB = false;
4388
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004389 private static final void sendPackageBroadcast(String action, String pkg,
4390 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 IActivityManager am = ActivityManagerNative.getDefault();
4392 if (am != null) {
4393 try {
4394 final Intent intent = new Intent(action,
4395 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4396 if (extras != null) {
4397 intent.putExtras(extras);
4398 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004399 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004400 am.broadcastIntent(null, intent, null, finishedReceiver,
4401 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 } catch (RemoteException ex) {
4403 }
4404 }
4405 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004406
4407 public String nextPackageToClean(String lastPackage) {
4408 synchronized (mPackages) {
4409 if (!mMediaMounted) {
4410 // If the external storage is no longer mounted at this point,
4411 // the caller may not have been able to delete all of this
4412 // packages files and can not delete any more. Bail.
4413 return null;
4414 }
4415 if (lastPackage != null) {
4416 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4417 }
4418 return mSettings.mPackagesToBeCleaned.size() > 0
4419 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4420 }
4421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004422
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004423 void schedulePackageCleaning(String packageName) {
4424 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4425 }
4426
4427 void startCleaningPackages() {
4428 synchronized (mPackages) {
4429 if (!mMediaMounted) {
4430 return;
4431 }
4432 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4433 return;
4434 }
4435 }
4436 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4437 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4438 IActivityManager am = ActivityManagerNative.getDefault();
4439 if (am != null) {
4440 try {
4441 am.startService(null, intent, null);
4442 } catch (RemoteException e) {
4443 }
4444 }
4445 }
4446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447 private final class AppDirObserver extends FileObserver {
4448 public AppDirObserver(String path, int mask, boolean isrom) {
4449 super(path, mask);
4450 mRootDir = path;
4451 mIsRom = isrom;
4452 }
4453
4454 public void onEvent(int event, String path) {
4455 String removedPackage = null;
4456 int removedUid = -1;
4457 String addedPackage = null;
4458 int addedUid = -1;
4459
4460 synchronized (mInstallLock) {
4461 String fullPathStr = null;
4462 File fullPath = null;
4463 if (path != null) {
4464 fullPath = new File(mRootDir, path);
4465 fullPathStr = fullPath.getPath();
4466 }
4467
4468 if (Config.LOGV) Log.v(
4469 TAG, "File " + fullPathStr + " changed: "
4470 + Integer.toHexString(event));
4471
4472 if (!isPackageFilename(path)) {
4473 if (Config.LOGV) Log.v(
4474 TAG, "Ignoring change of non-package file: " + fullPathStr);
4475 return;
4476 }
4477
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004478 // Ignore packages that are being installed or
4479 // have just been installed.
4480 if (ignoreCodePath(fullPathStr)) {
4481 return;
4482 }
4483 PackageParser.Package p = null;
4484 synchronized (mPackages) {
4485 p = mAppDirs.get(fullPathStr);
4486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004488 if (p != null) {
4489 removePackageLI(p, true);
4490 removedPackage = p.applicationInfo.packageName;
4491 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 }
4493 }
4494
4495 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004497 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004498 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4499 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004500 PackageParser.PARSE_CHATTY |
4501 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004502 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4503 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004504 if (p != null) {
4505 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004506 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004507 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004508 }
4509 addedPackage = p.applicationInfo.packageName;
4510 addedUid = p.applicationInfo.uid;
4511 }
4512 }
4513 }
4514
4515 synchronized (mPackages) {
4516 mSettings.writeLP();
4517 }
4518 }
4519
4520 if (removedPackage != null) {
4521 Bundle extras = new Bundle(1);
4522 extras.putInt(Intent.EXTRA_UID, removedUid);
4523 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004524 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4525 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526 }
4527 if (addedPackage != null) {
4528 Bundle extras = new Bundle(1);
4529 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004530 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4531 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004532 }
4533 }
4534
4535 private final String mRootDir;
4536 private final boolean mIsRom;
4537 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 /* Called when a downloaded package installation has been confirmed by the user */
4540 public void installPackage(
4541 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004542 installPackage(packageURI, observer, flags, null);
4543 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004544
Jacek Surazski65e13172009-04-28 15:26:38 +02004545 /* Called when a downloaded package installation has been confirmed by the user */
4546 public void installPackage(
4547 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4548 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004549 mContext.enforceCallingOrSelfPermission(
4550 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004551
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004552 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004553 msg.obj = new InstallParams(packageURI, observer, flags,
4554 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004555 mHandler.sendMessage(msg);
4556 }
4557
Christopher Tate1bb69062010-02-19 17:02:12 -08004558 public void finishPackageInstall(int token) {
4559 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4560 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4561 mHandler.sendMessage(msg);
4562 }
4563
Kenny Root93565c4b2010-06-18 15:46:06 -07004564 public void setPackageObbPath(String packageName, String path) {
4565 if (DEBUG_OBB)
4566 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4567 PackageSetting pkgSetting;
4568 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004569 final int permission = mContext.checkCallingPermission(
4570 android.Manifest.permission.INSTALL_PACKAGES);
4571 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004572 synchronized (mPackages) {
4573 pkgSetting = mSettings.mPackages.get(packageName);
4574 if (pkgSetting == null) {
4575 throw new IllegalArgumentException("Unknown package: " + packageName);
4576 }
4577 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4578 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4579 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4580 + pkgSetting.userId);
4581 }
4582 pkgSetting.obbPathString = path;
4583 mSettings.writeLP();
4584 }
4585 }
4586
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004587 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 // Queue up an async operation since the package installation may take a little while.
4589 mHandler.post(new Runnable() {
4590 public void run() {
4591 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004592 // Result object to be returned
4593 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004594 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004595 res.uid = -1;
4596 res.pkg = null;
4597 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004598 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004599 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004600 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004601 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004602 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004603 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004605
4606 // A restore should be performed at this point if (a) the install
4607 // succeeded, (b) the operation is not an update, and (c) the new
4608 // package has a backupAgent defined.
4609 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004610 boolean doRestore = (!update
4611 && res.pkg != null
4612 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004613
4614 // Set up the post-install work request bookkeeping. This will be used
4615 // and cleaned up by the post-install event handling regardless of whether
4616 // there's a restore pass performed. Token values are >= 1.
4617 int token;
4618 if (mNextInstallToken < 0) mNextInstallToken = 1;
4619 token = mNextInstallToken++;
4620
4621 PostInstallData data = new PostInstallData(args, res);
4622 mRunningInstalls.put(token, data);
4623 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4624
4625 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4626 // Pass responsibility to the Backup Manager. It will perform a
4627 // restore if appropriate, then pass responsibility back to the
4628 // Package Manager to run the post-install observer callbacks
4629 // and broadcasts.
4630 IBackupManager bm = IBackupManager.Stub.asInterface(
4631 ServiceManager.getService(Context.BACKUP_SERVICE));
4632 if (bm != null) {
4633 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4634 + " to BM for possible restore");
4635 try {
4636 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4637 } catch (RemoteException e) {
4638 // can't happen; the backup manager is local
4639 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004640 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004641 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004642 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004643 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004644 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004645 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004646 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004647 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004648
4649 if (!doRestore) {
4650 // No restore possible, or the Backup Manager was mysteriously not
4651 // available -- just fire the post-install work request directly.
4652 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4653 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4654 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004655 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004656 }
4657 });
4658 }
4659
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004660 abstract class HandlerParams {
4661 final static int MAX_RETRIES = 4;
4662 int retry = 0;
4663 final void startCopy() {
4664 try {
4665 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4666 retry++;
4667 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004668 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004669 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4670 handleServiceError();
4671 return;
4672 } else {
4673 handleStartCopy();
4674 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4675 mHandler.sendEmptyMessage(MCS_UNBIND);
4676 }
4677 } catch (RemoteException e) {
4678 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4679 mHandler.sendEmptyMessage(MCS_RECONNECT);
4680 }
4681 handleReturnCode();
4682 }
4683
4684 final void serviceError() {
4685 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4686 handleServiceError();
4687 handleReturnCode();
4688 }
4689 abstract void handleStartCopy() throws RemoteException;
4690 abstract void handleServiceError();
4691 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004692 }
4693
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004694 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004695 final IPackageInstallObserver observer;
4696 int flags;
4697 final Uri packageURI;
4698 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004699 private InstallArgs mArgs;
4700 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004701 InstallParams(Uri packageURI,
4702 IPackageInstallObserver observer, int flags,
4703 String installerPackageName) {
4704 this.packageURI = packageURI;
4705 this.flags = flags;
4706 this.observer = observer;
4707 this.installerPackageName = installerPackageName;
4708 }
4709
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004710 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4711 String packageName = pkgLite.packageName;
4712 int installLocation = pkgLite.installLocation;
4713 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4714 synchronized (mPackages) {
4715 PackageParser.Package pkg = mPackages.get(packageName);
4716 if (pkg != null) {
4717 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4718 // Check for updated system application.
4719 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4720 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004721 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004722 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4723 }
4724 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4725 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004726 if (onSd) {
4727 // Install flag overrides everything.
4728 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4729 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004730 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004731 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4732 // Application explicitly specified internal.
4733 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4734 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4735 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004736 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004737 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004738 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004739 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4740 }
4741 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004742 }
4743 }
4744 } else {
4745 // Invalid install. Return error code
4746 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4747 }
4748 }
4749 }
4750 // All the special cases have been taken care of.
4751 // Return result based on recommended install location.
4752 if (onSd) {
4753 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4754 }
4755 return pkgLite.recommendedInstallLocation;
4756 }
4757
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004758 /*
4759 * Invoke remote method to get package information and install
4760 * location values. Override install location based on default
4761 * policy if needed and then create install arguments based
4762 * on the install location.
4763 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004764 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004765 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004766 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4767 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004768 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4769 if (onInt && onSd) {
4770 // Check if both bits are set.
4771 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4772 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4773 } else if (fwdLocked && onSd) {
4774 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004775 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004776 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004777 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004778 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07004779 final PackageInfoLite pkgLite;
4780 try {
4781 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4782 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4783 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
4784 } finally {
4785 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4786 }
4787
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004788 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004789 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4790 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4791 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4792 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4793 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004794 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4795 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4796 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004797 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4798 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004799 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004800 // Override with defaults if needed.
4801 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004802 if (!onSd && !onInt) {
4803 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004804 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4805 // Set the flag to install on external media.
4806 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004807 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004808 } else {
4809 // Make sure the flag for installing on external
4810 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004811 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004812 flags &= ~PackageManager.INSTALL_EXTERNAL;
4813 }
4814 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004815 }
4816 }
4817 // Create the file args now.
4818 mArgs = createInstallArgs(this);
4819 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4820 // Create copy only if we are not in an erroneous state.
4821 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004822 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004823 }
4824 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004825 }
4826
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004827 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004828 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004829 // If mArgs is null, then MCS couldn't be reached. When it
4830 // reconnects, it will try again to install. At that point, this
4831 // will succeed.
4832 if (mArgs != null) {
4833 processPendingInstall(mArgs, mRet);
4834 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004835 }
4836
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004837 @Override
4838 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004839 mArgs = createInstallArgs(this);
4840 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004841 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004842 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004843
4844 /*
4845 * Utility class used in movePackage api.
4846 * srcArgs and targetArgs are not set for invalid flags and make
4847 * sure to do null checks when invoking methods on them.
4848 * We probably want to return ErrorPrams for both failed installs
4849 * and moves.
4850 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004851 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004852 final IPackageMoveObserver observer;
4853 final int flags;
4854 final String packageName;
4855 final InstallArgs srcArgs;
4856 final InstallArgs targetArgs;
4857 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004858
4859 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4860 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004861 this.srcArgs = srcArgs;
4862 this.observer = observer;
4863 this.flags = flags;
4864 this.packageName = packageName;
4865 if (srcArgs != null) {
4866 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004867 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004868 } else {
4869 targetArgs = null;
4870 }
4871 }
4872
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004873 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004874 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4875 // Check for storage space on target medium
4876 if (!targetArgs.checkFreeStorage(mContainerService)) {
4877 Log.w(TAG, "Insufficient storage to install");
4878 return;
4879 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004880 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004881 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004882 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004883 if (DEBUG_SD_INSTALL) {
4884 StringBuilder builder = new StringBuilder();
4885 if (srcArgs != null) {
4886 builder.append("src: ");
4887 builder.append(srcArgs.getCodePath());
4888 }
4889 if (targetArgs != null) {
4890 builder.append(" target : ");
4891 builder.append(targetArgs.getCodePath());
4892 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004893 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004894 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004895 }
4896
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004897 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004898 void handleReturnCode() {
4899 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004900 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4901 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4902 currentStatus = PackageManager.MOVE_SUCCEEDED;
4903 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4904 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4905 }
4906 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004907 }
4908
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004909 @Override
4910 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004911 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004912 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004913 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004914
4915 private InstallArgs createInstallArgs(InstallParams params) {
4916 if (installOnSd(params.flags)) {
4917 return new SdInstallArgs(params);
4918 } else {
4919 return new FileInstallArgs(params);
4920 }
4921 }
4922
Kenny Root85387d72010-08-26 10:13:11 -07004923 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4924 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004925 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004926 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004927 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004928 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004929 }
4930 }
4931
Kenny Root85387d72010-08-26 10:13:11 -07004932 // Used by package mover
4933 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004934 if (installOnSd(flags)) {
4935 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4936 return new SdInstallArgs(packageURI, cid);
4937 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004938 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004939 }
4940 }
4941
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004942 static abstract class InstallArgs {
4943 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004944 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004945 final int flags;
4946 final Uri packageURI;
4947 final String installerPackageName;
4948
4949 InstallArgs(Uri packageURI,
4950 IPackageInstallObserver observer, int flags,
4951 String installerPackageName) {
4952 this.packageURI = packageURI;
4953 this.flags = flags;
4954 this.observer = observer;
4955 this.installerPackageName = installerPackageName;
4956 }
4957
4958 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004959 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004960 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004961 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004962 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004963 abstract String getCodePath();
4964 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004965 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004966 // Need installer lock especially for dex file removal.
4967 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004968 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004969 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004970 }
4971
4972 class FileInstallArgs extends InstallArgs {
4973 File installDir;
4974 String codeFileName;
4975 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004976 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004977 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004978
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004979 FileInstallArgs(InstallParams params) {
4980 super(params.packageURI, params.observer,
4981 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004982 }
4983
Kenny Root85387d72010-08-26 10:13:11 -07004984 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004985 super(null, null, 0, null);
4986 File codeFile = new File(fullCodePath);
4987 installDir = codeFile.getParentFile();
4988 codeFileName = fullCodePath;
4989 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004990 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004991 }
4992
Kenny Root85387d72010-08-26 10:13:11 -07004993 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004994 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004995 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004996 String apkName = getNextCodePath(null, pkgName, ".apk");
4997 codeFileName = new File(installDir, apkName + ".apk").getPath();
4998 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004999 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005000 }
5001
Kenny Root11128572010-10-11 10:51:32 -07005002 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5003 try {
5004 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5005 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5006 return imcs.checkFreeStorage(false, packageURI);
5007 } finally {
5008 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5009 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005010 }
5011
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005012 String getCodePath() {
5013 return codeFileName;
5014 }
5015
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005016 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005017 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005018 codeFileName = createTempPackageFile(installDir).getPath();
5019 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005020 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005021 }
5022
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005023 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005024 if (temp) {
5025 // Generate temp file name
5026 createCopyFile();
5027 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005028 // Get a ParcelFileDescriptor to write to the output file
5029 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005030 if (!created) {
5031 try {
5032 codeFile.createNewFile();
5033 // Set permissions
5034 if (!setPermissions()) {
5035 // Failed setting permissions.
5036 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5037 }
5038 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005039 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005040 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5041 }
5042 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005043 ParcelFileDescriptor out = null;
5044 try {
Kenny Root85387d72010-08-26 10:13:11 -07005045 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005046 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005047 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005048 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5049 }
5050 // Copy the resource now
5051 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5052 try {
Kenny Root11128572010-10-11 10:51:32 -07005053 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5054 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005055 if (imcs.copyResource(packageURI, out)) {
5056 ret = PackageManager.INSTALL_SUCCEEDED;
5057 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005058 } finally {
5059 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005060 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005061 }
Kenny Root85387d72010-08-26 10:13:11 -07005062
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005063 return ret;
5064 }
5065
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005066 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005067 if (status != PackageManager.INSTALL_SUCCEEDED) {
5068 cleanUp();
5069 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005070 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005071 }
5072
5073 boolean doRename(int status, final String pkgName, String oldCodePath) {
5074 if (status != PackageManager.INSTALL_SUCCEEDED) {
5075 cleanUp();
5076 return false;
5077 } else {
5078 // Rename based on packageName
5079 File codeFile = new File(getCodePath());
5080 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5081 File desFile = new File(installDir, apkName + ".apk");
5082 if (!codeFile.renameTo(desFile)) {
5083 return false;
5084 }
5085 // Reset paths since the file has been renamed.
5086 codeFileName = desFile.getPath();
5087 resourceFileName = getResourcePathFromCodePath();
5088 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005089 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005090 // Failed setting permissions.
5091 return false;
5092 }
5093 return true;
5094 }
5095 }
5096
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005097 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005098 if (status != PackageManager.INSTALL_SUCCEEDED) {
5099 cleanUp();
5100 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005101 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005102 }
5103
5104 String getResourcePath() {
5105 return resourceFileName;
5106 }
5107
5108 String getResourcePathFromCodePath() {
5109 String codePath = getCodePath();
5110 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5111 String apkNameOnly = getApkName(codePath);
5112 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5113 } else {
5114 return codePath;
5115 }
5116 }
5117
Kenny Root85387d72010-08-26 10:13:11 -07005118 @Override
5119 String getNativeLibraryPath() {
5120 return libraryPath;
5121 }
5122
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005123 private boolean cleanUp() {
5124 boolean ret = true;
5125 String sourceDir = getCodePath();
5126 String publicSourceDir = getResourcePath();
5127 if (sourceDir != null) {
5128 File sourceFile = new File(sourceDir);
5129 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005130 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005131 ret = false;
5132 }
5133 // Delete application's code and resources
5134 sourceFile.delete();
5135 }
5136 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5137 final File publicSourceFile = new File(publicSourceDir);
5138 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005139 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005140 }
5141 if (publicSourceFile.exists()) {
5142 publicSourceFile.delete();
5143 }
5144 }
5145 return ret;
5146 }
5147
5148 void cleanUpResourcesLI() {
5149 String sourceDir = getCodePath();
5150 if (cleanUp() && mInstaller != null) {
5151 int retCode = mInstaller.rmdex(sourceDir);
5152 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005153 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005154 + " at location "
5155 + sourceDir + ", retcode=" + retCode);
5156 // we don't consider this to be a failure of the core package deletion
5157 }
5158 }
5159 }
5160
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005161 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005162 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005163 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005164 final int filePermissions =
5165 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5166 |FileUtils.S_IROTH;
5167 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5168 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005169 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005170 getCodePath()
5171 + ". The return code was: " + retCode);
5172 // TODO Define new internal error
5173 return false;
5174 }
5175 return true;
5176 }
5177 return true;
5178 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005179
5180 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005181 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005182 cleanUpResourcesLI();
5183 return true;
5184 }
Kenny Root85387d72010-08-26 10:13:11 -07005185
5186 private boolean isFwdLocked() {
5187 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5188 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005189 }
5190
5191 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005192 static final String RES_FILE_NAME = "pkg.apk";
5193
Kenny Root85387d72010-08-26 10:13:11 -07005194 String cid;
5195 String packagePath;
5196 String libraryPath;
5197
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005198 SdInstallArgs(InstallParams params) {
5199 super(params.packageURI, params.observer,
5200 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005201 }
5202
Kenny Root85387d72010-08-26 10:13:11 -07005203 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005204 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005205 // Extract cid from fullCodePath
5206 int eidx = fullCodePath.lastIndexOf("/");
5207 String subStr1 = fullCodePath.substring(0, eidx);
5208 int sidx = subStr1.lastIndexOf("/");
5209 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005210 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005211 }
5212
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005213 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005214 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5215 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005216 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005217 }
5218
5219 SdInstallArgs(Uri packageURI, String cid) {
5220 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005221 this.cid = cid;
5222 }
5223
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005224 void createCopyFile() {
5225 cid = getTempContainerId();
5226 }
5227
Kenny Root11128572010-10-11 10:51:32 -07005228 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5229 try {
5230 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5231 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5232 return imcs.checkFreeStorage(true, packageURI);
5233 } finally {
5234 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5235 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005236 }
5237
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005238 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005239 if (temp) {
5240 createCopyFile();
5241 }
Kenny Root11128572010-10-11 10:51:32 -07005242
5243 final String newCachePath;
5244 try {
5245 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5246 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5247 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5248 getEncryptKey(), RES_FILE_NAME);
5249 } finally {
5250 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5251 }
5252
Kenny Root85387d72010-08-26 10:13:11 -07005253 if (newCachePath != null) {
5254 setCachePath(newCachePath);
5255 return PackageManager.INSTALL_SUCCEEDED;
5256 } else {
5257 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5258 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005259 }
5260
5261 @Override
5262 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005263 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005264 }
5265
5266 @Override
5267 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005268 return packagePath;
5269 }
5270
5271 @Override
5272 String getNativeLibraryPath() {
5273 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005274 }
5275
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005276 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005277 if (status != PackageManager.INSTALL_SUCCEEDED) {
5278 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005279 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005280 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005281 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005282 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005283 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5284 Process.SYSTEM_UID);
5285 if (newCachePath != null) {
5286 setCachePath(newCachePath);
5287 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005288 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5289 }
5290 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005291 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005292 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005293 }
5294
5295 boolean doRename(int status, final String pkgName,
5296 String oldCodePath) {
5297 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005298 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005299 if (PackageHelper.isContainerMounted(cid)) {
5300 // Unmount the container
5301 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005302 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005303 return false;
5304 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005305 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005306 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005307 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5308 " which might be stale. Will try to clean up.");
5309 // Clean up the stale container and proceed to recreate.
5310 if (!PackageHelper.destroySdDir(newCacheId)) {
5311 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5312 return false;
5313 }
5314 // Successfully cleaned up stale container. Try to rename again.
5315 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5316 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5317 + " inspite of cleaning it up.");
5318 return false;
5319 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005320 }
5321 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005322 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005323 newCachePath = PackageHelper.mountSdDir(newCacheId,
5324 getEncryptKey(), Process.SYSTEM_UID);
5325 } else {
5326 newCachePath = PackageHelper.getSdDir(newCacheId);
5327 }
5328 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005329 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005330 return false;
5331 }
5332 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005333 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005334 " at new path: " + newCachePath);
5335 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005336 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005337 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005338 }
5339
Kenny Root85387d72010-08-26 10:13:11 -07005340 private void setCachePath(String newCachePath) {
5341 File cachePath = new File(newCachePath);
5342 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5343 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5344 }
5345
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005346 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005347 if (status != PackageManager.INSTALL_SUCCEEDED) {
5348 cleanUp();
5349 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005350 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005351 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005352 PackageHelper.mountSdDir(cid,
5353 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005354 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005355 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005356 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005357 }
5358
5359 private void cleanUp() {
5360 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005361 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005362 }
5363
5364 void cleanUpResourcesLI() {
5365 String sourceFile = getCodePath();
5366 // Remove dex file
5367 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005368 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005369 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005370 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 + " at location "
5372 + sourceFile.toString() + ", retcode=" + retCode);
5373 // we don't consider this to be a failure of the core package deletion
5374 }
5375 }
5376 cleanUp();
5377 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005378
5379 boolean matchContainer(String app) {
5380 if (cid.startsWith(app)) {
5381 return true;
5382 }
5383 return false;
5384 }
5385
5386 String getPackageName() {
5387 int idx = cid.lastIndexOf("-");
5388 if (idx == -1) {
5389 return cid;
5390 }
5391 return cid.substring(0, idx);
5392 }
5393
5394 boolean doPostDeleteLI(boolean delete) {
5395 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005396 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005397 if (mounted) {
5398 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005399 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005400 }
5401 if (ret && delete) {
5402 cleanUpResourcesLI();
5403 }
5404 return ret;
5405 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005406 };
5407
5408 // Utility method used to create code paths based on package name and available index.
5409 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5410 String idxStr = "";
5411 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005412 // Fall back to default value of idx=1 if prefix is not
5413 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005414 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005415 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005416 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005417 if (subStr.endsWith(suffix)) {
5418 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005419 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005420 // If oldCodePath already contains prefix find out the
5421 // ending index to either increment or decrement.
5422 int sidx = subStr.lastIndexOf(prefix);
5423 if (sidx != -1) {
5424 subStr = subStr.substring(sidx + prefix.length());
5425 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005426 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5427 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005428 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005429 try {
5430 idx = Integer.parseInt(subStr);
5431 if (idx <= 1) {
5432 idx++;
5433 } else {
5434 idx--;
5435 }
5436 } catch(NumberFormatException e) {
5437 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005438 }
5439 }
5440 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005441 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005442 return prefix + idxStr;
5443 }
5444
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005445 // Utility method used to ignore ADD/REMOVE events
5446 // by directory observer.
5447 private static boolean ignoreCodePath(String fullPathStr) {
5448 String apkName = getApkName(fullPathStr);
5449 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5450 if (idx != -1 && ((idx+1) < apkName.length())) {
5451 // Make sure the package ends with a numeral
5452 String version = apkName.substring(idx+1);
5453 try {
5454 Integer.parseInt(version);
5455 return true;
5456 } catch (NumberFormatException e) {}
5457 }
5458 return false;
5459 }
5460
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005461 // Utility method that returns the relative package path with respect
5462 // to the installation directory. Like say for /data/data/com.test-1.apk
5463 // string com.test-1 is returned.
5464 static String getApkName(String codePath) {
5465 if (codePath == null) {
5466 return null;
5467 }
5468 int sidx = codePath.lastIndexOf("/");
5469 int eidx = codePath.lastIndexOf(".");
5470 if (eidx == -1) {
5471 eidx = codePath.length();
5472 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005473 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005474 return null;
5475 }
5476 return codePath.substring(sidx+1, eidx);
5477 }
5478
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 class PackageInstalledInfo {
5480 String name;
5481 int uid;
5482 PackageParser.Package pkg;
5483 int returnCode;
5484 PackageRemovedInfo removedInfo;
5485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005487 /*
5488 * Install a non-existing package.
5489 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005490 private void installNewPackageLI(PackageParser.Package pkg,
5491 int parseFlags,
5492 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005493 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005494 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005495 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005496
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005497 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005498 res.name = pkgName;
5499 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005500 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5501 // A package with the same name is already installed, though
5502 // it has been renamed to an older name. The package we
5503 // are trying to install should be installed as an update to
5504 // the existing one, but that has not been requested, so bail.
5505 Slog.w(TAG, "Attempt to re-install " + pkgName
5506 + " without first uninstalling package running as "
5507 + mSettings.mRenamedPackages.get(pkgName));
5508 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5509 return;
5510 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005511 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005513 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005514 + " without first uninstalling.");
5515 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5516 return;
5517 }
5518 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005519 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005520 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5521 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005523 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5525 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5526 }
5527 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005528 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005529 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005530 res);
5531 // delete the partially installed application. the data directory will have to be
5532 // restored if it was already existing
5533 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5534 // remove package from internal structures. Note that we want deletePackageX to
5535 // delete the package data and cache directories that it created in
5536 // scanPackageLocked, unless those directories existed before we even tried to
5537 // install.
5538 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005539 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005541 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005542 }
5543 }
5544 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005545
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005546 private void replacePackageLI(PackageParser.Package pkg,
5547 int parseFlags,
5548 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005549 String installerPackageName, PackageInstalledInfo res) {
5550
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005551 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005552 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 // First find the old package info and check signatures
5554 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005555 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005556 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005557 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5559 return;
5560 }
5561 }
Kenny Root85387d72010-08-26 10:13:11 -07005562 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005563 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005564 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005565 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005566 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 }
5568 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005571 PackageParser.Package pkg,
5572 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005573 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005574 PackageParser.Package newPackage = null;
5575 String pkgName = deletedPackage.packageName;
5576 boolean deletedPkg = true;
5577 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005578
Jacek Surazski65e13172009-04-28 15:26:38 +02005579 String oldInstallerPackageName = null;
5580 synchronized (mPackages) {
5581 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005583
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005584 long origUpdateTime;
5585 if (pkg.mExtras != null) {
5586 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5587 } else {
5588 origUpdateTime = 0;
5589 }
5590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005592 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005593 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005594 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005595 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5596 deletedPkg = false;
5597 } else {
5598 // Successfully deleted the old package. Now proceed with re-installation
5599 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005600 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5601 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005603 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005604 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5605 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005606 }
5607 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005608 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005609 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610 res);
5611 updatedSettings = true;
5612 }
5613 }
5614
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005615 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 // remove package from internal structures. Note that we want deletePackageX to
5617 // delete the package data and cache directories that it created in
5618 // scanPackageLocked, unless those directories existed before we even tried to
5619 // install.
5620 if(updatedSettings) {
5621 deletePackageLI(
5622 pkgName, true,
5623 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005624 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 }
5626 // Since we failed to install the new package we need to restore the old
5627 // package that we deleted.
5628 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005629 File restoreFile = new File(deletedPackage.mPath);
5630 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005631 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005632 return;
5633 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005634 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005635 boolean oldOnSd = isExternal(deletedPackage);
5636 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5637 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5638 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005639 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5640 | SCAN_UPDATE_TIME;
5641 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5642 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005643 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5644 return;
5645 }
5646 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005647 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005648 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005649 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005650 mSettings.writeLP();
5651 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005652 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 }
5654 }
5655 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005656
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005658 PackageParser.Package pkg,
5659 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005660 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 PackageParser.Package newPackage = null;
5662 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005663 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 PackageParser.PARSE_IS_SYSTEM;
5665 String packageName = deletedPackage.packageName;
5666 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5667 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005668 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 return;
5670 }
5671 PackageParser.Package oldPkg;
5672 PackageSetting oldPkgSetting;
5673 synchronized (mPackages) {
5674 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005675 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005676 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5677 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005678 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005679 return;
5680 }
5681 }
5682 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5683 res.removedInfo.removedPackage = packageName;
5684 // Remove existing system package
5685 removePackageLI(oldPkg, true);
5686 synchronized (mPackages) {
5687 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5688 }
5689
5690 // Successfully disabled the old package. Now proceed with re-installation
5691 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5692 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005693 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005694 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005695 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5697 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5698 }
5699 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005700 if (newPackage.mExtras != null) {
5701 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5702 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5703 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5704 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005705 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 updatedSettings = true;
5707 }
5708
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005709 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 // Re installation failed. Restore old information
5711 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005712 if (newPackage != null) {
5713 removePackageLI(newPackage, true);
5714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005716 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 // Restore the old system information in Settings
5718 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005719 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005721 mSettings.setInstallerPackageName(packageName,
5722 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 }
5724 mSettings.writeLP();
5725 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005726 } else {
5727 // If this is an update to an existing update, setup
5728 // to remove the existing update.
5729 synchronized (mPackages) {
5730 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5731 if (ps != null && ps.codePathString != null &&
5732 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005733 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005734 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005735 }
5736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 }
5738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005739
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005740 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005741 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005742 int retCode;
5743 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5744 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5745 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005746 if (mNoDexOpt) {
5747 /*
5748 * If we're in an engineering build, programs are lazily run
5749 * through dexopt. If the .dex file doesn't exist yet, it
5750 * will be created when the program is run next.
5751 */
5752 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5753 } else {
5754 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5755 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5756 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005757 }
5758 }
5759 return PackageManager.INSTALL_SUCCEEDED;
5760 }
5761
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005762 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005763 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005764 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005765 synchronized (mPackages) {
5766 //write settings. the installStatus will be incomplete at this stage.
5767 //note that the new package setting would have already been
5768 //added to mPackages. It hasn't been persisted yet.
5769 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5770 mSettings.writeLP();
5771 }
5772
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005773 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005774 != PackageManager.INSTALL_SUCCEEDED) {
5775 // Discontinue if moving dex files failed.
5776 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005777 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005778 if((res.returnCode = setPermissionsLI(newPackage))
5779 != PackageManager.INSTALL_SUCCEEDED) {
5780 if (mInstaller != null) {
5781 mInstaller.rmdex(newPackage.mScanPath);
5782 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005783 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005784 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005785 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005788 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005789 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 res.name = pkgName;
5791 res.uid = newPackage.applicationInfo.uid;
5792 res.pkg = newPackage;
5793 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005794 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005795 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5796 //to update install status
5797 mSettings.writeLP();
5798 }
5799 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005800
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005801 private void installPackageLI(InstallArgs args,
5802 boolean newInstall, PackageInstalledInfo res) {
5803 int pFlags = args.flags;
5804 String installerPackageName = args.installerPackageName;
5805 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005806 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005807 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005808 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005809 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005810 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005811 // Result object to be returned
5812 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5813
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005814 // Retrieve PackageSettings and parse package
5815 int parseFlags = PackageParser.PARSE_CHATTY |
5816 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5817 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5818 parseFlags |= mDefParseFlags;
5819 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5820 pp.setSeparateProcesses(mSeparateProcesses);
5821 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5822 null, mMetrics, parseFlags);
5823 if (pkg == null) {
5824 res.returnCode = pp.getParseError();
5825 return;
5826 }
5827 String pkgName = res.name = pkg.packageName;
5828 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5829 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5830 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5831 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005832 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005833 }
5834 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5835 res.returnCode = pp.getParseError();
5836 return;
5837 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005838 // Get rid of all references to package scan path via parser.
5839 pp = null;
5840 String oldCodePath = null;
5841 boolean systemApp = false;
5842 synchronized (mPackages) {
5843 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005844 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5845 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005846 if (pkg.mOriginalPackages != null
5847 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005848 && mPackages.containsKey(oldName)) {
5849 // This package is derived from an original package,
5850 // and this device has been updating from that original
5851 // name. We must continue using the original name, so
5852 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005853 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005854 pkgName = pkg.packageName;
5855 replace = true;
5856 } else if (mPackages.containsKey(pkgName)) {
5857 // This package, under its official name, already exists
5858 // on the device; we should replace it.
5859 replace = true;
5860 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005861 }
5862 PackageSetting ps = mSettings.mPackages.get(pkgName);
5863 if (ps != null) {
5864 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5865 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5866 systemApp = (ps.pkg.applicationInfo.flags &
5867 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005868 }
5869 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005871
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005872 if (systemApp && onSd) {
5873 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005874 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005875 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5876 return;
5877 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005878
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005879 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5880 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5881 return;
5882 }
5883 // Set application objects path explicitly after the rename
5884 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005885 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005886 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005887 replacePackageLI(pkg, parseFlags, scanMode,
5888 installerPackageName, res);
5889 } else {
5890 installNewPackageLI(pkg, parseFlags, scanMode,
5891 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005892 }
5893 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005894
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005895 private int setPermissionsLI(PackageParser.Package newPackage) {
5896 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005897 int retCode = 0;
5898 // TODO Gross hack but fix later. Ideally move this to be a post installation
5899 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005900 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005901 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005902 try {
5903 extractPublicFiles(newPackage, destResourceFile);
5904 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005905 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 -08005906 " forward-locked app.");
5907 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5908 } finally {
5909 //TODO clean up the extracted public files
5910 }
5911 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005912 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005913 newPackage.applicationInfo.uid);
5914 } else {
5915 final int filePermissions =
5916 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005917 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005918 newPackage.applicationInfo.uid);
5919 }
5920 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005921 // The permissions on the resource file was set when it was copied for
5922 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005923 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005925 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005926 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005927 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005929 // TODO Define new internal error
5930 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 }
5932 return PackageManager.INSTALL_SUCCEEDED;
5933 }
5934
Kenny Root85387d72010-08-26 10:13:11 -07005935 private static boolean isForwardLocked(PackageParser.Package pkg) {
5936 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005937 }
5938
Kenny Root85387d72010-08-26 10:13:11 -07005939 private static boolean isExternal(PackageParser.Package pkg) {
5940 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5941 }
5942
5943 private static boolean isSystemApp(PackageParser.Package pkg) {
5944 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5945 }
5946
5947 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5948 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005949 }
5950
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 private void extractPublicFiles(PackageParser.Package newPackage,
5952 File publicZipFile) throws IOException {
5953 final ZipOutputStream publicZipOutStream =
5954 new ZipOutputStream(new FileOutputStream(publicZipFile));
5955 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5956
5957 // Copy manifest, resources.arsc and res directory to public zip
5958
5959 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5960 while (privateZipEntries.hasMoreElements()) {
5961 final ZipEntry zipEntry = privateZipEntries.nextElement();
5962 final String zipEntryName = zipEntry.getName();
5963 if ("AndroidManifest.xml".equals(zipEntryName)
5964 || "resources.arsc".equals(zipEntryName)
5965 || zipEntryName.startsWith("res/")) {
5966 try {
5967 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5968 } catch (IOException e) {
5969 try {
5970 publicZipOutStream.close();
5971 throw e;
5972 } finally {
5973 publicZipFile.delete();
5974 }
5975 }
5976 }
5977 }
5978
5979 publicZipOutStream.close();
5980 FileUtils.setPermissions(
5981 publicZipFile.getAbsolutePath(),
5982 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5983 -1, -1);
5984 }
5985
5986 private static void copyZipEntry(ZipEntry zipEntry,
5987 ZipFile inZipFile,
5988 ZipOutputStream outZipStream) throws IOException {
5989 byte[] buffer = new byte[4096];
5990 int num;
5991
5992 ZipEntry newEntry;
5993 if (zipEntry.getMethod() == ZipEntry.STORED) {
5994 // Preserve the STORED method of the input entry.
5995 newEntry = new ZipEntry(zipEntry);
5996 } else {
5997 // Create a new entry so that the compressed len is recomputed.
5998 newEntry = new ZipEntry(zipEntry.getName());
5999 }
6000 outZipStream.putNextEntry(newEntry);
6001
6002 InputStream data = inZipFile.getInputStream(zipEntry);
6003 while ((num = data.read(buffer)) > 0) {
6004 outZipStream.write(buffer, 0, num);
6005 }
6006 outZipStream.flush();
6007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006009 private void deleteTempPackageFiles() {
6010 FilenameFilter filter = new FilenameFilter() {
6011 public boolean accept(File dir, String name) {
6012 return name.startsWith("vmdl") && name.endsWith(".tmp");
6013 }
6014 };
6015 String tmpFilesList[] = mAppInstallDir.list(filter);
6016 if(tmpFilesList == null) {
6017 return;
6018 }
6019 for(int i = 0; i < tmpFilesList.length; i++) {
6020 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6021 tmpFile.delete();
6022 }
6023 }
6024
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006025 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 File tmpPackageFile;
6027 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006028 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006030 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006031 return null;
6032 }
6033 try {
6034 FileUtils.setPermissions(
6035 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6036 -1, -1);
6037 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006038 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006039 return null;
6040 }
6041 return tmpPackageFile;
6042 }
6043
6044 public void deletePackage(final String packageName,
6045 final IPackageDeleteObserver observer,
6046 final int flags) {
6047 mContext.enforceCallingOrSelfPermission(
6048 android.Manifest.permission.DELETE_PACKAGES, null);
6049 // Queue up an async operation since the package deletion may take a little while.
6050 mHandler.post(new Runnable() {
6051 public void run() {
6052 mHandler.removeCallbacks(this);
6053 final boolean succeded = deletePackageX(packageName, true, true, flags);
6054 if (observer != null) {
6055 try {
6056 observer.packageDeleted(succeded);
6057 } catch (RemoteException e) {
6058 Log.i(TAG, "Observer no longer exists.");
6059 } //end catch
6060 } //end if
6061 } //end run
6062 });
6063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006065 /**
6066 * This method is an internal method that could be get invoked either
6067 * to delete an installed package or to clean up a failed installation.
6068 * After deleting an installed package, a broadcast is sent to notify any
6069 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006070 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006071 * installation wouldn't have sent the initial broadcast either
6072 * The key steps in deleting a package are
6073 * deleting the package information in internal structures like mPackages,
6074 * deleting the packages base directories through installd
6075 * updating mSettings to reflect current status
6076 * persisting settings for later use
6077 * sending a broadcast if necessary
6078 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006079 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6080 boolean deleteCodeAndResources, int flags) {
6081 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006082 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006084 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6085 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6086 try {
6087 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006088 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006089 return false;
6090 }
6091 } catch (RemoteException e) {
6092 }
6093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006095 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006096 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006100 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006101 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006102
6103 // If the removed package was a system update, the old system packaged
6104 // was re-enabled; we need to broadcast this information
6105 if (systemUpdate) {
6106 Bundle extras = new Bundle(1);
6107 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6108 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6109
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006110 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6111 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006114 // Force a gc here.
6115 Runtime.getRuntime().gc();
6116 // Delete the resources here after sending the broadcast to let
6117 // other processes clean up before deleting resources.
6118 if (info.args != null) {
6119 synchronized (mInstallLock) {
6120 info.args.doPostDeleteLI(deleteCodeAndResources);
6121 }
6122 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006123 return res;
6124 }
6125
6126 static class PackageRemovedInfo {
6127 String removedPackage;
6128 int uid = -1;
6129 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006130 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006131 // Clean up resources deleted packages.
6132 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006133
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006134 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 Bundle extras = new Bundle(1);
6136 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6137 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6138 if (replacing) {
6139 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6140 }
6141 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006142 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006143 }
6144 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006145 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 }
6147 }
6148 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 /*
6151 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6152 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006153 * 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 -08006154 * delete a partially installed application.
6155 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006156 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006157 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006159 if (outInfo != null) {
6160 outInfo.removedPackage = packageName;
6161 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006162 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 // Retrieve object to delete permissions for shared user later on
6164 PackageSetting deletedPs;
6165 synchronized (mPackages) {
6166 deletedPs = mSettings.mPackages.get(packageName);
6167 }
6168 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006169 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006170 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006171 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006172 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006173 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006174 + packageName + ", retcode=" + retCode);
6175 // we don't consider this to be a failure of the core package deletion
6176 }
6177 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006178 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 PackageParser.Package pkg = mPackages.get(packageName);
6180 File dataDir = new File(pkg.applicationInfo.dataDir);
6181 dataDir.delete();
6182 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006183 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 }
6185 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006186 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006187 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6188 if (outInfo != null) {
6189 outInfo.removedUid = mSettings.removePackageLP(packageName);
6190 }
6191 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006192 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006193 if (deletedPs.sharedUser != null) {
6194 // remove permissions associated with package
6195 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6196 }
6197 }
6198 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006199 // remove from preferred activities.
6200 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6201 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6202 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6203 removed.add(pa);
6204 }
6205 }
6206 for (PreferredActivity pa : removed) {
6207 mSettings.mPreferredActivities.removeFilter(pa);
6208 }
6209 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006210 if (writeSettings) {
6211 // Save settings now
6212 mSettings.writeLP();
6213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 }
6215 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 /*
6218 * Tries to delete system package.
6219 */
6220 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006221 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 ApplicationInfo applicationInfo = p.applicationInfo;
6223 //applicable for non-partially installed applications only
6224 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006225 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006226 return false;
6227 }
6228 PackageSetting ps = null;
6229 // Confirm if the system package has been updated
6230 // An updated system app can be deleted. This will also have to restore
6231 // the system pkg from system partition
6232 synchronized (mPackages) {
6233 ps = mSettings.getDisabledSystemPkg(p.packageName);
6234 }
6235 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006236 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 return false;
6238 } else {
6239 Log.i(TAG, "Deleting system pkg from data partition");
6240 }
6241 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006242 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006243 final boolean deleteCodeAndResources;
6244 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006245 // Delete code and resources for downgrades
6246 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006247 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006248 } else {
6249 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006250 deleteCodeAndResources = false;
6251 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006252 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006253 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6254 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 if (!ret) {
6256 return false;
6257 }
6258 synchronized (mPackages) {
6259 // Reinstate the old system package
6260 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006261 // Remove any native libraries from the upgraded package.
6262 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 }
6264 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006265 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006267 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006270 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 return false;
6272 }
6273 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006274 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006275 if (writeSettings) {
6276 mSettings.writeLP();
6277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 }
6279 return true;
6280 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006283 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6284 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 ApplicationInfo applicationInfo = p.applicationInfo;
6286 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006287 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 return false;
6289 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006290 if (outInfo != null) {
6291 outInfo.uid = applicationInfo.uid;
6292 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006293
6294 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006295 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006296
6297 // Delete application code and resources
6298 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006299 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006300 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6301 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6302 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6303 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006304 }
6305 return true;
6306 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006308 /*
6309 * This method handles package deletion in general
6310 */
6311 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006312 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6313 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006314 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006315 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006316 return false;
6317 }
6318 PackageParser.Package p;
6319 boolean dataOnly = false;
6320 synchronized (mPackages) {
6321 p = mPackages.get(packageName);
6322 if (p == null) {
6323 //this retrieves partially installed apps
6324 dataOnly = true;
6325 PackageSetting ps = mSettings.mPackages.get(packageName);
6326 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006327 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 return false;
6329 }
6330 p = ps.pkg;
6331 }
6332 }
6333 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006334 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006335 return false;
6336 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 if (dataOnly) {
6339 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006340 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 return true;
6342 }
6343 // At this point the package should have ApplicationInfo associated with it
6344 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006345 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006346 return false;
6347 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006348 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006349 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006350 Log.i(TAG, "Removing system package:"+p.packageName);
6351 // When an updated system application is deleted we delete the existing resources as well and
6352 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006353 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006354 } else {
6355 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006356 // Kill application pre-emptively especially for apps on sd.
6357 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006358 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6359 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006361 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006362 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 public void clearApplicationUserData(final String packageName,
6365 final IPackageDataObserver observer) {
6366 mContext.enforceCallingOrSelfPermission(
6367 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6368 // Queue up an async operation since the package deletion may take a little while.
6369 mHandler.post(new Runnable() {
6370 public void run() {
6371 mHandler.removeCallbacks(this);
6372 final boolean succeeded;
6373 synchronized (mInstallLock) {
6374 succeeded = clearApplicationUserDataLI(packageName);
6375 }
6376 if (succeeded) {
6377 // invoke DeviceStorageMonitor's update method to clear any notifications
6378 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6379 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6380 if (dsm != null) {
6381 dsm.updateMemory();
6382 }
6383 }
6384 if(observer != null) {
6385 try {
6386 observer.onRemoveCompleted(packageName, succeeded);
6387 } catch (RemoteException e) {
6388 Log.i(TAG, "Observer no longer exists.");
6389 }
6390 } //end if observer
6391 } //end run
6392 });
6393 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006395 private boolean clearApplicationUserDataLI(String packageName) {
6396 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006397 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 return false;
6399 }
6400 PackageParser.Package p;
6401 boolean dataOnly = false;
6402 synchronized (mPackages) {
6403 p = mPackages.get(packageName);
6404 if(p == null) {
6405 dataOnly = true;
6406 PackageSetting ps = mSettings.mPackages.get(packageName);
6407 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006408 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 return false;
6410 }
6411 p = ps.pkg;
6412 }
6413 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006414 boolean useEncryptedFSDir = false;
6415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006416 if(!dataOnly) {
6417 //need to check this only for fully installed applications
6418 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006419 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 return false;
6421 }
6422 final ApplicationInfo applicationInfo = p.applicationInfo;
6423 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006424 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 return false;
6426 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006427 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 }
6429 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006430 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006432 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006433 + packageName);
6434 return false;
6435 }
6436 }
6437 return true;
6438 }
6439
6440 public void deleteApplicationCacheFiles(final String packageName,
6441 final IPackageDataObserver observer) {
6442 mContext.enforceCallingOrSelfPermission(
6443 android.Manifest.permission.DELETE_CACHE_FILES, null);
6444 // Queue up an async operation since the package deletion may take a little while.
6445 mHandler.post(new Runnable() {
6446 public void run() {
6447 mHandler.removeCallbacks(this);
6448 final boolean succeded;
6449 synchronized (mInstallLock) {
6450 succeded = deleteApplicationCacheFilesLI(packageName);
6451 }
6452 if(observer != null) {
6453 try {
6454 observer.onRemoveCompleted(packageName, succeded);
6455 } catch (RemoteException e) {
6456 Log.i(TAG, "Observer no longer exists.");
6457 }
6458 } //end if observer
6459 } //end run
6460 });
6461 }
6462
6463 private boolean deleteApplicationCacheFilesLI(String packageName) {
6464 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006465 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006466 return false;
6467 }
6468 PackageParser.Package p;
6469 synchronized (mPackages) {
6470 p = mPackages.get(packageName);
6471 }
6472 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006473 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006474 return false;
6475 }
6476 final ApplicationInfo applicationInfo = p.applicationInfo;
6477 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006478 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 return false;
6480 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006481 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006483 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006485 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006486 + packageName);
6487 return false;
6488 }
6489 }
6490 return true;
6491 }
6492
6493 public void getPackageSizeInfo(final String packageName,
6494 final IPackageStatsObserver observer) {
6495 mContext.enforceCallingOrSelfPermission(
6496 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6497 // Queue up an async operation since the package deletion may take a little while.
6498 mHandler.post(new Runnable() {
6499 public void run() {
6500 mHandler.removeCallbacks(this);
6501 PackageStats lStats = new PackageStats(packageName);
6502 final boolean succeded;
6503 synchronized (mInstallLock) {
6504 succeded = getPackageSizeInfoLI(packageName, lStats);
6505 }
6506 if(observer != null) {
6507 try {
6508 observer.onGetStatsCompleted(lStats, succeded);
6509 } catch (RemoteException e) {
6510 Log.i(TAG, "Observer no longer exists.");
6511 }
6512 } //end if observer
6513 } //end run
6514 });
6515 }
6516
6517 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6518 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006519 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 return false;
6521 }
6522 PackageParser.Package p;
6523 boolean dataOnly = false;
6524 synchronized (mPackages) {
6525 p = mPackages.get(packageName);
6526 if(p == null) {
6527 dataOnly = true;
6528 PackageSetting ps = mSettings.mPackages.get(packageName);
6529 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006530 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 return false;
6532 }
6533 p = ps.pkg;
6534 }
6535 }
6536 String publicSrcDir = null;
6537 if(!dataOnly) {
6538 final ApplicationInfo applicationInfo = p.applicationInfo;
6539 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006540 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006541 return false;
6542 }
6543 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6544 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006545 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006546 if (mInstaller != null) {
6547 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006548 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 if (res < 0) {
6550 return false;
6551 } else {
6552 return true;
6553 }
6554 }
6555 return true;
6556 }
6557
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006559 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006560 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 }
6562
6563 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006564 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006565 }
6566
6567 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006568 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006569 }
6570
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006571 int getUidTargetSdkVersionLockedLP(int uid) {
6572 Object obj = mSettings.getUserIdLP(uid);
6573 if (obj instanceof SharedUserSetting) {
6574 SharedUserSetting sus = (SharedUserSetting)obj;
6575 final int N = sus.packages.size();
6576 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6577 Iterator<PackageSetting> it = sus.packages.iterator();
6578 int i=0;
6579 while (it.hasNext()) {
6580 PackageSetting ps = it.next();
6581 if (ps.pkg != null) {
6582 int v = ps.pkg.applicationInfo.targetSdkVersion;
6583 if (v < vers) vers = v;
6584 }
6585 }
6586 return vers;
6587 } else if (obj instanceof PackageSetting) {
6588 PackageSetting ps = (PackageSetting)obj;
6589 if (ps.pkg != null) {
6590 return ps.pkg.applicationInfo.targetSdkVersion;
6591 }
6592 }
6593 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6594 }
6595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006596 public void addPreferredActivity(IntentFilter filter, int match,
6597 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006599 if (mContext.checkCallingOrSelfPermission(
6600 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6601 != PackageManager.PERMISSION_GRANTED) {
6602 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6603 < Build.VERSION_CODES.FROYO) {
6604 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6605 + Binder.getCallingUid());
6606 return;
6607 }
6608 mContext.enforceCallingOrSelfPermission(
6609 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6610 }
6611
6612 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6614 mSettings.mPreferredActivities.addFilter(
6615 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006616 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006617 }
6618 }
6619
Satish Sampath8dbe6122009-06-02 23:35:54 +01006620 public void replacePreferredActivity(IntentFilter filter, int match,
6621 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006622 if (filter.countActions() != 1) {
6623 throw new IllegalArgumentException(
6624 "replacePreferredActivity expects filter to have only 1 action.");
6625 }
6626 if (filter.countCategories() != 1) {
6627 throw new IllegalArgumentException(
6628 "replacePreferredActivity expects filter to have only 1 category.");
6629 }
6630 if (filter.countDataAuthorities() != 0
6631 || filter.countDataPaths() != 0
6632 || filter.countDataSchemes() != 0
6633 || filter.countDataTypes() != 0) {
6634 throw new IllegalArgumentException(
6635 "replacePreferredActivity expects filter to have no data authorities, " +
6636 "paths, schemes or types.");
6637 }
6638 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006639 if (mContext.checkCallingOrSelfPermission(
6640 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6641 != PackageManager.PERMISSION_GRANTED) {
6642 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6643 < Build.VERSION_CODES.FROYO) {
6644 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6645 + Binder.getCallingUid());
6646 return;
6647 }
6648 mContext.enforceCallingOrSelfPermission(
6649 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6650 }
6651
Satish Sampath8dbe6122009-06-02 23:35:54 +01006652 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6653 String action = filter.getAction(0);
6654 String category = filter.getCategory(0);
6655 while (it.hasNext()) {
6656 PreferredActivity pa = it.next();
6657 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6658 it.remove();
6659 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6660 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6661 }
6662 }
6663 addPreferredActivity(filter, match, set, activity);
6664 }
6665 }
6666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006668 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006669 int uid = Binder.getCallingUid();
6670 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006671 if (pkg == null || pkg.applicationInfo.uid != uid) {
6672 if (mContext.checkCallingOrSelfPermission(
6673 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6674 != PackageManager.PERMISSION_GRANTED) {
6675 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6676 < Build.VERSION_CODES.FROYO) {
6677 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6678 + Binder.getCallingUid());
6679 return;
6680 }
6681 mContext.enforceCallingOrSelfPermission(
6682 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6683 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006684 }
6685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006686 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006687 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006688 }
6689 }
6690 }
6691
6692 boolean clearPackagePreferredActivitiesLP(String packageName) {
6693 boolean changed = false;
6694 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6695 while (it.hasNext()) {
6696 PreferredActivity pa = it.next();
6697 if (pa.mActivity.getPackageName().equals(packageName)) {
6698 it.remove();
6699 changed = true;
6700 }
6701 }
6702 return changed;
6703 }
6704
6705 public int getPreferredActivities(List<IntentFilter> outFilters,
6706 List<ComponentName> outActivities, String packageName) {
6707
6708 int num = 0;
6709 synchronized (mPackages) {
6710 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6711 while (it.hasNext()) {
6712 PreferredActivity pa = it.next();
6713 if (packageName == null
6714 || pa.mActivity.getPackageName().equals(packageName)) {
6715 if (outFilters != null) {
6716 outFilters.add(new IntentFilter(pa));
6717 }
6718 if (outActivities != null) {
6719 outActivities.add(pa.mActivity);
6720 }
6721 }
6722 }
6723 }
6724
6725 return num;
6726 }
6727
6728 public void setApplicationEnabledSetting(String appPackageName,
6729 int newState, int flags) {
6730 setEnabledSetting(appPackageName, null, newState, flags);
6731 }
6732
6733 public void setComponentEnabledSetting(ComponentName componentName,
6734 int newState, int flags) {
6735 setEnabledSetting(componentName.getPackageName(),
6736 componentName.getClassName(), newState, flags);
6737 }
6738
6739 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006740 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6742 || newState == COMPONENT_ENABLED_STATE_ENABLED
6743 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6744 throw new IllegalArgumentException("Invalid new component state: "
6745 + newState);
6746 }
6747 PackageSetting pkgSetting;
6748 final int uid = Binder.getCallingUid();
6749 final int permission = mContext.checkCallingPermission(
6750 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6751 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006752 boolean sendNow = false;
6753 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006754 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006755 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006756 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006757 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006758 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006759 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006760 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006761 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006762 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006763 }
6764 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006765 "Unknown component: " + packageName
6766 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 }
6768 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6769 throw new SecurityException(
6770 "Permission Denial: attempt to change component state from pid="
6771 + Binder.getCallingPid()
6772 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6773 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006774 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006776 if (pkgSetting.enabled == newState) {
6777 // Nothing to do
6778 return;
6779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006780 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006781 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006782 } else {
6783 // We're dealing with a component level state change
6784 switch (newState) {
6785 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006786 if (!pkgSetting.enableComponentLP(className)) {
6787 return;
6788 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006789 break;
6790 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006791 if (!pkgSetting.disableComponentLP(className)) {
6792 return;
6793 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006794 break;
6795 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006796 if (!pkgSetting.restoreComponentLP(className)) {
6797 return;
6798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006799 break;
6800 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006801 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006802 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006803 }
6804 }
6805 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006806 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006807 components = mPendingBroadcasts.get(packageName);
6808 boolean newPackage = components == null;
6809 if (newPackage) {
6810 components = new ArrayList<String>();
6811 }
6812 if (!components.contains(componentName)) {
6813 components.add(componentName);
6814 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006815 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6816 sendNow = true;
6817 // Purge entry from pending broadcast list if another one exists already
6818 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006819 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006820 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006821 if (newPackage) {
6822 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006823 }
6824 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6825 // Schedule a message
6826 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6827 }
6828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006829 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006831 long callingId = Binder.clearCallingIdentity();
6832 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006833 if (sendNow) {
6834 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006835 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 } finally {
6838 Binder.restoreCallingIdentity(callingId);
6839 }
6840 }
6841
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006842 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006843 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6844 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6845 + " components=" + componentNames);
6846 Bundle extras = new Bundle(4);
6847 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6848 String nameList[] = new String[componentNames.size()];
6849 componentNames.toArray(nameList);
6850 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006851 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6852 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006853 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006854 }
6855
Jacek Surazski65e13172009-04-28 15:26:38 +02006856 public String getInstallerPackageName(String packageName) {
6857 synchronized (mPackages) {
6858 PackageSetting pkg = mSettings.mPackages.get(packageName);
6859 if (pkg == null) {
6860 throw new IllegalArgumentException("Unknown package: " + packageName);
6861 }
6862 return pkg.installerPackageName;
6863 }
6864 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006866 public int getApplicationEnabledSetting(String appPackageName) {
6867 synchronized (mPackages) {
6868 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6869 if (pkg == null) {
6870 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6871 }
6872 return pkg.enabled;
6873 }
6874 }
6875
6876 public int getComponentEnabledSetting(ComponentName componentName) {
6877 synchronized (mPackages) {
6878 final String packageNameStr = componentName.getPackageName();
6879 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6880 if (pkg == null) {
6881 throw new IllegalArgumentException("Unknown component: " + componentName);
6882 }
6883 final String classNameStr = componentName.getClassName();
6884 return pkg.currentEnabledStateLP(classNameStr);
6885 }
6886 }
6887
6888 public void enterSafeMode() {
6889 if (!mSystemReady) {
6890 mSafeMode = true;
6891 }
6892 }
6893
6894 public void systemReady() {
6895 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006896
6897 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006898 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006899 mContext.getContentResolver(),
6900 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006901 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006902 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006903 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006905 }
6906
6907 public boolean isSafeMode() {
6908 return mSafeMode;
6909 }
6910
6911 public boolean hasSystemUidErrors() {
6912 return mHasSystemUidErrors;
6913 }
6914
6915 static String arrayToString(int[] array) {
6916 StringBuffer buf = new StringBuffer(128);
6917 buf.append('[');
6918 if (array != null) {
6919 for (int i=0; i<array.length; i++) {
6920 if (i > 0) buf.append(", ");
6921 buf.append(array[i]);
6922 }
6923 }
6924 buf.append(']');
6925 return buf.toString();
6926 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006928 @Override
6929 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6930 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6931 != PackageManager.PERMISSION_GRANTED) {
6932 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6933 + Binder.getCallingPid()
6934 + ", uid=" + Binder.getCallingUid()
6935 + " without permission "
6936 + android.Manifest.permission.DUMP);
6937 return;
6938 }
6939
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006940 boolean dumpStar = true;
6941 boolean dumpLibs = false;
6942 boolean dumpFeatures = false;
6943 boolean dumpResolvers = false;
6944 boolean dumpPermissions = false;
6945 boolean dumpPackages = false;
6946 boolean dumpSharedUsers = false;
6947 boolean dumpMessages = false;
6948 boolean dumpProviders = false;
6949
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006950 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006951 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006952
6953 int opti = 0;
6954 while (opti < args.length) {
6955 String opt = args[opti];
6956 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6957 break;
6958 }
6959 opti++;
6960 if ("-a".equals(opt)) {
6961 // Right now we only know how to print all.
6962 } else if ("-h".equals(opt)) {
6963 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006964 pw.println(" [-h] [-f] [cmd] ...");
6965 pw.println(" -f: print details of intent filters");
6966 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006967 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006968 pw.println(" l[ibraries]: list known shared libraries");
6969 pw.println(" f[ibraries]: list device features");
6970 pw.println(" r[esolvers]: dump intent resolvers");
6971 pw.println(" perm[issions]: dump permissions");
6972 pw.println(" prov[iders]: dump content providers");
6973 pw.println(" p[ackages]: dump installed packages");
6974 pw.println(" s[hared-users]: dump shared user IDs");
6975 pw.println(" m[essages]: print collected runtime messages");
6976 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006977 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006978 } else if ("-f".equals(opt)) {
6979 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006980 } else {
6981 pw.println("Unknown argument: " + opt + "; use -h for help");
6982 }
6983 }
6984
6985 // Is the caller requesting to dump a particular piece of data?
6986 if (opti < args.length) {
6987 String cmd = args[opti];
6988 opti++;
6989 // Is this a package name?
6990 if ("android".equals(cmd) || cmd.contains(".")) {
6991 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006992 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
6993 dumpStar = false;
6994 dumpLibs = true;
6995 } else if ("f".equals(cmd) || "features".equals(cmd)) {
6996 dumpStar = false;
6997 dumpFeatures = true;
6998 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
6999 dumpStar = false;
7000 dumpResolvers = true;
7001 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
7002 dumpStar = false;
7003 dumpPermissions = true;
7004 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
7005 dumpStar = false;
7006 dumpPackages = true;
7007 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
7008 dumpStar = false;
7009 dumpSharedUsers = true;
7010 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
7011 dumpStar = false;
7012 dumpProviders = true;
7013 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
7014 dumpStar = false;
7015 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007016 }
7017 }
7018
7019 boolean printedTitle = false;
7020
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007022 if ((dumpStar || dumpLibs) && packageName == null) {
7023 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007024 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007025 pw.println("Libraries:");
7026 Iterator<String> it = mSharedLibraries.keySet().iterator();
7027 while (it.hasNext()) {
7028 String name = it.next();
7029 pw.print(" ");
7030 pw.print(name);
7031 pw.print(" -> ");
7032 pw.println(mSharedLibraries.get(name));
7033 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007034 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007035
7036 if ((dumpStar || dumpFeatures) && packageName == null) {
7037 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007038 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007039 pw.println("Features:");
7040 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7041 while (it.hasNext()) {
7042 String name = it.next();
7043 pw.print(" ");
7044 pw.println(name);
7045 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007046 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007047
7048 if (dumpStar || dumpResolvers) {
7049 if (mActivities.dump(pw, printedTitle
7050 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7051 " ", packageName, showFilters)) {
7052 printedTitle = true;
7053 }
7054 if (mReceivers.dump(pw, printedTitle
7055 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7056 " ", packageName, showFilters)) {
7057 printedTitle = true;
7058 }
7059 if (mServices.dump(pw, printedTitle
7060 ? "\nService Resolver Table:" : "Service Resolver Table:",
7061 " ", packageName, showFilters)) {
7062 printedTitle = true;
7063 }
7064 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7065 ? "\nPreferred Activities:" : "Preferred Activities:",
7066 " ", packageName, showFilters)) {
7067 printedTitle = true;
7068 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007069 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007070
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007071 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007072 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007073 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007074 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7075 continue;
7076 }
7077 if (!printedSomething) {
7078 if (printedTitle) pw.println(" ");
7079 pw.println("Permissions:");
7080 printedSomething = true;
7081 printedTitle = true;
7082 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007083 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7084 pw.print(Integer.toHexString(System.identityHashCode(p)));
7085 pw.println("):");
7086 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7087 pw.print(" uid="); pw.print(p.uid);
7088 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007089 pw.print(" type="); pw.print(p.type);
7090 pw.print(" prot="); pw.println(p.protectionLevel);
7091 if (p.packageSetting != null) {
7092 pw.print(" packageSetting="); pw.println(p.packageSetting);
7093 }
7094 if (p.perm != null) {
7095 pw.print(" perm="); pw.println(p.perm);
7096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007097 }
7098 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007099
7100 if (dumpStar || dumpProviders) {
7101 printedSomething = false;
7102 for (PackageParser.Provider p : mProviders.values()) {
7103 if (packageName != null && !packageName.equals(p.info.packageName)) {
7104 continue;
7105 }
7106 if (!printedSomething) {
7107 if (printedTitle) pw.println(" ");
7108 pw.println("Registered ContentProviders:");
7109 printedSomething = true;
7110 printedTitle = true;
7111 }
7112 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7113 pw.println(p.toString());
7114 }
7115 }
7116
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007117 printedSomething = false;
7118 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007119 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007120 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7121 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007123 if (packageName != null && !packageName.equals(ps.realName)
7124 && !packageName.equals(ps.name)) {
7125 continue;
7126 }
7127 if (!printedSomething) {
7128 if (printedTitle) pw.println(" ");
7129 pw.println("Packages:");
7130 printedSomething = true;
7131 printedTitle = true;
7132 }
7133 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007134 pw.print(" Package [");
7135 pw.print(ps.realName != null ? ps.realName : ps.name);
7136 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007137 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7138 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007139 if (ps.realName != null) {
7140 pw.print(" compat name="); pw.println(ps.name);
7141 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007142 pw.print(" userId="); pw.print(ps.userId);
7143 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7144 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7145 pw.print(" pkg="); pw.println(ps.pkg);
7146 pw.print(" codePath="); pw.println(ps.codePathString);
7147 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007148 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007149 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007150 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007151 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007152 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007153 if (ps.pkg.mOperationPending) {
7154 pw.println(" mOperationPending=true");
7155 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007156 pw.print(" supportsScreens=[");
7157 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007158 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007159 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7160 if (!first) pw.print(", ");
7161 first = false;
7162 pw.print("small");
7163 }
7164 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007165 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007166 if (!first) pw.print(", ");
7167 first = false;
7168 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007169 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007170 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007171 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007172 if (!first) pw.print(", ");
7173 first = false;
7174 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007175 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007176 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007177 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007178 if (!first) pw.print(", ");
7179 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007180 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007181 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007182 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007183 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007184 if (!first) pw.print(", ");
7185 first = false;
7186 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007187 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007188 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007189 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7190 if (!first) pw.print(", ");
7191 first = false;
7192 pw.print("anyDensity");
7193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007194 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007195 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007196 pw.print(" timeStamp=");
7197 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7198 pw.print(" firstInstallTime=");
7199 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7200 pw.print(" lastUpdateTime=");
7201 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007202 pw.print(" signatures="); pw.println(ps.signatures);
7203 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007204 pw.print(" haveGids="); pw.println(ps.haveGids);
7205 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007206 pw.print(" installStatus="); pw.print(ps.installStatus);
7207 pw.print(" enabled="); pw.println(ps.enabled);
Andy Stadler8e2be262010-10-12 15:00:43 -07007208 pw.print(" versionCode="); pw.print(ps.versionCode);
7209 pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007210 if (ps.disabledComponents.size() > 0) {
7211 pw.println(" disabledComponents:");
7212 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007213 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007214 }
7215 }
7216 if (ps.enabledComponents.size() > 0) {
7217 pw.println(" enabledComponents:");
7218 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007219 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007220 }
7221 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007222 if (ps.grantedPermissions.size() > 0) {
7223 pw.println(" grantedPermissions:");
7224 for (String s : ps.grantedPermissions) {
7225 pw.print(" "); pw.println(s);
7226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 }
7229 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007230 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007231 if (dumpStar || dumpPackages) {
7232 if (mSettings.mRenamedPackages.size() > 0) {
7233 for (HashMap.Entry<String, String> e
7234 : mSettings.mRenamedPackages.entrySet()) {
7235 if (packageName != null && !packageName.equals(e.getKey())
7236 && !packageName.equals(e.getValue())) {
7237 continue;
7238 }
7239 if (!printedSomething) {
7240 if (printedTitle) pw.println(" ");
7241 pw.println("Renamed packages:");
7242 printedSomething = true;
7243 printedTitle = true;
7244 }
7245 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7246 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007247 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007248 }
7249 printedSomething = false;
7250 if (mSettings.mDisabledSysPackages.size() > 0) {
7251 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7252 if (packageName != null && !packageName.equals(ps.realName)
7253 && !packageName.equals(ps.name)) {
7254 continue;
7255 }
7256 if (!printedSomething) {
7257 if (printedTitle) pw.println(" ");
7258 pw.println("Hidden system packages:");
7259 printedSomething = true;
7260 printedTitle = true;
7261 }
7262 pw.print(" Package [");
7263 pw.print(ps.realName != null ? ps.realName : ps.name);
7264 pw.print("] (");
7265 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7266 pw.println("):");
7267 if (ps.realName != null) {
7268 pw.print(" compat name="); pw.println(ps.name);
7269 }
7270 pw.print(" userId="); pw.println(ps.userId);
7271 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7272 pw.print(" codePath="); pw.println(ps.codePathString);
7273 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007274 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007275 }
7276 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007277 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007278 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007279 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007280 if (packageName != null && su != packageSharedUser) {
7281 continue;
7282 }
7283 if (!printedSomething) {
7284 if (printedTitle) pw.println(" ");
7285 pw.println("Shared users:");
7286 printedSomething = true;
7287 printedTitle = true;
7288 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007289 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7290 pw.print(Integer.toHexString(System.identityHashCode(su)));
7291 pw.println("):");
7292 pw.print(" userId="); pw.print(su.userId);
7293 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007294 pw.println(" grantedPermissions:");
7295 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007296 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007297 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007298 }
7299 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007300
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007301 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007302 if (printedTitle) pw.println(" ");
7303 printedTitle = true;
7304 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007305 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007306
7307 pw.println(" ");
7308 pw.println("Package warning messages:");
7309 File fname = getSettingsProblemFile();
7310 FileInputStream in;
7311 try {
7312 in = new FileInputStream(fname);
7313 int avail = in.available();
7314 byte[] data = new byte[avail];
7315 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007316 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007317 } catch (FileNotFoundException e) {
7318 } catch (IOException e) {
7319 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007321 }
7322 }
7323
7324 static final class BasePermission {
7325 final static int TYPE_NORMAL = 0;
7326 final static int TYPE_BUILTIN = 1;
7327 final static int TYPE_DYNAMIC = 2;
7328
7329 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007330 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007331 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007332 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007333 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007334 PackageParser.Permission perm;
7335 PermissionInfo pendingInfo;
7336 int uid;
7337 int[] gids;
7338
7339 BasePermission(String _name, String _sourcePackage, int _type) {
7340 name = _name;
7341 sourcePackage = _sourcePackage;
7342 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007343 // Default to most conservative protection level.
7344 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7345 }
7346
7347 public String toString() {
7348 return "BasePermission{"
7349 + Integer.toHexString(System.identityHashCode(this))
7350 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007351 }
7352 }
7353
7354 static class PackageSignatures {
7355 private Signature[] mSignatures;
7356
7357 PackageSignatures(Signature[] sigs) {
7358 assignSignatures(sigs);
7359 }
7360
7361 PackageSignatures() {
7362 }
7363
7364 void writeXml(XmlSerializer serializer, String tagName,
7365 ArrayList<Signature> pastSignatures) throws IOException {
7366 if (mSignatures == null) {
7367 return;
7368 }
7369 serializer.startTag(null, tagName);
7370 serializer.attribute(null, "count",
7371 Integer.toString(mSignatures.length));
7372 for (int i=0; i<mSignatures.length; i++) {
7373 serializer.startTag(null, "cert");
7374 final Signature sig = mSignatures[i];
7375 final int sigHash = sig.hashCode();
7376 final int numPast = pastSignatures.size();
7377 int j;
7378 for (j=0; j<numPast; j++) {
7379 Signature pastSig = pastSignatures.get(j);
7380 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7381 serializer.attribute(null, "index", Integer.toString(j));
7382 break;
7383 }
7384 }
7385 if (j >= numPast) {
7386 pastSignatures.add(sig);
7387 serializer.attribute(null, "index", Integer.toString(numPast));
7388 serializer.attribute(null, "key", sig.toCharsString());
7389 }
7390 serializer.endTag(null, "cert");
7391 }
7392 serializer.endTag(null, tagName);
7393 }
7394
7395 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7396 throws IOException, XmlPullParserException {
7397 String countStr = parser.getAttributeValue(null, "count");
7398 if (countStr == null) {
7399 reportSettingsProblem(Log.WARN,
7400 "Error in package manager settings: <signatures> has"
7401 + " no count at " + parser.getPositionDescription());
7402 XmlUtils.skipCurrentTag(parser);
7403 }
7404 final int count = Integer.parseInt(countStr);
7405 mSignatures = new Signature[count];
7406 int pos = 0;
7407
7408 int outerDepth = parser.getDepth();
7409 int type;
7410 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7411 && (type != XmlPullParser.END_TAG
7412 || parser.getDepth() > outerDepth)) {
7413 if (type == XmlPullParser.END_TAG
7414 || type == XmlPullParser.TEXT) {
7415 continue;
7416 }
7417
7418 String tagName = parser.getName();
7419 if (tagName.equals("cert")) {
7420 if (pos < count) {
7421 String index = parser.getAttributeValue(null, "index");
7422 if (index != null) {
7423 try {
7424 int idx = Integer.parseInt(index);
7425 String key = parser.getAttributeValue(null, "key");
7426 if (key == null) {
7427 if (idx >= 0 && idx < pastSignatures.size()) {
7428 Signature sig = pastSignatures.get(idx);
7429 if (sig != null) {
7430 mSignatures[pos] = pastSignatures.get(idx);
7431 pos++;
7432 } else {
7433 reportSettingsProblem(Log.WARN,
7434 "Error in package manager settings: <cert> "
7435 + "index " + index + " is not defined at "
7436 + parser.getPositionDescription());
7437 }
7438 } else {
7439 reportSettingsProblem(Log.WARN,
7440 "Error in package manager settings: <cert> "
7441 + "index " + index + " is out of bounds at "
7442 + parser.getPositionDescription());
7443 }
7444 } else {
7445 while (pastSignatures.size() <= idx) {
7446 pastSignatures.add(null);
7447 }
7448 Signature sig = new Signature(key);
7449 pastSignatures.set(idx, sig);
7450 mSignatures[pos] = sig;
7451 pos++;
7452 }
7453 } catch (NumberFormatException e) {
7454 reportSettingsProblem(Log.WARN,
7455 "Error in package manager settings: <cert> "
7456 + "index " + index + " is not a number at "
7457 + parser.getPositionDescription());
7458 }
7459 } else {
7460 reportSettingsProblem(Log.WARN,
7461 "Error in package manager settings: <cert> has"
7462 + " no index at " + parser.getPositionDescription());
7463 }
7464 } else {
7465 reportSettingsProblem(Log.WARN,
7466 "Error in package manager settings: too "
7467 + "many <cert> tags, expected " + count
7468 + " at " + parser.getPositionDescription());
7469 }
7470 } else {
7471 reportSettingsProblem(Log.WARN,
7472 "Unknown element under <cert>: "
7473 + parser.getName());
7474 }
7475 XmlUtils.skipCurrentTag(parser);
7476 }
7477
7478 if (pos < count) {
7479 // Should never happen -- there is an error in the written
7480 // settings -- but if it does we don't want to generate
7481 // a bad array.
7482 Signature[] newSigs = new Signature[pos];
7483 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7484 mSignatures = newSigs;
7485 }
7486 }
7487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007488 private void assignSignatures(Signature[] sigs) {
7489 if (sigs == null) {
7490 mSignatures = null;
7491 return;
7492 }
7493 mSignatures = new Signature[sigs.length];
7494 for (int i=0; i<sigs.length; i++) {
7495 mSignatures[i] = sigs[i];
7496 }
7497 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007499 @Override
7500 public String toString() {
7501 StringBuffer buf = new StringBuffer(128);
7502 buf.append("PackageSignatures{");
7503 buf.append(Integer.toHexString(System.identityHashCode(this)));
7504 buf.append(" [");
7505 if (mSignatures != null) {
7506 for (int i=0; i<mSignatures.length; i++) {
7507 if (i > 0) buf.append(", ");
7508 buf.append(Integer.toHexString(
7509 System.identityHashCode(mSignatures[i])));
7510 }
7511 }
7512 buf.append("]}");
7513 return buf.toString();
7514 }
7515 }
7516
7517 static class PreferredActivity extends IntentFilter {
7518 final int mMatch;
7519 final String[] mSetPackages;
7520 final String[] mSetClasses;
7521 final String[] mSetComponents;
7522 final ComponentName mActivity;
7523 final String mShortActivity;
7524 String mParseError;
7525
7526 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7527 ComponentName activity) {
7528 super(filter);
7529 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7530 mActivity = activity;
7531 mShortActivity = activity.flattenToShortString();
7532 mParseError = null;
7533 if (set != null) {
7534 final int N = set.length;
7535 String[] myPackages = new String[N];
7536 String[] myClasses = new String[N];
7537 String[] myComponents = new String[N];
7538 for (int i=0; i<N; i++) {
7539 ComponentName cn = set[i];
7540 if (cn == null) {
7541 mSetPackages = null;
7542 mSetClasses = null;
7543 mSetComponents = null;
7544 return;
7545 }
7546 myPackages[i] = cn.getPackageName().intern();
7547 myClasses[i] = cn.getClassName().intern();
7548 myComponents[i] = cn.flattenToShortString().intern();
7549 }
7550 mSetPackages = myPackages;
7551 mSetClasses = myClasses;
7552 mSetComponents = myComponents;
7553 } else {
7554 mSetPackages = null;
7555 mSetClasses = null;
7556 mSetComponents = null;
7557 }
7558 }
7559
7560 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7561 IOException {
7562 mShortActivity = parser.getAttributeValue(null, "name");
7563 mActivity = ComponentName.unflattenFromString(mShortActivity);
7564 if (mActivity == null) {
7565 mParseError = "Bad activity name " + mShortActivity;
7566 }
7567 String matchStr = parser.getAttributeValue(null, "match");
7568 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7569 String setCountStr = parser.getAttributeValue(null, "set");
7570 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7571
7572 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7573 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7574 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7575
7576 int setPos = 0;
7577
7578 int outerDepth = parser.getDepth();
7579 int type;
7580 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7581 && (type != XmlPullParser.END_TAG
7582 || parser.getDepth() > outerDepth)) {
7583 if (type == XmlPullParser.END_TAG
7584 || type == XmlPullParser.TEXT) {
7585 continue;
7586 }
7587
7588 String tagName = parser.getName();
7589 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7590 // + parser.getDepth() + " tag=" + tagName);
7591 if (tagName.equals("set")) {
7592 String name = parser.getAttributeValue(null, "name");
7593 if (name == null) {
7594 if (mParseError == null) {
7595 mParseError = "No name in set tag in preferred activity "
7596 + mShortActivity;
7597 }
7598 } else if (setPos >= setCount) {
7599 if (mParseError == null) {
7600 mParseError = "Too many set tags in preferred activity "
7601 + mShortActivity;
7602 }
7603 } else {
7604 ComponentName cn = ComponentName.unflattenFromString(name);
7605 if (cn == null) {
7606 if (mParseError == null) {
7607 mParseError = "Bad set name " + name + " in preferred activity "
7608 + mShortActivity;
7609 }
7610 } else {
7611 myPackages[setPos] = cn.getPackageName();
7612 myClasses[setPos] = cn.getClassName();
7613 myComponents[setPos] = name;
7614 setPos++;
7615 }
7616 }
7617 XmlUtils.skipCurrentTag(parser);
7618 } else if (tagName.equals("filter")) {
7619 //Log.i(TAG, "Starting to parse filter...");
7620 readFromXml(parser);
7621 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7622 // + parser.getDepth() + " tag=" + parser.getName());
7623 } else {
7624 reportSettingsProblem(Log.WARN,
7625 "Unknown element under <preferred-activities>: "
7626 + parser.getName());
7627 XmlUtils.skipCurrentTag(parser);
7628 }
7629 }
7630
7631 if (setPos != setCount) {
7632 if (mParseError == null) {
7633 mParseError = "Not enough set tags (expected " + setCount
7634 + " but found " + setPos + ") in " + mShortActivity;
7635 }
7636 }
7637
7638 mSetPackages = myPackages;
7639 mSetClasses = myClasses;
7640 mSetComponents = myComponents;
7641 }
7642
7643 public void writeToXml(XmlSerializer serializer) throws IOException {
7644 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7645 serializer.attribute(null, "name", mShortActivity);
7646 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7647 serializer.attribute(null, "set", Integer.toString(NS));
7648 for (int s=0; s<NS; s++) {
7649 serializer.startTag(null, "set");
7650 serializer.attribute(null, "name", mSetComponents[s]);
7651 serializer.endTag(null, "set");
7652 }
7653 serializer.startTag(null, "filter");
7654 super.writeToXml(serializer);
7655 serializer.endTag(null, "filter");
7656 }
7657
7658 boolean sameSet(List<ResolveInfo> query, int priority) {
7659 if (mSetPackages == null) return false;
7660 final int NQ = query.size();
7661 final int NS = mSetPackages.length;
7662 int numMatch = 0;
7663 for (int i=0; i<NQ; i++) {
7664 ResolveInfo ri = query.get(i);
7665 if (ri.priority != priority) continue;
7666 ActivityInfo ai = ri.activityInfo;
7667 boolean good = false;
7668 for (int j=0; j<NS; j++) {
7669 if (mSetPackages[j].equals(ai.packageName)
7670 && mSetClasses[j].equals(ai.name)) {
7671 numMatch++;
7672 good = true;
7673 break;
7674 }
7675 }
7676 if (!good) return false;
7677 }
7678 return numMatch == NS;
7679 }
7680 }
7681
7682 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007683 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007685 HashSet<String> grantedPermissions = new HashSet<String>();
7686 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007689 setFlags(pkgFlags);
7690 }
7691
7692 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007693 this.pkgFlags = pkgFlags & (
7694 ApplicationInfo.FLAG_SYSTEM |
7695 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007696 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007697 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007698 }
7699 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007701 /**
7702 * Settings base class for pending and resolved classes.
7703 */
7704 static class PackageSettingBase extends GrantedPermissions {
7705 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007706 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007707 File codePath;
7708 String codePathString;
7709 File resourcePath;
7710 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007711 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007712 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007713 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007714 long firstInstallTime;
7715 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007716 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007717
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007718 boolean uidError;
7719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007720 PackageSignatures signatures = new PackageSignatures();
7721
7722 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007723 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007725 /* Explicitly disabled components */
7726 HashSet<String> disabledComponents = new HashSet<String>(0);
7727 /* Explicitly enabled components */
7728 HashSet<String> enabledComponents = new HashSet<String>(0);
7729 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7730 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007731
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007732 PackageSettingBase origPackage;
7733
Jacek Surazski65e13172009-04-28 15:26:38 +02007734 /* package name of the app that installed this package */
7735 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007737 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007738 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 super(pkgFlags);
7740 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007741 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007742 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007743 }
7744
Kenny Root806cc132010-09-12 08:34:19 -07007745 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7746 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007747 this.codePath = codePath;
7748 this.codePathString = codePath.toString();
7749 this.resourcePath = resourcePath;
7750 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007751 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007752 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 }
Kenny Root85387d72010-08-26 10:13:11 -07007754
Jacek Surazski65e13172009-04-28 15:26:38 +02007755 public void setInstallerPackageName(String packageName) {
7756 installerPackageName = packageName;
7757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007758
Jacek Surazski65e13172009-04-28 15:26:38 +02007759 String getInstallerPackageName() {
7760 return installerPackageName;
7761 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007763 public void setInstallStatus(int newStatus) {
7764 installStatus = newStatus;
7765 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007767 public int getInstallStatus() {
7768 return installStatus;
7769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007771 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 }
7774
7775 public void copyFrom(PackageSettingBase base) {
7776 grantedPermissions = base.grantedPermissions;
7777 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007779 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007780 firstInstallTime = base.firstInstallTime;
7781 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007782 signatures = base.signatures;
7783 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007784 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 disabledComponents = base.disabledComponents;
7786 enabledComponents = base.enabledComponents;
7787 enabled = base.enabled;
7788 installStatus = base.installStatus;
7789 }
7790
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007791 boolean enableComponentLP(String componentClassName) {
7792 boolean changed = disabledComponents.remove(componentClassName);
7793 changed |= enabledComponents.add(componentClassName);
7794 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 }
7796
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007797 boolean disableComponentLP(String componentClassName) {
7798 boolean changed = enabledComponents.remove(componentClassName);
7799 changed |= disabledComponents.add(componentClassName);
7800 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 }
7802
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007803 boolean restoreComponentLP(String componentClassName) {
7804 boolean changed = enabledComponents.remove(componentClassName);
7805 changed |= disabledComponents.remove(componentClassName);
7806 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007807 }
7808
7809 int currentEnabledStateLP(String componentName) {
7810 if (enabledComponents.contains(componentName)) {
7811 return COMPONENT_ENABLED_STATE_ENABLED;
7812 } else if (disabledComponents.contains(componentName)) {
7813 return COMPONENT_ENABLED_STATE_DISABLED;
7814 } else {
7815 return COMPONENT_ENABLED_STATE_DEFAULT;
7816 }
7817 }
7818 }
7819
7820 /**
7821 * Settings data for a particular package we know about.
7822 */
7823 static final class PackageSetting extends PackageSettingBase {
7824 int userId;
7825 PackageParser.Package pkg;
7826 SharedUserSetting sharedUser;
7827
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007828 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007829 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7830 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7831 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007834 @Override
7835 public String toString() {
7836 return "PackageSetting{"
7837 + Integer.toHexString(System.identityHashCode(this))
7838 + " " + name + "/" + userId + "}";
7839 }
7840 }
7841
7842 /**
7843 * Settings data for a particular shared user ID we know about.
7844 */
7845 static final class SharedUserSetting extends GrantedPermissions {
7846 final String name;
7847 int userId;
7848 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7849 final PackageSignatures signatures = new PackageSignatures();
7850
7851 SharedUserSetting(String _name, int _pkgFlags) {
7852 super(_pkgFlags);
7853 name = _name;
7854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 @Override
7857 public String toString() {
7858 return "SharedUserSetting{"
7859 + Integer.toHexString(System.identityHashCode(this))
7860 + " " + name + "/" + userId + "}";
7861 }
7862 }
7863
7864 /**
7865 * Holds information about dynamic settings.
7866 */
7867 private static final class Settings {
7868 private final File mSettingsFilename;
7869 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007870 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 private final HashMap<String, PackageSetting> mPackages =
7872 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007873 // List of replaced system applications
7874 final HashMap<String, PackageSetting> mDisabledSysPackages =
7875 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007876
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007877 // These are the last platform API version we were using for
7878 // the apps installed on internal and external storage. It is
7879 // used to grant newer permissions one time during a system upgrade.
7880 int mInternalSdkPlatform;
7881 int mExternalSdkPlatform;
7882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007883 // The user's preferred activities associated with particular intent
7884 // filters.
7885 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7886 new IntentResolver<PreferredActivity, PreferredActivity>() {
7887 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007888 protected String packageForFilter(PreferredActivity filter) {
7889 return filter.mActivity.getPackageName();
7890 }
7891 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007892 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007893 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007894 out.print(prefix); out.print(
7895 Integer.toHexString(System.identityHashCode(filter)));
7896 out.print(' ');
7897 out.print(filter.mActivity.flattenToShortString());
7898 out.print(" match=0x");
7899 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007900 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007901 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007902 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007903 out.print(prefix); out.print(" ");
7904 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007905 }
7906 }
7907 }
7908 };
7909 private final HashMap<String, SharedUserSetting> mSharedUsers =
7910 new HashMap<String, SharedUserSetting>();
7911 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7912 private final SparseArray<Object> mOtherUserIds =
7913 new SparseArray<Object>();
7914
7915 // For reading/writing settings file.
7916 private final ArrayList<Signature> mPastSignatures =
7917 new ArrayList<Signature>();
7918
7919 // Mapping from permission names to info about them.
7920 final HashMap<String, BasePermission> mPermissions =
7921 new HashMap<String, BasePermission>();
7922
7923 // Mapping from permission tree names to info about them.
7924 final HashMap<String, BasePermission> mPermissionTrees =
7925 new HashMap<String, BasePermission>();
7926
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007927 // Packages that have been uninstalled and still need their external
7928 // storage data deleted.
7929 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7930
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007931 // Packages that have been renamed since they were first installed.
7932 // Keys are the new names of the packages, values are the original
7933 // names. The packages appear everwhere else under their original
7934 // names.
7935 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 private final StringBuilder mReadMessages = new StringBuilder();
7938
7939 private static final class PendingPackage extends PackageSettingBase {
7940 final int sharedId;
7941
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007942 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007943 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7944 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7945 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007946 this.sharedId = sharedId;
7947 }
7948 }
7949 private final ArrayList<PendingPackage> mPendingPackages
7950 = new ArrayList<PendingPackage>();
7951
7952 Settings() {
7953 File dataDir = Environment.getDataDirectory();
7954 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007955 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7956 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007957 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007958 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007959 FileUtils.setPermissions(systemDir.toString(),
7960 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7961 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7962 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007963 FileUtils.setPermissions(systemSecureDir.toString(),
7964 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7965 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7966 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007967 mSettingsFilename = new File(systemDir, "packages.xml");
7968 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007969 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007970 }
7971
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007972 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007973 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007974 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007975 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007976 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007977 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007978 return p;
7979 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007980
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007981 PackageSetting peekPackageLP(String name) {
7982 return mPackages.get(name);
7983 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007984 PackageSetting p = mPackages.get(name);
7985 if (p != null && p.codePath.getPath().equals(codePath)) {
7986 return p;
7987 }
7988 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007989 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007990 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007991
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007992 void setInstallStatus(String pkgName, int status) {
7993 PackageSetting p = mPackages.get(pkgName);
7994 if(p != null) {
7995 if(p.getInstallStatus() != status) {
7996 p.setInstallStatus(status);
7997 }
7998 }
7999 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008000
Jacek Surazski65e13172009-04-28 15:26:38 +02008001 void setInstallerPackageName(String pkgName,
8002 String installerPkgName) {
8003 PackageSetting p = mPackages.get(pkgName);
8004 if(p != null) {
8005 p.setInstallerPackageName(installerPkgName);
8006 }
8007 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008008
Jacek Surazski65e13172009-04-28 15:26:38 +02008009 String getInstallerPackageName(String pkgName) {
8010 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008011 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008012 }
8013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008014 int getInstallStatus(String pkgName) {
8015 PackageSetting p = mPackages.get(pkgName);
8016 if(p != null) {
8017 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008019 return -1;
8020 }
8021
8022 SharedUserSetting getSharedUserLP(String name,
8023 int pkgFlags, boolean create) {
8024 SharedUserSetting s = mSharedUsers.get(name);
8025 if (s == null) {
8026 if (!create) {
8027 return null;
8028 }
8029 s = new SharedUserSetting(name, pkgFlags);
8030 if (MULTIPLE_APPLICATION_UIDS) {
8031 s.userId = newUserIdLP(s);
8032 } else {
8033 s.userId = FIRST_APPLICATION_UID;
8034 }
8035 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8036 // < 0 means we couldn't assign a userid; fall out and return
8037 // s, which is currently null
8038 if (s.userId >= 0) {
8039 mSharedUsers.put(name, s);
8040 }
8041 }
8042
8043 return s;
8044 }
8045
8046 int disableSystemPackageLP(String name) {
8047 PackageSetting p = mPackages.get(name);
8048 if(p == null) {
8049 Log.w(TAG, "Package:"+name+" is not an installed package");
8050 return -1;
8051 }
8052 PackageSetting dp = mDisabledSysPackages.get(name);
8053 // always make sure the system package code and resource paths dont change
8054 if(dp == null) {
8055 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8056 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8057 }
8058 mDisabledSysPackages.put(name, p);
8059 }
8060 return removePackageLP(name);
8061 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 PackageSetting enableSystemPackageLP(String name) {
8064 PackageSetting p = mDisabledSysPackages.get(name);
8065 if(p == null) {
8066 Log.w(TAG, "Package:"+name+" is not disabled");
8067 return null;
8068 }
8069 // Reset flag in ApplicationInfo object
8070 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8071 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8072 }
Kenny Root806cc132010-09-12 08:34:19 -07008073 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8074 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008075 mDisabledSysPackages.remove(name);
8076 return ret;
8077 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008078
Kenny Root806cc132010-09-12 08:34:19 -07008079 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8080 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008081 PackageSetting p = mPackages.get(name);
8082 if (p != null) {
8083 if (p.userId == uid) {
8084 return p;
8085 }
8086 reportSettingsProblem(Log.ERROR,
8087 "Adding duplicate package, keeping first: " + name);
8088 return null;
8089 }
Kenny Root806cc132010-09-12 08:34:19 -07008090 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8091 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008092 p.userId = uid;
8093 if (addUserIdLP(uid, p, name)) {
8094 mPackages.put(name, p);
8095 return p;
8096 }
8097 return null;
8098 }
8099
8100 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8101 SharedUserSetting s = mSharedUsers.get(name);
8102 if (s != null) {
8103 if (s.userId == uid) {
8104 return s;
8105 }
8106 reportSettingsProblem(Log.ERROR,
8107 "Adding duplicate shared user, keeping first: " + name);
8108 return null;
8109 }
8110 s = new SharedUserSetting(name, pkgFlags);
8111 s.userId = uid;
8112 if (addUserIdLP(uid, s, name)) {
8113 mSharedUsers.put(name, s);
8114 return s;
8115 }
8116 return null;
8117 }
8118
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008119 // Transfer ownership of permissions from one package to another.
8120 private void transferPermissions(String origPkg, String newPkg) {
8121 // Transfer ownership of permissions to the new package.
8122 for (int i=0; i<2; i++) {
8123 HashMap<String, BasePermission> permissions =
8124 i == 0 ? mPermissionTrees : mPermissions;
8125 for (BasePermission bp : permissions.values()) {
8126 if (origPkg.equals(bp.sourcePackage)) {
8127 if (DEBUG_UPGRADE) Log.v(TAG,
8128 "Moving permission " + bp.name
8129 + " from pkg " + bp.sourcePackage
8130 + " to " + newPkg);
8131 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008132 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008133 bp.perm = null;
8134 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008135 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008136 }
8137 bp.uid = 0;
8138 bp.gids = null;
8139 }
8140 }
8141 }
8142 }
8143
8144 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008145 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008146 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008147 PackageSetting p = mPackages.get(name);
8148 if (p != null) {
8149 if (!p.codePath.equals(codePath)) {
8150 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008151 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008152 // This is an updated system app with versions in both system
8153 // and data partition. Just let the most recent version
8154 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008155 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008156 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008157 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008158 // Just a change in the code path is not an issue, but
8159 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008160 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008161 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008162 /*
8163 * Since we've changed paths, we need to prefer the new
8164 * native library path over the one stored in the
8165 * package settings since we might have moved from
8166 * internal to external storage or vice versa.
8167 */
8168 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008169 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008170 }
8171 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008172 reportSettingsProblem(Log.WARN,
8173 "Package " + name + " shared user changed from "
8174 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8175 + " to "
8176 + (sharedUser != null ? sharedUser.name : "<nothing>")
8177 + "; replacing with new");
8178 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008179 } else {
8180 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8181 // If what we are scanning is a system package, then
8182 // make it so, regardless of whether it was previously
8183 // installed only in the data partition.
8184 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 }
8187 }
8188 if (p == null) {
8189 // Create a new PackageSettings entry. this can end up here because
8190 // of code path mismatch or user id mismatch of an updated system partition
8191 if (!create) {
8192 return null;
8193 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008194 if (origPackage != null) {
8195 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008196 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8197 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008198 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8199 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008200 // Note that we will retain the new package's signature so
8201 // that we can keep its data.
8202 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008203 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008204 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008205 p.sharedUser = origPackage.sharedUser;
8206 p.userId = origPackage.userId;
8207 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008208 mRenamedPackages.put(name, origPackage.name);
8209 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008210 // Update new package state.
8211 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008212 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008213 p = new PackageSetting(name, realName, codePath, resourcePath,
8214 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008215 p.setTimeStamp(codePath.lastModified());
8216 p.sharedUser = sharedUser;
8217 if (sharedUser != null) {
8218 p.userId = sharedUser.userId;
8219 } else if (MULTIPLE_APPLICATION_UIDS) {
8220 // Clone the setting here for disabled system packages
8221 PackageSetting dis = mDisabledSysPackages.get(name);
8222 if (dis != null) {
8223 // For disabled packages a new setting is created
8224 // from the existing user id. This still has to be
8225 // added to list of user id's
8226 // Copy signatures from previous setting
8227 if (dis.signatures.mSignatures != null) {
8228 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8229 }
8230 p.userId = dis.userId;
8231 // Clone permissions
8232 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008233 // Clone component info
8234 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8235 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8236 // Add new setting to list of user ids
8237 addUserIdLP(p.userId, p, name);
8238 } else {
8239 // Assign new user id
8240 p.userId = newUserIdLP(p);
8241 }
8242 } else {
8243 p.userId = FIRST_APPLICATION_UID;
8244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008245 }
8246 if (p.userId < 0) {
8247 reportSettingsProblem(Log.WARN,
8248 "Package " + name + " could not be assigned a valid uid");
8249 return null;
8250 }
8251 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008252 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008253 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008254 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 }
8256 }
8257 return p;
8258 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008259
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008260 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008261 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008262 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008263 final String codePath = pkg.applicationInfo.sourceDir;
8264 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008265 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008266 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008267 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008268 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008269 p.codePath = new File(codePath);
8270 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008271 }
8272 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008273 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008274 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008275 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008276 p.resourcePath = new File(resourcePath);
8277 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008278 }
Kenny Root85387d72010-08-26 10:13:11 -07008279 // Update the native library path if needed
8280 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8281 if (nativeLibraryPath != null
8282 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8283 p.nativeLibraryPathString = nativeLibraryPath;
8284 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008285 // Update version code if needed
8286 if (pkg.mVersionCode != p.versionCode) {
8287 p.versionCode = pkg.mVersionCode;
8288 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008289 // Update signatures if needed.
8290 if (p.signatures.mSignatures == null) {
8291 p.signatures.assignSignatures(pkg.mSignatures);
8292 }
8293 // If this app defines a shared user id initialize
8294 // the shared user signatures as well.
8295 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8296 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8297 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008298 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8299 }
8300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008301 // Utility method that adds a PackageSetting to mPackages and
8302 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008303 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 SharedUserSetting sharedUser) {
8305 mPackages.put(name, p);
8306 if (sharedUser != null) {
8307 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8308 reportSettingsProblem(Log.ERROR,
8309 "Package " + p.name + " was user "
8310 + p.sharedUser + " but is now " + sharedUser
8311 + "; I am not changing its files so it will probably fail!");
8312 p.sharedUser.packages.remove(p);
8313 } else if (p.userId != sharedUser.userId) {
8314 reportSettingsProblem(Log.ERROR,
8315 "Package " + p.name + " was user id " + p.userId
8316 + " but is now user " + sharedUser
8317 + " with id " + sharedUser.userId
8318 + "; I am not changing its files so it will probably fail!");
8319 }
8320
8321 sharedUser.packages.add(p);
8322 p.sharedUser = sharedUser;
8323 p.userId = sharedUser.userId;
8324 }
8325 }
8326
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008327 /*
8328 * Update the shared user setting when a package using
8329 * specifying the shared user id is removed. The gids
8330 * associated with each permission of the deleted package
8331 * are removed from the shared user's gid list only if its
8332 * not in use by other permissions of packages in the
8333 * shared user setting.
8334 */
8335 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008337 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 return;
8339 }
8340 // No sharedUserId
8341 if (deletedPs.sharedUser == null) {
8342 return;
8343 }
8344 SharedUserSetting sus = deletedPs.sharedUser;
8345 // Update permissions
8346 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8347 boolean used = false;
8348 if (!sus.grantedPermissions.contains (eachPerm)) {
8349 continue;
8350 }
8351 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008352 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008353 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008354 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008355 used = true;
8356 break;
8357 }
8358 }
8359 if (!used) {
8360 // can safely delete this permission from list
8361 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008362 }
8363 }
8364 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008365 int newGids[] = globalGids;
8366 for (String eachPerm : sus.grantedPermissions) {
8367 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008368 if (bp != null) {
8369 newGids = appendInts(newGids, bp.gids);
8370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 }
8372 sus.gids = newGids;
8373 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008375 private int removePackageLP(String name) {
8376 PackageSetting p = mPackages.get(name);
8377 if (p != null) {
8378 mPackages.remove(name);
8379 if (p.sharedUser != null) {
8380 p.sharedUser.packages.remove(p);
8381 if (p.sharedUser.packages.size() == 0) {
8382 mSharedUsers.remove(p.sharedUser.name);
8383 removeUserIdLP(p.sharedUser.userId);
8384 return p.sharedUser.userId;
8385 }
8386 } else {
8387 removeUserIdLP(p.userId);
8388 return p.userId;
8389 }
8390 }
8391 return -1;
8392 }
8393
8394 private boolean addUserIdLP(int uid, Object obj, Object name) {
8395 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8396 return false;
8397 }
8398
8399 if (uid >= FIRST_APPLICATION_UID) {
8400 int N = mUserIds.size();
8401 final int index = uid - FIRST_APPLICATION_UID;
8402 while (index >= N) {
8403 mUserIds.add(null);
8404 N++;
8405 }
8406 if (mUserIds.get(index) != null) {
8407 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008408 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 + " name=" + name);
8410 return false;
8411 }
8412 mUserIds.set(index, obj);
8413 } else {
8414 if (mOtherUserIds.get(uid) != null) {
8415 reportSettingsProblem(Log.ERROR,
8416 "Adding duplicate shared id: " + uid
8417 + " name=" + name);
8418 return false;
8419 }
8420 mOtherUserIds.put(uid, obj);
8421 }
8422 return true;
8423 }
8424
8425 public Object getUserIdLP(int uid) {
8426 if (uid >= FIRST_APPLICATION_UID) {
8427 int N = mUserIds.size();
8428 final int index = uid - FIRST_APPLICATION_UID;
8429 return index < N ? mUserIds.get(index) : null;
8430 } else {
8431 return mOtherUserIds.get(uid);
8432 }
8433 }
8434
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008435 private Set<String> findPackagesWithFlag(int flag) {
8436 Set<String> ret = new HashSet<String>();
8437 for (PackageSetting ps : mPackages.values()) {
8438 // Has to match atleast all the flag bits set on flag
8439 if ((ps.pkgFlags & flag) == flag) {
8440 ret.add(ps.name);
8441 }
8442 }
8443 return ret;
8444 }
8445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008446 private void removeUserIdLP(int uid) {
8447 if (uid >= FIRST_APPLICATION_UID) {
8448 int N = mUserIds.size();
8449 final int index = uid - FIRST_APPLICATION_UID;
8450 if (index < N) mUserIds.set(index, null);
8451 } else {
8452 mOtherUserIds.remove(uid);
8453 }
8454 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456 void writeLP() {
8457 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8458
8459 // Keep the old settings around until we know the new ones have
8460 // been successfully written.
8461 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008462 // Presence of backup settings file indicates that we failed
8463 // to persist settings earlier. So preserve the older
8464 // backup for future reference since the current settings
8465 // might have been corrupted.
8466 if (!mBackupSettingsFilename.exists()) {
8467 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008468 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008469 return;
8470 }
8471 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008472 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008473 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 }
8476
8477 mPastSignatures.clear();
8478
8479 try {
Kenny Root9f306d72010-09-26 11:19:47 -07008480 BufferedOutputStream str = new BufferedOutputStream(new FileOutputStream(
8481 mSettingsFilename));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008482
8483 //XmlSerializer serializer = XmlUtils.serializerInstance();
8484 XmlSerializer serializer = new FastXmlSerializer();
8485 serializer.setOutput(str, "utf-8");
8486 serializer.startDocument(null, true);
8487 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8488
8489 serializer.startTag(null, "packages");
8490
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008491 serializer.startTag(null, "last-platform-version");
8492 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8493 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8494 serializer.endTag(null, "last-platform-version");
8495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008496 serializer.startTag(null, "permission-trees");
8497 for (BasePermission bp : mPermissionTrees.values()) {
8498 writePermission(serializer, bp);
8499 }
8500 serializer.endTag(null, "permission-trees");
8501
8502 serializer.startTag(null, "permissions");
8503 for (BasePermission bp : mPermissions.values()) {
8504 writePermission(serializer, bp);
8505 }
8506 serializer.endTag(null, "permissions");
8507
8508 for (PackageSetting pkg : mPackages.values()) {
8509 writePackage(serializer, pkg);
8510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008512 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8513 writeDisabledSysPackage(serializer, pkg);
8514 }
8515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008516 serializer.startTag(null, "preferred-activities");
8517 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8518 serializer.startTag(null, "item");
8519 pa.writeToXml(serializer);
8520 serializer.endTag(null, "item");
8521 }
8522 serializer.endTag(null, "preferred-activities");
8523
8524 for (SharedUserSetting usr : mSharedUsers.values()) {
8525 serializer.startTag(null, "shared-user");
8526 serializer.attribute(null, "name", usr.name);
8527 serializer.attribute(null, "userId",
8528 Integer.toString(usr.userId));
8529 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8530 serializer.startTag(null, "perms");
8531 for (String name : usr.grantedPermissions) {
8532 serializer.startTag(null, "item");
8533 serializer.attribute(null, "name", name);
8534 serializer.endTag(null, "item");
8535 }
8536 serializer.endTag(null, "perms");
8537 serializer.endTag(null, "shared-user");
8538 }
8539
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008540 if (mPackagesToBeCleaned.size() > 0) {
8541 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8542 serializer.startTag(null, "cleaning-package");
8543 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8544 serializer.endTag(null, "cleaning-package");
8545 }
8546 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008547
8548 if (mRenamedPackages.size() > 0) {
8549 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8550 serializer.startTag(null, "renamed-package");
8551 serializer.attribute(null, "new", e.getKey());
8552 serializer.attribute(null, "old", e.getValue());
8553 serializer.endTag(null, "renamed-package");
8554 }
8555 }
8556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008557 serializer.endTag(null, "packages");
8558
8559 serializer.endDocument();
8560
8561 str.flush();
8562 str.close();
8563
8564 // New settings successfully written, old ones are no longer
8565 // needed.
8566 mBackupSettingsFilename.delete();
8567 FileUtils.setPermissions(mSettingsFilename.toString(),
8568 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8569 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8570 |FileUtils.S_IROTH,
8571 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008572
8573 // Write package list file now, use a JournaledFile.
8574 //
8575 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8576 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8577
Kenny Root9f306d72010-09-26 11:19:47 -07008578 str = new BufferedOutputStream(new FileOutputStream(journal.chooseForWrite()));
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008579 try {
8580 StringBuilder sb = new StringBuilder();
8581 for (PackageSetting pkg : mPackages.values()) {
8582 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008583 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008584 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8585
8586 // Avoid any application that has a space in its path
8587 // or that is handled by the system.
8588 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8589 continue;
8590
8591 // we store on each line the following information for now:
8592 //
8593 // pkgName - package name
8594 // userId - application-specific user id
8595 // debugFlag - 0 or 1 if the package is debuggable.
8596 // dataPath - path to package's data path
8597 //
8598 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8599 //
8600 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8601 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8602 // system/core/run-as/run-as.c
8603 //
8604 sb.setLength(0);
8605 sb.append(ai.packageName);
8606 sb.append(" ");
8607 sb.append((int)ai.uid);
8608 sb.append(isDebug ? " 1 " : " 0 ");
8609 sb.append(dataPath);
8610 sb.append("\n");
8611 str.write(sb.toString().getBytes());
8612 }
8613 str.flush();
8614 str.close();
8615 journal.commit();
8616 }
8617 catch (Exception e) {
8618 journal.rollback();
8619 }
8620
8621 FileUtils.setPermissions(mPackageListFilename.toString(),
8622 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8623 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8624 |FileUtils.S_IROTH,
8625 -1, -1);
8626
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008627 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628
8629 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008630 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 -08008631 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008632 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 -08008633 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008634 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008635 if (mSettingsFilename.exists()) {
8636 if (!mSettingsFilename.delete()) {
8637 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8638 }
8639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008640 //Debug.stopMethodTracing();
8641 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008642
8643 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008644 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008645 serializer.startTag(null, "updated-package");
8646 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008647 if (pkg.realName != null) {
8648 serializer.attribute(null, "realName", pkg.realName);
8649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008651 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8652 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8653 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008654 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008655 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8656 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8657 }
Kenny Root85387d72010-08-26 10:13:11 -07008658 if (pkg.nativeLibraryPathString != null) {
8659 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 if (pkg.sharedUser == null) {
8662 serializer.attribute(null, "userId",
8663 Integer.toString(pkg.userId));
8664 } else {
8665 serializer.attribute(null, "sharedUserId",
8666 Integer.toString(pkg.userId));
8667 }
8668 serializer.startTag(null, "perms");
8669 if (pkg.sharedUser == null) {
8670 // If this is a shared user, the permissions will
8671 // be written there. We still need to write an
8672 // empty permissions list so permissionsFixed will
8673 // be set.
8674 for (final String name : pkg.grantedPermissions) {
8675 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008676 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008677 // We only need to write signature or system permissions but this wont
8678 // match the semantics of grantedPermissions. So write all permissions.
8679 serializer.startTag(null, "item");
8680 serializer.attribute(null, "name", name);
8681 serializer.endTag(null, "item");
8682 }
8683 }
8684 }
8685 serializer.endTag(null, "perms");
8686 serializer.endTag(null, "updated-package");
8687 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008688
8689 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008690 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 serializer.startTag(null, "package");
8692 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008693 if (pkg.realName != null) {
8694 serializer.attribute(null, "realName", pkg.realName);
8695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 serializer.attribute(null, "codePath", pkg.codePathString);
8697 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8698 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8699 }
Kenny Root85387d72010-08-26 10:13:11 -07008700 if (pkg.nativeLibraryPathString != null) {
8701 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8702 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008703 serializer.attribute(null, "flags",
8704 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008705 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8706 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8707 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008708 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 if (pkg.sharedUser == null) {
8710 serializer.attribute(null, "userId",
8711 Integer.toString(pkg.userId));
8712 } else {
8713 serializer.attribute(null, "sharedUserId",
8714 Integer.toString(pkg.userId));
8715 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008716 if (pkg.uidError) {
8717 serializer.attribute(null, "uidError", "true");
8718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008719 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8720 serializer.attribute(null, "enabled",
8721 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8722 ? "true" : "false");
8723 }
8724 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8725 serializer.attribute(null, "installStatus", "false");
8726 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008727 if (pkg.installerPackageName != null) {
8728 serializer.attribute(null, "installer", pkg.installerPackageName);
8729 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008730 if (pkg.obbPathString != null) {
8731 serializer.attribute(null, "obbPath", pkg.obbPathString);
8732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008733 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8734 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8735 serializer.startTag(null, "perms");
8736 if (pkg.sharedUser == null) {
8737 // If this is a shared user, the permissions will
8738 // be written there. We still need to write an
8739 // empty permissions list so permissionsFixed will
8740 // be set.
8741 for (final String name : pkg.grantedPermissions) {
8742 serializer.startTag(null, "item");
8743 serializer.attribute(null, "name", name);
8744 serializer.endTag(null, "item");
8745 }
8746 }
8747 serializer.endTag(null, "perms");
8748 }
8749 if (pkg.disabledComponents.size() > 0) {
8750 serializer.startTag(null, "disabled-components");
8751 for (final String name : pkg.disabledComponents) {
8752 serializer.startTag(null, "item");
8753 serializer.attribute(null, "name", name);
8754 serializer.endTag(null, "item");
8755 }
8756 serializer.endTag(null, "disabled-components");
8757 }
8758 if (pkg.enabledComponents.size() > 0) {
8759 serializer.startTag(null, "enabled-components");
8760 for (final String name : pkg.enabledComponents) {
8761 serializer.startTag(null, "item");
8762 serializer.attribute(null, "name", name);
8763 serializer.endTag(null, "item");
8764 }
8765 serializer.endTag(null, "enabled-components");
8766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768 serializer.endTag(null, "package");
8769 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771 void writePermission(XmlSerializer serializer, BasePermission bp)
8772 throws XmlPullParserException, java.io.IOException {
8773 if (bp.type != BasePermission.TYPE_BUILTIN
8774 && bp.sourcePackage != null) {
8775 serializer.startTag(null, "item");
8776 serializer.attribute(null, "name", bp.name);
8777 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008778 if (bp.protectionLevel !=
8779 PermissionInfo.PROTECTION_NORMAL) {
8780 serializer.attribute(null, "protection",
8781 Integer.toString(bp.protectionLevel));
8782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008783 if (DEBUG_SETTINGS) Log.v(TAG,
8784 "Writing perm: name=" + bp.name + " type=" + bp.type);
8785 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8786 PermissionInfo pi = bp.perm != null ? bp.perm.info
8787 : bp.pendingInfo;
8788 if (pi != null) {
8789 serializer.attribute(null, "type", "dynamic");
8790 if (pi.icon != 0) {
8791 serializer.attribute(null, "icon",
8792 Integer.toString(pi.icon));
8793 }
8794 if (pi.nonLocalizedLabel != null) {
8795 serializer.attribute(null, "label",
8796 pi.nonLocalizedLabel.toString());
8797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008798 }
8799 }
8800 serializer.endTag(null, "item");
8801 }
8802 }
8803
8804 String getReadMessagesLP() {
8805 return mReadMessages.toString();
8806 }
8807
Oscar Montemayora8529f62009-11-18 10:14:20 -08008808 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8810 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008811 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008812 while(its.hasNext()) {
8813 String key = its.next();
8814 PackageSetting ps = mPackages.get(key);
8815 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008816 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008817 }
8818 }
8819 return ret;
8820 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008822 boolean readLP() {
8823 FileInputStream str = null;
8824 if (mBackupSettingsFilename.exists()) {
8825 try {
8826 str = new FileInputStream(mBackupSettingsFilename);
8827 mReadMessages.append("Reading from backup settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008828 reportSettingsProblem(Log.INFO, "Need to read from backup settings file");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008829 if (mSettingsFilename.exists()) {
8830 // If both the backup and settings file exist, we
8831 // ignore the settings since it might have been
8832 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008833 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008834 mSettingsFilename.delete();
8835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008836 } catch (java.io.IOException e) {
8837 // We'll try for the normal settings file.
8838 }
8839 }
8840
8841 mPastSignatures.clear();
8842
8843 try {
8844 if (str == null) {
8845 if (!mSettingsFilename.exists()) {
8846 mReadMessages.append("No settings file found\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008847 reportSettingsProblem(Log.INFO, "No settings file; creating initial state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008848 return false;
8849 }
8850 str = new FileInputStream(mSettingsFilename);
8851 }
8852 XmlPullParser parser = Xml.newPullParser();
8853 parser.setInput(str, null);
8854
8855 int type;
8856 while ((type=parser.next()) != XmlPullParser.START_TAG
8857 && type != XmlPullParser.END_DOCUMENT) {
8858 ;
8859 }
8860
8861 if (type != XmlPullParser.START_TAG) {
8862 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008863 reportSettingsProblem(Log.WARN, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 return false;
8865 }
8866
8867 int outerDepth = parser.getDepth();
8868 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8869 && (type != XmlPullParser.END_TAG
8870 || parser.getDepth() > outerDepth)) {
8871 if (type == XmlPullParser.END_TAG
8872 || type == XmlPullParser.TEXT) {
8873 continue;
8874 }
8875
8876 String tagName = parser.getName();
8877 if (tagName.equals("package")) {
8878 readPackageLP(parser);
8879 } else if (tagName.equals("permissions")) {
8880 readPermissionsLP(mPermissions, parser);
8881 } else if (tagName.equals("permission-trees")) {
8882 readPermissionsLP(mPermissionTrees, parser);
8883 } else if (tagName.equals("shared-user")) {
8884 readSharedUserLP(parser);
8885 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008886 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887 } else if (tagName.equals("preferred-activities")) {
8888 readPreferredActivitiesLP(parser);
8889 } else if(tagName.equals("updated-package")) {
8890 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008891 } else if (tagName.equals("cleaning-package")) {
8892 String name = parser.getAttributeValue(null, "name");
8893 if (name != null) {
8894 mPackagesToBeCleaned.add(name);
8895 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008896 } else if (tagName.equals("renamed-package")) {
8897 String nname = parser.getAttributeValue(null, "new");
8898 String oname = parser.getAttributeValue(null, "old");
8899 if (nname != null && oname != null) {
8900 mRenamedPackages.put(nname, oname);
8901 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008902 } else if (tagName.equals("last-platform-version")) {
8903 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8904 try {
8905 String internal = parser.getAttributeValue(null, "internal");
8906 if (internal != null) {
8907 mInternalSdkPlatform = Integer.parseInt(internal);
8908 }
8909 String external = parser.getAttributeValue(null, "external");
8910 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008911 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008912 }
8913 } catch (NumberFormatException e) {
8914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008915 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008916 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008917 + parser.getName());
8918 XmlUtils.skipCurrentTag(parser);
8919 }
8920 }
8921
8922 str.close();
8923
8924 } catch(XmlPullParserException e) {
8925 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07008926 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008927 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008928
8929 } catch(java.io.IOException e) {
8930 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07008931 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008932 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933
8934 }
8935
8936 int N = mPendingPackages.size();
8937 for (int i=0; i<N; i++) {
8938 final PendingPackage pp = mPendingPackages.get(i);
8939 Object idObj = getUserIdLP(pp.sharedId);
8940 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008941 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008942 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8943 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 if (p == null) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07008945 reportSettingsProblem(Log.WARN, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 + pp.name);
8947 continue;
8948 }
8949 p.copyFrom(pp);
8950 } else if (idObj != null) {
8951 String msg = "Bad package setting: package " + pp.name
8952 + " has shared uid " + pp.sharedId
8953 + " that is not a shared uid\n";
8954 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07008955 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956 } else {
8957 String msg = "Bad package setting: package " + pp.name
8958 + " has shared uid " + pp.sharedId
8959 + " that is not defined\n";
8960 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07008961 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008962 }
8963 }
8964 mPendingPackages.clear();
8965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 mReadMessages.append("Read completed successfully: "
8967 + mPackages.size() + " packages, "
8968 + mSharedUsers.size() + " shared uids\n");
8969
8970 return true;
8971 }
8972
8973 private int readInt(XmlPullParser parser, String ns, String name,
8974 int defValue) {
8975 String v = parser.getAttributeValue(ns, name);
8976 try {
8977 if (v == null) {
8978 return defValue;
8979 }
8980 return Integer.parseInt(v);
8981 } catch (NumberFormatException e) {
8982 reportSettingsProblem(Log.WARN,
8983 "Error in package manager settings: attribute " +
8984 name + " has bad integer value " + v + " at "
8985 + parser.getPositionDescription());
8986 }
8987 return defValue;
8988 }
8989
8990 private void readPermissionsLP(HashMap<String, BasePermission> out,
8991 XmlPullParser parser)
8992 throws IOException, XmlPullParserException {
8993 int outerDepth = parser.getDepth();
8994 int type;
8995 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8996 && (type != XmlPullParser.END_TAG
8997 || parser.getDepth() > outerDepth)) {
8998 if (type == XmlPullParser.END_TAG
8999 || type == XmlPullParser.TEXT) {
9000 continue;
9001 }
9002
9003 String tagName = parser.getName();
9004 if (tagName.equals("item")) {
9005 String name = parser.getAttributeValue(null, "name");
9006 String sourcePackage = parser.getAttributeValue(null, "package");
9007 String ptype = parser.getAttributeValue(null, "type");
9008 if (name != null && sourcePackage != null) {
9009 boolean dynamic = "dynamic".equals(ptype);
9010 BasePermission bp = new BasePermission(name, sourcePackage,
9011 dynamic
9012 ? BasePermission.TYPE_DYNAMIC
9013 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009014 bp.protectionLevel = readInt(parser, null, "protection",
9015 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 if (dynamic) {
9017 PermissionInfo pi = new PermissionInfo();
9018 pi.packageName = sourcePackage.intern();
9019 pi.name = name.intern();
9020 pi.icon = readInt(parser, null, "icon", 0);
9021 pi.nonLocalizedLabel = parser.getAttributeValue(
9022 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009023 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 bp.pendingInfo = pi;
9025 }
9026 out.put(bp.name, bp);
9027 } else {
9028 reportSettingsProblem(Log.WARN,
9029 "Error in package manager settings: permissions has"
9030 + " no name at " + parser.getPositionDescription());
9031 }
9032 } else {
9033 reportSettingsProblem(Log.WARN,
9034 "Unknown element reading permissions: "
9035 + parser.getName() + " at "
9036 + parser.getPositionDescription());
9037 }
9038 XmlUtils.skipCurrentTag(parser);
9039 }
9040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009043 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009044 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009045 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046 String codePathStr = parser.getAttributeValue(null, "codePath");
9047 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009048 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009049 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009050 resourcePathStr = codePathStr;
9051 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009052 String version = parser.getAttributeValue(null, "version");
9053 int versionCode = 0;
9054 if (version != null) {
9055 try {
9056 versionCode = Integer.parseInt(version);
9057 } catch (NumberFormatException e) {
9058 }
9059 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009061 int pkgFlags = 0;
9062 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009063 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9064 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009065 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009066 if (timeStampStr != null) {
9067 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009068 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009069 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009070 } catch (NumberFormatException e) {
9071 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009072 } else {
9073 timeStampStr = parser.getAttributeValue(null, "ts");
9074 if (timeStampStr != null) {
9075 try {
9076 long timeStamp = Long.parseLong(timeStampStr);
9077 ps.setTimeStamp(timeStamp);
9078 } catch (NumberFormatException e) {
9079 }
9080 }
9081 }
9082 timeStampStr = parser.getAttributeValue(null, "it");
9083 if (timeStampStr != null) {
9084 try {
9085 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9086 } catch (NumberFormatException e) {
9087 }
9088 }
9089 timeStampStr = parser.getAttributeValue(null, "ut");
9090 if (timeStampStr != null) {
9091 try {
9092 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9093 } catch (NumberFormatException e) {
9094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009095 }
9096 String idStr = parser.getAttributeValue(null, "userId");
9097 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9098 if(ps.userId <= 0) {
9099 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9100 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9101 }
9102 int outerDepth = parser.getDepth();
9103 int type;
9104 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9105 && (type != XmlPullParser.END_TAG
9106 || parser.getDepth() > outerDepth)) {
9107 if (type == XmlPullParser.END_TAG
9108 || type == XmlPullParser.TEXT) {
9109 continue;
9110 }
9111
9112 String tagName = parser.getName();
9113 if (tagName.equals("perms")) {
9114 readGrantedPermissionsLP(parser,
9115 ps.grantedPermissions);
9116 } else {
9117 reportSettingsProblem(Log.WARN,
9118 "Unknown element under <updated-package>: "
9119 + parser.getName());
9120 XmlUtils.skipCurrentTag(parser);
9121 }
9122 }
9123 mDisabledSysPackages.put(name, ps);
9124 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009126 private void readPackageLP(XmlPullParser parser)
9127 throws XmlPullParserException, IOException {
9128 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009129 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009130 String idStr = null;
9131 String sharedIdStr = null;
9132 String codePathStr = null;
9133 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009134 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009135 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009136 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009137 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009138 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009139 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009140 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009141 long firstInstallTime = 0;
9142 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009143 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009144 String version = null;
9145 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009146 try {
9147 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009148 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009149 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009150 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009151 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9152 codePathStr = parser.getAttributeValue(null, "codePath");
9153 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009154 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009155 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009156 version = parser.getAttributeValue(null, "version");
9157 if (version != null) {
9158 try {
9159 versionCode = Integer.parseInt(version);
9160 } catch (NumberFormatException e) {
9161 }
9162 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009163 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009164
9165 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009166 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009167 try {
9168 pkgFlags = Integer.parseInt(systemStr);
9169 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009170 }
9171 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009172 // For backward compatibility
9173 systemStr = parser.getAttributeValue(null, "system");
9174 if (systemStr != null) {
9175 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9176 } else {
9177 // Old settings that don't specify system... just treat
9178 // them as system, good enough.
9179 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009182 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 if (timeStampStr != null) {
9184 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009185 timeStamp = Long.parseLong(timeStampStr, 16);
9186 } catch (NumberFormatException e) {
9187 }
9188 } else {
9189 timeStampStr = parser.getAttributeValue(null, "ts");
9190 if (timeStampStr != null) {
9191 try {
9192 timeStamp = Long.parseLong(timeStampStr);
9193 } catch (NumberFormatException e) {
9194 }
9195 }
9196 }
9197 timeStampStr = parser.getAttributeValue(null, "it");
9198 if (timeStampStr != null) {
9199 try {
9200 firstInstallTime = Long.parseLong(timeStampStr, 16);
9201 } catch (NumberFormatException e) {
9202 }
9203 }
9204 timeStampStr = parser.getAttributeValue(null, "ut");
9205 if (timeStampStr != null) {
9206 try {
9207 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009208 } catch (NumberFormatException e) {
9209 }
9210 }
9211 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9212 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9213 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9214 if (resourcePathStr == null) {
9215 resourcePathStr = codePathStr;
9216 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009217 if (realName != null) {
9218 realName = realName.intern();
9219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009220 if (name == null) {
9221 reportSettingsProblem(Log.WARN,
9222 "Error in package manager settings: <package> has no name at "
9223 + parser.getPositionDescription());
9224 } else if (codePathStr == null) {
9225 reportSettingsProblem(Log.WARN,
9226 "Error in package manager settings: <package> has no codePath at "
9227 + parser.getPositionDescription());
9228 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009229 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9230 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9231 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009232 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9233 + ": userId=" + userId + " pkg=" + packageSetting);
9234 if (packageSetting == null) {
9235 reportSettingsProblem(Log.ERROR,
9236 "Failure adding uid " + userId
9237 + " while parsing settings at "
9238 + parser.getPositionDescription());
9239 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009240 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009241 packageSetting.firstInstallTime = firstInstallTime;
9242 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009243 }
9244 } else if (sharedIdStr != null) {
9245 userId = sharedIdStr != null
9246 ? Integer.parseInt(sharedIdStr) : 0;
9247 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009248 packageSetting = new PendingPackage(name.intern(), realName,
9249 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009250 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009251 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009252 packageSetting.firstInstallTime = firstInstallTime;
9253 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009254 mPendingPackages.add((PendingPackage) packageSetting);
9255 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9256 + ": sharedUserId=" + userId + " pkg="
9257 + packageSetting);
9258 } else {
9259 reportSettingsProblem(Log.WARN,
9260 "Error in package manager settings: package "
9261 + name + " has bad sharedId " + sharedIdStr
9262 + " at " + parser.getPositionDescription());
9263 }
9264 } else {
9265 reportSettingsProblem(Log.WARN,
9266 "Error in package manager settings: package "
9267 + name + " has bad userId " + idStr + " at "
9268 + parser.getPositionDescription());
9269 }
9270 } catch (NumberFormatException e) {
9271 reportSettingsProblem(Log.WARN,
9272 "Error in package manager settings: package "
9273 + name + " has bad userId " + idStr + " at "
9274 + parser.getPositionDescription());
9275 }
9276 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009277 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009278 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009279 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009280 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009281 final String enabledStr = parser.getAttributeValue(null, "enabled");
9282 if (enabledStr != null) {
9283 if (enabledStr.equalsIgnoreCase("true")) {
9284 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9285 } else if (enabledStr.equalsIgnoreCase("false")) {
9286 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9287 } else if (enabledStr.equalsIgnoreCase("default")) {
9288 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9289 } else {
9290 reportSettingsProblem(Log.WARN,
9291 "Error in package manager settings: package "
9292 + name + " has bad enabled value: " + idStr
9293 + " at " + parser.getPositionDescription());
9294 }
9295 } else {
9296 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9297 }
9298 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9299 if (installStatusStr != null) {
9300 if (installStatusStr.equalsIgnoreCase("false")) {
9301 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9302 } else {
9303 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9304 }
9305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307 int outerDepth = parser.getDepth();
9308 int type;
9309 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9310 && (type != XmlPullParser.END_TAG
9311 || parser.getDepth() > outerDepth)) {
9312 if (type == XmlPullParser.END_TAG
9313 || type == XmlPullParser.TEXT) {
9314 continue;
9315 }
9316
9317 String tagName = parser.getName();
9318 if (tagName.equals("disabled-components")) {
9319 readDisabledComponentsLP(packageSetting, parser);
9320 } else if (tagName.equals("enabled-components")) {
9321 readEnabledComponentsLP(packageSetting, parser);
9322 } else if (tagName.equals("sigs")) {
9323 packageSetting.signatures.readXml(parser, mPastSignatures);
9324 } else if (tagName.equals("perms")) {
9325 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009326 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009327 packageSetting.permissionsFixed = true;
9328 } else {
9329 reportSettingsProblem(Log.WARN,
9330 "Unknown element under <package>: "
9331 + parser.getName());
9332 XmlUtils.skipCurrentTag(parser);
9333 }
9334 }
9335 } else {
9336 XmlUtils.skipCurrentTag(parser);
9337 }
9338 }
9339
9340 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9341 XmlPullParser parser)
9342 throws IOException, XmlPullParserException {
9343 int outerDepth = parser.getDepth();
9344 int type;
9345 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9346 && (type != XmlPullParser.END_TAG
9347 || parser.getDepth() > outerDepth)) {
9348 if (type == XmlPullParser.END_TAG
9349 || type == XmlPullParser.TEXT) {
9350 continue;
9351 }
9352
9353 String tagName = parser.getName();
9354 if (tagName.equals("item")) {
9355 String name = parser.getAttributeValue(null, "name");
9356 if (name != null) {
9357 packageSetting.disabledComponents.add(name.intern());
9358 } else {
9359 reportSettingsProblem(Log.WARN,
9360 "Error in package manager settings: <disabled-components> has"
9361 + " no name at " + parser.getPositionDescription());
9362 }
9363 } else {
9364 reportSettingsProblem(Log.WARN,
9365 "Unknown element under <disabled-components>: "
9366 + parser.getName());
9367 }
9368 XmlUtils.skipCurrentTag(parser);
9369 }
9370 }
9371
9372 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9373 XmlPullParser parser)
9374 throws IOException, XmlPullParserException {
9375 int outerDepth = parser.getDepth();
9376 int type;
9377 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9378 && (type != XmlPullParser.END_TAG
9379 || parser.getDepth() > outerDepth)) {
9380 if (type == XmlPullParser.END_TAG
9381 || type == XmlPullParser.TEXT) {
9382 continue;
9383 }
9384
9385 String tagName = parser.getName();
9386 if (tagName.equals("item")) {
9387 String name = parser.getAttributeValue(null, "name");
9388 if (name != null) {
9389 packageSetting.enabledComponents.add(name.intern());
9390 } else {
9391 reportSettingsProblem(Log.WARN,
9392 "Error in package manager settings: <enabled-components> has"
9393 + " no name at " + parser.getPositionDescription());
9394 }
9395 } else {
9396 reportSettingsProblem(Log.WARN,
9397 "Unknown element under <enabled-components>: "
9398 + parser.getName());
9399 }
9400 XmlUtils.skipCurrentTag(parser);
9401 }
9402 }
9403
9404 private void readSharedUserLP(XmlPullParser parser)
9405 throws XmlPullParserException, IOException {
9406 String name = null;
9407 String idStr = null;
9408 int pkgFlags = 0;
9409 SharedUserSetting su = null;
9410 try {
9411 name = parser.getAttributeValue(null, "name");
9412 idStr = parser.getAttributeValue(null, "userId");
9413 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9414 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9415 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9416 }
9417 if (name == null) {
9418 reportSettingsProblem(Log.WARN,
9419 "Error in package manager settings: <shared-user> has no name at "
9420 + parser.getPositionDescription());
9421 } else if (userId == 0) {
9422 reportSettingsProblem(Log.WARN,
9423 "Error in package manager settings: shared-user "
9424 + name + " has bad userId " + idStr + " at "
9425 + parser.getPositionDescription());
9426 } else {
9427 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9428 reportSettingsProblem(Log.ERROR,
9429 "Occurred while parsing settings at "
9430 + parser.getPositionDescription());
9431 }
9432 }
9433 } catch (NumberFormatException e) {
9434 reportSettingsProblem(Log.WARN,
9435 "Error in package manager settings: package "
9436 + name + " has bad userId " + idStr + " at "
9437 + parser.getPositionDescription());
9438 };
9439
9440 if (su != null) {
9441 int outerDepth = parser.getDepth();
9442 int type;
9443 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9444 && (type != XmlPullParser.END_TAG
9445 || parser.getDepth() > outerDepth)) {
9446 if (type == XmlPullParser.END_TAG
9447 || type == XmlPullParser.TEXT) {
9448 continue;
9449 }
9450
9451 String tagName = parser.getName();
9452 if (tagName.equals("sigs")) {
9453 su.signatures.readXml(parser, mPastSignatures);
9454 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009455 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009456 } else {
9457 reportSettingsProblem(Log.WARN,
9458 "Unknown element under <shared-user>: "
9459 + parser.getName());
9460 XmlUtils.skipCurrentTag(parser);
9461 }
9462 }
9463
9464 } else {
9465 XmlUtils.skipCurrentTag(parser);
9466 }
9467 }
9468
9469 private void readGrantedPermissionsLP(XmlPullParser parser,
9470 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9471 int outerDepth = parser.getDepth();
9472 int type;
9473 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9474 && (type != XmlPullParser.END_TAG
9475 || parser.getDepth() > outerDepth)) {
9476 if (type == XmlPullParser.END_TAG
9477 || type == XmlPullParser.TEXT) {
9478 continue;
9479 }
9480
9481 String tagName = parser.getName();
9482 if (tagName.equals("item")) {
9483 String name = parser.getAttributeValue(null, "name");
9484 if (name != null) {
9485 outPerms.add(name.intern());
9486 } else {
9487 reportSettingsProblem(Log.WARN,
9488 "Error in package manager settings: <perms> has"
9489 + " no name at " + parser.getPositionDescription());
9490 }
9491 } else {
9492 reportSettingsProblem(Log.WARN,
9493 "Unknown element under <perms>: "
9494 + parser.getName());
9495 }
9496 XmlUtils.skipCurrentTag(parser);
9497 }
9498 }
9499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009500 private void readPreferredActivitiesLP(XmlPullParser parser)
9501 throws XmlPullParserException, IOException {
9502 int outerDepth = parser.getDepth();
9503 int type;
9504 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9505 && (type != XmlPullParser.END_TAG
9506 || parser.getDepth() > outerDepth)) {
9507 if (type == XmlPullParser.END_TAG
9508 || type == XmlPullParser.TEXT) {
9509 continue;
9510 }
9511
9512 String tagName = parser.getName();
9513 if (tagName.equals("item")) {
9514 PreferredActivity pa = new PreferredActivity(parser);
9515 if (pa.mParseError == null) {
9516 mPreferredActivities.addFilter(pa);
9517 } else {
9518 reportSettingsProblem(Log.WARN,
9519 "Error in package manager settings: <preferred-activity> "
9520 + pa.mParseError + " at "
9521 + parser.getPositionDescription());
9522 }
9523 } else {
9524 reportSettingsProblem(Log.WARN,
9525 "Unknown element under <preferred-activities>: "
9526 + parser.getName());
9527 XmlUtils.skipCurrentTag(parser);
9528 }
9529 }
9530 }
9531
9532 // Returns -1 if we could not find an available UserId to assign
9533 private int newUserIdLP(Object obj) {
9534 // Let's be stupidly inefficient for now...
9535 final int N = mUserIds.size();
9536 for (int i=0; i<N; i++) {
9537 if (mUserIds.get(i) == null) {
9538 mUserIds.set(i, obj);
9539 return FIRST_APPLICATION_UID + i;
9540 }
9541 }
9542
9543 // None left?
9544 if (N >= MAX_APPLICATION_UIDS) {
9545 return -1;
9546 }
9547
9548 mUserIds.add(obj);
9549 return FIRST_APPLICATION_UID + N;
9550 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009552 public PackageSetting getDisabledSystemPkg(String name) {
9553 synchronized(mPackages) {
9554 PackageSetting ps = mDisabledSysPackages.get(name);
9555 return ps;
9556 }
9557 }
9558
9559 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009560 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9561 return true;
9562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009563 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9564 if (Config.LOGV) {
9565 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9566 + " componentName = " + componentInfo.name);
9567 Log.v(TAG, "enabledComponents: "
9568 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9569 Log.v(TAG, "disabledComponents: "
9570 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9571 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009572 if (packageSettings == null) {
9573 if (false) {
9574 Log.w(TAG, "WAITING FOR DEBUGGER");
9575 Debug.waitForDebugger();
9576 Log.i(TAG, "We will crash!");
9577 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009578 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009579 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009580 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9581 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9582 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9583 return false;
9584 }
9585 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9586 return true;
9587 }
9588 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9589 return false;
9590 }
9591 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009592 }
9593 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009594
9595 // ------- apps on sdcard specific code -------
9596 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009597 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9598 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9599 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009600 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009601
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009602 private String getEncryptKey() {
9603 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009604 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9605 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009606 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009607 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9608 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009609 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009610 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009611 return null;
9612 }
9613 }
9614 return sdEncKey;
9615 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009616 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009617 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009618 } catch (IOException ioe) {
9619 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9620 + ioe);
9621 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009622 }
Rich Cannings8d578832010-09-09 15:12:40 -07009623
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009624 }
9625
Kenny Rootc78a8072010-07-27 15:18:38 -07009626 /* package */ static String getTempContainerId() {
9627 int tmpIdx = 1;
9628 String list[] = PackageHelper.getSecureContainerList();
9629 if (list != null) {
9630 for (final String name : list) {
9631 // Ignore null and non-temporary container entries
9632 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9633 continue;
9634 }
9635
9636 String subStr = name.substring(mTempContainerPrefix.length());
9637 try {
9638 int cid = Integer.parseInt(subStr);
9639 if (cid >= tmpIdx) {
9640 tmpIdx = cid + 1;
9641 }
9642 } catch (NumberFormatException e) {
9643 }
9644 }
9645 }
9646 return mTempContainerPrefix + tmpIdx;
9647 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009648
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009649 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009650 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009651 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009652 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
Marco Nelissen584f1372010-05-24 16:34:30 -07009653 int callingUid = Binder.getCallingUid();
9654 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009655 throw new SecurityException("Media status can only be updated by the system");
9656 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009657 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009658 Log.i(TAG, "Updating external media status from " +
9659 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9660 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009661 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9662 mediaStatus+", mMediaMounted=" + mMediaMounted);
9663 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009664 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9665 reportStatus ? 1 : 0, -1);
9666 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009667 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009668 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009669 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009670 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009671 // Queue up an async operation since the package installation may take a little while.
9672 mHandler.post(new Runnable() {
9673 public void run() {
9674 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009675 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009676 }
9677 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009678 }
9679
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009680 /*
9681 * Collect information of applications on external media, map them
9682 * against existing containers and update information based on current
9683 * mount status. Please note that we always have to report status
9684 * if reportStatus has been set to true especially when unloading packages.
9685 */
9686 private void updateExternalMediaStatusInner(boolean mediaStatus,
9687 boolean reportStatus) {
9688 // Collection of uids
9689 int uidArr[] = null;
9690 // Collection of stale containers
9691 HashSet<String> removeCids = new HashSet<String>();
9692 // Collection of packages on external media with valid containers.
9693 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9694 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009695 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009696 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009697 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009698 } else {
9699 // Process list of secure containers and categorize them
9700 // as active or stale based on their package internal state.
9701 int uidList[] = new int[list.length];
9702 int num = 0;
9703 synchronized (mPackages) {
9704 for (String cid : list) {
9705 SdInstallArgs args = new SdInstallArgs(cid);
9706 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009707 String pkgName = args.getPackageName();
9708 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009709 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9710 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009711 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009712 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009713 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9714 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009715 // The package status is changed only if the code path
9716 // matches between settings and the container id.
9717 if (ps != null && ps.codePathString != null &&
9718 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009719 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9720 " corresponds to pkg : " + pkgName +
9721 " at code path: " + ps.codePathString);
9722 // We do have a valid package installed on sdcard
9723 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009724 int uid = ps.userId;
9725 if (uid != -1) {
9726 uidList[num++] = uid;
9727 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009728 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009729 // Stale container on sdcard. Just delete
9730 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9731 removeCids.add(cid);
9732 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009733 }
9734 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009735
9736 if (num > 0) {
9737 // Sort uid list
9738 Arrays.sort(uidList, 0, num);
9739 // Throw away duplicates
9740 uidArr = new int[num];
9741 uidArr[0] = uidList[0];
9742 int di = 0;
9743 for (int i = 1; i < num; i++) {
9744 if (uidList[i-1] != uidList[i]) {
9745 uidArr[di++] = uidList[i];
9746 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009747 }
9748 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009749 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009750 // Process packages with valid entries.
9751 if (mediaStatus) {
9752 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009753 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009754 startCleaningPackages();
9755 } else {
9756 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009757 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009758 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009759 }
9760
9761 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009762 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009763 int size = pkgList.size();
9764 if (size > 0) {
9765 // Send broadcasts here
9766 Bundle extras = new Bundle();
9767 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9768 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009769 if (uidArr != null) {
9770 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9771 }
9772 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9773 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009774 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009775 }
9776 }
9777
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009778 /*
9779 * Look at potentially valid container ids from processCids
9780 * If package information doesn't match the one on record
9781 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009782 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009783 */
9784 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009785 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009786 ArrayList<String> pkgList = new ArrayList<String>();
9787 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009788 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009789 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009790 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009791 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9792 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009793 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009794 try {
9795 // Make sure there are no container errors first.
9796 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9797 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009798 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009799 " when installing from sdcard");
9800 continue;
9801 }
9802 // Check code path here.
9803 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009804 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009805 " does not match one in settings " + codePath);
9806 continue;
9807 }
9808 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009809 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009810 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009811 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009812 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009813 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009814 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009815 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009816 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009817 retCode = PackageManager.INSTALL_SUCCEEDED;
9818 pkgList.add(pkg.packageName);
9819 // Post process args
9820 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9821 }
9822 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009823 Slog.i(TAG, "Failed to install pkg from " +
9824 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009825 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009826 }
9827
9828 } finally {
9829 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9830 // Don't destroy container here. Wait till gc clears things up.
9831 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009832 }
9833 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009834 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009835 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009836 // If the platform SDK has changed since the last time we booted,
9837 // we need to re-grant app permission to catch any new ones that
9838 // appear. This is really a hack, and means that apps can in some
9839 // cases get permissions that the user didn't initially explicitly
9840 // allow... it would be nice to have some better way to handle
9841 // this situation.
9842 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9843 != mSdkVersion;
9844 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9845 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9846 + "; regranting permissions for external storage");
9847 mSettings.mExternalSdkPlatform = mSdkVersion;
9848
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009849 // Make sure group IDs have been assigned, and any permission
9850 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009851 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009852 // Persist settings
9853 mSettings.writeLP();
9854 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009855 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009856 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009857 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009858 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009859 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009860 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009861 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009862 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009863 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009864 if (removeCids != null) {
9865 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009866 if (cid.startsWith(mTempContainerPrefix)) {
9867 Log.i(TAG, "Destroying stale temporary container " + cid);
9868 PackageHelper.destroySdDir(cid);
9869 } else {
9870 Log.w(TAG, "Container " + cid + " is stale");
9871 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009872 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009873 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009874 }
9875
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009876 /*
9877 * Utility method to unload a list of specified containers
9878 */
9879 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9880 // Just unmount all valid containers.
9881 for (SdInstallArgs arg : cidArgs) {
9882 synchronized (mInstallLock) {
9883 arg.doPostDeleteLI(false);
9884 }
9885 }
9886 }
9887
9888 /*
9889 * Unload packages mounted on external media. This involves deleting
9890 * package data from internal structures, sending broadcasts about
9891 * diabled packages, gc'ing to free up references, unmounting all
9892 * secure containers corresponding to packages on external media, and
9893 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9894 * Please note that we always have to post this message if status has
9895 * been requested no matter what.
9896 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009897 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009898 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009899 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009900 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009901 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009902 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009903 for (SdInstallArgs args : keys) {
9904 String cid = args.cid;
9905 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009906 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009907 // Delete package internally
9908 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9909 synchronized (mInstallLock) {
9910 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009911 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009912 if (res) {
9913 pkgList.add(pkgName);
9914 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009915 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009916 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009917 }
9918 }
9919 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009920
9921 synchronized (mPackages) {
9922 // We didn't update the settings after removing each package;
9923 // write them now for all packages.
9924 mSettings.writeLP();
9925 }
9926
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009927 // We have to absolutely send UPDATED_MEDIA_STATUS only
9928 // after confirming that all the receivers processed the ordered
9929 // broadcast when packages get disabled, force a gc to clean things up.
9930 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009931 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009932 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9933 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9934 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009935 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9936 reportStatus ? 1 : 0, 1, keys);
9937 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009938 }
9939 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009940 } else {
9941 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9942 reportStatus ? 1 : 0, -1, keys);
9943 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009944 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009945 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009946
9947 public void movePackage(final String packageName,
9948 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009949 mContext.enforceCallingOrSelfPermission(
9950 android.Manifest.permission.MOVE_PACKAGE, null);
9951 int returnCode = PackageManager.MOVE_SUCCEEDED;
9952 int currFlags = 0;
9953 int newFlags = 0;
9954 synchronized (mPackages) {
9955 PackageParser.Package pkg = mPackages.get(packageName);
9956 if (pkg == null) {
9957 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009958 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009959 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009960 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009961 Slog.w(TAG, "Cannot move system application");
9962 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009963 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009964 Slog.w(TAG, "Cannot move forward locked app.");
9965 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009966 } else if (pkg.mOperationPending) {
9967 Slog.w(TAG, "Attempt to move package which has pending operations");
9968 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009969 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009970 // Find install location first
9971 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9972 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9973 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009974 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009975 } else {
9976 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9977 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009978 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9979 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009980 if (newFlags == currFlags) {
9981 Slog.w(TAG, "No move required. Trying to move to same location");
9982 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9983 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009984 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009985 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9986 pkg.mOperationPending = true;
9987 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009988 }
9989 }
9990 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009991 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009992 } else {
9993 Message msg = mHandler.obtainMessage(INIT_COPY);
9994 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009995 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9996 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9997 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009998 msg.obj = mp;
9999 mHandler.sendMessage(msg);
10000 }
10001 }
10002 }
10003
10004 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10005 // Queue up an async operation since the package deletion may take a little while.
10006 mHandler.post(new Runnable() {
10007 public void run() {
10008 mHandler.removeCallbacks(this);
10009 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010010 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10011 int uidArr[] = null;
10012 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010013 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010014 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010015 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010016 Slog.w(TAG, " Package " + mp.packageName +
10017 " doesn't exist. Aborting move");
10018 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10019 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10020 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10021 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10022 " Aborting move and returning error");
10023 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10024 } else {
10025 uidArr = new int[] { pkg.applicationInfo.uid };
10026 pkgList = new ArrayList<String>();
10027 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010028 }
10029 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010030 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10031 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010032 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010033 // Update package code and resource paths
10034 synchronized (mInstallLock) {
10035 synchronized (mPackages) {
10036 PackageParser.Package pkg = mPackages.get(mp.packageName);
10037 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010038 if (pkg == null) {
10039 Slog.w(TAG, " Package " + mp.packageName
10040 + " doesn't exist. Aborting move");
10041 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010042 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10043 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10044 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10045 " Aborting move and returning error");
10046 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10047 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010048 final String oldCodePath = pkg.mPath;
10049 final String newCodePath = mp.targetArgs.getCodePath();
10050 final String newResPath = mp.targetArgs.getResourcePath();
10051 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010052
10053 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10054 if (mInstaller
10055 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10056 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10057 } else {
10058 NativeLibraryHelper.copyNativeBinariesLI(
10059 new File(newCodePath), new File(newNativePath));
10060 }
10061 } else {
10062 if (mInstaller.linkNativeLibraryDirectory(
10063 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10064 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10065 }
10066 }
10067
10068 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10069 pkg.mPath = newCodePath;
10070 // Move dex files around
10071 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10072 // Moving of dex files failed. Set
10073 // error code and abort move.
10074 pkg.mPath = pkg.mScanPath;
10075 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10076 }
10077 }
10078
10079 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010080 pkg.mScanPath = newCodePath;
10081 pkg.applicationInfo.sourceDir = newCodePath;
10082 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010083 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010084 PackageSetting ps = (PackageSetting) pkg.mExtras;
10085 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10086 ps.codePathString = ps.codePath.getPath();
10087 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10088 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010089 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010090 // Set the application info flag correctly.
10091 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10092 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10093 } else {
10094 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10095 }
10096 ps.setFlags(pkg.applicationInfo.flags);
10097 mAppDirs.remove(oldCodePath);
10098 mAppDirs.put(newCodePath, pkg);
10099 // Persist settings
10100 mSettings.writeLP();
10101 }
10102 }
10103 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010104 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010105 // Send resources available broadcast
10106 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010107 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010108 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010109 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010110 // Clean up failed installation
10111 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010112 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010113 }
10114 } else {
10115 // Force a gc to clear things up.
10116 Runtime.getRuntime().gc();
10117 // Delete older code
10118 synchronized (mInstallLock) {
10119 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010120 }
10121 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010122
10123 // Allow more operations on this file if we didn't fail because
10124 // an operation was already pending for this package.
10125 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10126 synchronized (mPackages) {
10127 PackageParser.Package pkg = mPackages.get(mp.packageName);
10128 if (pkg != null) {
10129 pkg.mOperationPending = false;
10130 }
10131 }
10132 }
10133
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010134 IPackageMoveObserver observer = mp.observer;
10135 if (observer != null) {
10136 try {
10137 observer.packageMoved(mp.packageName, returnCode);
10138 } catch (RemoteException e) {
10139 Log.i(TAG, "Observer no longer exists.");
10140 }
10141 }
10142 }
10143 });
10144 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010145
10146 public boolean setInstallLocation(int loc) {
10147 mContext.enforceCallingOrSelfPermission(
10148 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10149 if (getInstallLocation() == loc) {
10150 return true;
10151 }
10152 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10153 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10154 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10155 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10156 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10157 return true;
10158 }
10159 return false;
10160 }
10161
10162 public int getInstallLocation() {
10163 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10164 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010166}