blob: bc802a830723cd4d2310528e1bcf17c19f283536 [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 }
Kenny Root85387d72010-08-26 10:13:11 -07005159 if (libraryPath != null) {
Kenny Root8f7cc022010-09-12 09:04:56 -07005160 NativeLibraryHelper.removeNativeBinariesLI(libraryPath);
Kenny Root85387d72010-08-26 10:13:11 -07005161 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005162 }
5163
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005164 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005165 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005166 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005167 final int filePermissions =
5168 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5169 |FileUtils.S_IROTH;
5170 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5171 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005172 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005173 getCodePath()
5174 + ". The return code was: " + retCode);
5175 // TODO Define new internal error
5176 return false;
5177 }
5178 return true;
5179 }
5180 return true;
5181 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005182
5183 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005184 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005185 cleanUpResourcesLI();
5186 return true;
5187 }
Kenny Root85387d72010-08-26 10:13:11 -07005188
5189 private boolean isFwdLocked() {
5190 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5191 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005192 }
5193
5194 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005195 static final String RES_FILE_NAME = "pkg.apk";
5196
Kenny Root85387d72010-08-26 10:13:11 -07005197 String cid;
5198 String packagePath;
5199 String libraryPath;
5200
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005201 SdInstallArgs(InstallParams params) {
5202 super(params.packageURI, params.observer,
5203 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005204 }
5205
Kenny Root85387d72010-08-26 10:13:11 -07005206 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005207 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005208 // Extract cid from fullCodePath
5209 int eidx = fullCodePath.lastIndexOf("/");
5210 String subStr1 = fullCodePath.substring(0, eidx);
5211 int sidx = subStr1.lastIndexOf("/");
5212 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005213 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005214 }
5215
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005216 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005217 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5218 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005219 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005220 }
5221
5222 SdInstallArgs(Uri packageURI, String cid) {
5223 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005224 this.cid = cid;
5225 }
5226
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005227 void createCopyFile() {
5228 cid = getTempContainerId();
5229 }
5230
Kenny Root11128572010-10-11 10:51:32 -07005231 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5232 try {
5233 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5234 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5235 return imcs.checkFreeStorage(true, packageURI);
5236 } finally {
5237 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5238 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005239 }
5240
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005241 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005242 if (temp) {
5243 createCopyFile();
5244 }
Kenny Root11128572010-10-11 10:51:32 -07005245
5246 final String newCachePath;
5247 try {
5248 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5249 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5250 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5251 getEncryptKey(), RES_FILE_NAME);
5252 } finally {
5253 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5254 }
5255
Kenny Root85387d72010-08-26 10:13:11 -07005256 if (newCachePath != null) {
5257 setCachePath(newCachePath);
5258 return PackageManager.INSTALL_SUCCEEDED;
5259 } else {
5260 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5261 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005262 }
5263
5264 @Override
5265 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005266 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005267 }
5268
5269 @Override
5270 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005271 return packagePath;
5272 }
5273
5274 @Override
5275 String getNativeLibraryPath() {
5276 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005277 }
5278
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005279 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005280 if (status != PackageManager.INSTALL_SUCCEEDED) {
5281 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005282 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005283 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005284 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005285 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005286 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5287 Process.SYSTEM_UID);
5288 if (newCachePath != null) {
5289 setCachePath(newCachePath);
5290 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005291 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5292 }
5293 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005294 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005295 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005296 }
5297
5298 boolean doRename(int status, final String pkgName,
5299 String oldCodePath) {
5300 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005301 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005302 if (PackageHelper.isContainerMounted(cid)) {
5303 // Unmount the container
5304 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005305 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005306 return false;
5307 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005308 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005309 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005310 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5311 " which might be stale. Will try to clean up.");
5312 // Clean up the stale container and proceed to recreate.
5313 if (!PackageHelper.destroySdDir(newCacheId)) {
5314 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5315 return false;
5316 }
5317 // Successfully cleaned up stale container. Try to rename again.
5318 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5319 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5320 + " inspite of cleaning it up.");
5321 return false;
5322 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005323 }
5324 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005325 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005326 newCachePath = PackageHelper.mountSdDir(newCacheId,
5327 getEncryptKey(), Process.SYSTEM_UID);
5328 } else {
5329 newCachePath = PackageHelper.getSdDir(newCacheId);
5330 }
5331 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005332 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005333 return false;
5334 }
5335 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005336 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005337 " at new path: " + newCachePath);
5338 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005339 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005340 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005341 }
5342
Kenny Root85387d72010-08-26 10:13:11 -07005343 private void setCachePath(String newCachePath) {
5344 File cachePath = new File(newCachePath);
5345 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5346 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5347 }
5348
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005349 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005350 if (status != PackageManager.INSTALL_SUCCEEDED) {
5351 cleanUp();
5352 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005353 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005354 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005355 PackageHelper.mountSdDir(cid,
5356 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005357 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005358 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005359 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005360 }
5361
5362 private void cleanUp() {
5363 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005364 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005365 }
5366
5367 void cleanUpResourcesLI() {
5368 String sourceFile = getCodePath();
5369 // Remove dex file
5370 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005371 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005372 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005373 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005374 + " at location "
5375 + sourceFile.toString() + ", retcode=" + retCode);
5376 // we don't consider this to be a failure of the core package deletion
5377 }
5378 }
5379 cleanUp();
5380 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005381
5382 boolean matchContainer(String app) {
5383 if (cid.startsWith(app)) {
5384 return true;
5385 }
5386 return false;
5387 }
5388
5389 String getPackageName() {
5390 int idx = cid.lastIndexOf("-");
5391 if (idx == -1) {
5392 return cid;
5393 }
5394 return cid.substring(0, idx);
5395 }
5396
5397 boolean doPostDeleteLI(boolean delete) {
5398 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005399 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005400 if (mounted) {
5401 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005402 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005403 }
5404 if (ret && delete) {
5405 cleanUpResourcesLI();
5406 }
5407 return ret;
5408 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005409 };
5410
5411 // Utility method used to create code paths based on package name and available index.
5412 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5413 String idxStr = "";
5414 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005415 // Fall back to default value of idx=1 if prefix is not
5416 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005417 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005418 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005419 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005420 if (subStr.endsWith(suffix)) {
5421 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005422 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005423 // If oldCodePath already contains prefix find out the
5424 // ending index to either increment or decrement.
5425 int sidx = subStr.lastIndexOf(prefix);
5426 if (sidx != -1) {
5427 subStr = subStr.substring(sidx + prefix.length());
5428 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005429 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5430 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005431 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005432 try {
5433 idx = Integer.parseInt(subStr);
5434 if (idx <= 1) {
5435 idx++;
5436 } else {
5437 idx--;
5438 }
5439 } catch(NumberFormatException e) {
5440 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005441 }
5442 }
5443 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005444 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005445 return prefix + idxStr;
5446 }
5447
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005448 // Utility method used to ignore ADD/REMOVE events
5449 // by directory observer.
5450 private static boolean ignoreCodePath(String fullPathStr) {
5451 String apkName = getApkName(fullPathStr);
5452 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5453 if (idx != -1 && ((idx+1) < apkName.length())) {
5454 // Make sure the package ends with a numeral
5455 String version = apkName.substring(idx+1);
5456 try {
5457 Integer.parseInt(version);
5458 return true;
5459 } catch (NumberFormatException e) {}
5460 }
5461 return false;
5462 }
5463
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005464 // Utility method that returns the relative package path with respect
5465 // to the installation directory. Like say for /data/data/com.test-1.apk
5466 // string com.test-1 is returned.
5467 static String getApkName(String codePath) {
5468 if (codePath == null) {
5469 return null;
5470 }
5471 int sidx = codePath.lastIndexOf("/");
5472 int eidx = codePath.lastIndexOf(".");
5473 if (eidx == -1) {
5474 eidx = codePath.length();
5475 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005476 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005477 return null;
5478 }
5479 return codePath.substring(sidx+1, eidx);
5480 }
5481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005482 class PackageInstalledInfo {
5483 String name;
5484 int uid;
5485 PackageParser.Package pkg;
5486 int returnCode;
5487 PackageRemovedInfo removedInfo;
5488 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 /*
5491 * Install a non-existing package.
5492 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005493 private void installNewPackageLI(PackageParser.Package pkg,
5494 int parseFlags,
5495 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005496 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005498 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005499
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005500 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005501 res.name = pkgName;
5502 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005503 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5504 // A package with the same name is already installed, though
5505 // it has been renamed to an older name. The package we
5506 // are trying to install should be installed as an update to
5507 // the existing one, but that has not been requested, so bail.
5508 Slog.w(TAG, "Attempt to re-install " + pkgName
5509 + " without first uninstalling package running as "
5510 + mSettings.mRenamedPackages.get(pkgName));
5511 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5512 return;
5513 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005514 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005516 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 + " without first uninstalling.");
5518 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5519 return;
5520 }
5521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005523 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5524 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005526 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005527 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5528 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5529 }
5530 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005531 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005532 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533 res);
5534 // delete the partially installed application. the data directory will have to be
5535 // restored if it was already existing
5536 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5537 // remove package from internal structures. Note that we want deletePackageX to
5538 // delete the package data and cache directories that it created in
5539 // scanPackageLocked, unless those directories existed before we even tried to
5540 // install.
5541 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005542 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005544 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 }
5546 }
5547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005548
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005549 private void replacePackageLI(PackageParser.Package pkg,
5550 int parseFlags,
5551 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005552 String installerPackageName, PackageInstalledInfo res) {
5553
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005554 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005555 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005556 // First find the old package info and check signatures
5557 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005558 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005559 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005560 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5562 return;
5563 }
5564 }
Kenny Root85387d72010-08-26 10:13:11 -07005565 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005566 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005567 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005568 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005569 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005570 }
5571 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005574 PackageParser.Package pkg,
5575 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005576 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 PackageParser.Package newPackage = null;
5578 String pkgName = deletedPackage.packageName;
5579 boolean deletedPkg = true;
5580 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005581
Jacek Surazski65e13172009-04-28 15:26:38 +02005582 String oldInstallerPackageName = null;
5583 synchronized (mPackages) {
5584 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5585 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005586
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005587 long origUpdateTime;
5588 if (pkg.mExtras != null) {
5589 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5590 } else {
5591 origUpdateTime = 0;
5592 }
5593
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005594 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005595 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005596 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005597 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5599 deletedPkg = false;
5600 } else {
5601 // Successfully deleted the old package. Now proceed with re-installation
5602 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005603 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5604 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005605 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005606 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005607 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5608 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005609 }
5610 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005611 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005612 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 res);
5614 updatedSettings = true;
5615 }
5616 }
5617
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005618 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 // remove package from internal structures. Note that we want deletePackageX to
5620 // delete the package data and cache directories that it created in
5621 // scanPackageLocked, unless those directories existed before we even tried to
5622 // install.
5623 if(updatedSettings) {
5624 deletePackageLI(
5625 pkgName, true,
5626 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005627 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 }
5629 // Since we failed to install the new package we need to restore the old
5630 // package that we deleted.
5631 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005632 File restoreFile = new File(deletedPackage.mPath);
5633 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005634 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005635 return;
5636 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005637 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005638 boolean oldOnSd = isExternal(deletedPackage);
5639 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5640 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5641 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005642 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5643 | SCAN_UPDATE_TIME;
5644 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5645 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005646 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5647 return;
5648 }
5649 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005650 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005651 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005652 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005653 mSettings.writeLP();
5654 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005655 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005656 }
5657 }
5658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005660 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005661 PackageParser.Package pkg,
5662 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005663 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005664 PackageParser.Package newPackage = null;
5665 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005666 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005667 PackageParser.PARSE_IS_SYSTEM;
5668 String packageName = deletedPackage.packageName;
5669 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5670 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005671 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005672 return;
5673 }
5674 PackageParser.Package oldPkg;
5675 PackageSetting oldPkgSetting;
5676 synchronized (mPackages) {
5677 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005678 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005679 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5680 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005681 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005682 return;
5683 }
5684 }
5685 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5686 res.removedInfo.removedPackage = packageName;
5687 // Remove existing system package
5688 removePackageLI(oldPkg, true);
5689 synchronized (mPackages) {
5690 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5691 }
5692
5693 // Successfully disabled the old package. Now proceed with re-installation
5694 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5695 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005696 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005698 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005699 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5700 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5701 }
5702 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005703 if (newPackage.mExtras != null) {
5704 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5705 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5706 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5707 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005708 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005709 updatedSettings = true;
5710 }
5711
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005712 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005713 // Re installation failed. Restore old information
5714 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005715 if (newPackage != null) {
5716 removePackageLI(newPackage, true);
5717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005718 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005719 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 // Restore the old system information in Settings
5721 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005722 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005723 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005724 mSettings.setInstallerPackageName(packageName,
5725 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005726 }
5727 mSettings.writeLP();
5728 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005729 } else {
5730 // If this is an update to an existing update, setup
5731 // to remove the existing update.
5732 synchronized (mPackages) {
5733 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5734 if (ps != null && ps.codePathString != null &&
5735 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005736 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005737 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005738 }
5739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 }
5741 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005742
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005743 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005744 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005745 int retCode;
5746 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5747 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5748 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005749 if (mNoDexOpt) {
5750 /*
5751 * If we're in an engineering build, programs are lazily run
5752 * through dexopt. If the .dex file doesn't exist yet, it
5753 * will be created when the program is run next.
5754 */
5755 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5756 } else {
5757 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5758 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5759 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005760 }
5761 }
5762 return PackageManager.INSTALL_SUCCEEDED;
5763 }
5764
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005765 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005766 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005767 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005768 synchronized (mPackages) {
5769 //write settings. the installStatus will be incomplete at this stage.
5770 //note that the new package setting would have already been
5771 //added to mPackages. It hasn't been persisted yet.
5772 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5773 mSettings.writeLP();
5774 }
5775
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005776 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005777 != PackageManager.INSTALL_SUCCEEDED) {
5778 // Discontinue if moving dex files failed.
5779 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005780 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005781 if((res.returnCode = setPermissionsLI(newPackage))
5782 != PackageManager.INSTALL_SUCCEEDED) {
5783 if (mInstaller != null) {
5784 mInstaller.rmdex(newPackage.mScanPath);
5785 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005786 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005788 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005791 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005792 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005793 res.name = pkgName;
5794 res.uid = newPackage.applicationInfo.uid;
5795 res.pkg = newPackage;
5796 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005797 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005798 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5799 //to update install status
5800 mSettings.writeLP();
5801 }
5802 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005803
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005804 private void installPackageLI(InstallArgs args,
5805 boolean newInstall, PackageInstalledInfo res) {
5806 int pFlags = args.flags;
5807 String installerPackageName = args.installerPackageName;
5808 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005809 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005810 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005811 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005812 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005813 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005814 // Result object to be returned
5815 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5816
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005817 // Retrieve PackageSettings and parse package
5818 int parseFlags = PackageParser.PARSE_CHATTY |
5819 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5820 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5821 parseFlags |= mDefParseFlags;
5822 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5823 pp.setSeparateProcesses(mSeparateProcesses);
5824 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5825 null, mMetrics, parseFlags);
5826 if (pkg == null) {
5827 res.returnCode = pp.getParseError();
5828 return;
5829 }
5830 String pkgName = res.name = pkg.packageName;
5831 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5832 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5833 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5834 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005836 }
5837 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5838 res.returnCode = pp.getParseError();
5839 return;
5840 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005841 // Get rid of all references to package scan path via parser.
5842 pp = null;
5843 String oldCodePath = null;
5844 boolean systemApp = false;
5845 synchronized (mPackages) {
5846 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005847 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5848 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005849 if (pkg.mOriginalPackages != null
5850 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005851 && mPackages.containsKey(oldName)) {
5852 // This package is derived from an original package,
5853 // and this device has been updating from that original
5854 // name. We must continue using the original name, so
5855 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005856 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005857 pkgName = pkg.packageName;
5858 replace = true;
5859 } else if (mPackages.containsKey(pkgName)) {
5860 // This package, under its official name, already exists
5861 // on the device; we should replace it.
5862 replace = true;
5863 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005864 }
5865 PackageSetting ps = mSettings.mPackages.get(pkgName);
5866 if (ps != null) {
5867 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5868 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5869 systemApp = (ps.pkg.applicationInfo.flags &
5870 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005871 }
5872 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005873 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005874
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005875 if (systemApp && onSd) {
5876 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005877 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005878 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5879 return;
5880 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005881
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005882 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5883 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5884 return;
5885 }
5886 // Set application objects path explicitly after the rename
5887 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005888 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005889 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005890 replacePackageLI(pkg, parseFlags, scanMode,
5891 installerPackageName, res);
5892 } else {
5893 installNewPackageLI(pkg, parseFlags, scanMode,
5894 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005895 }
5896 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005897
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005898 private int setPermissionsLI(PackageParser.Package newPackage) {
5899 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005900 int retCode = 0;
5901 // TODO Gross hack but fix later. Ideally move this to be a post installation
5902 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005903 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005904 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 try {
5906 extractPublicFiles(newPackage, destResourceFile);
5907 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005908 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 -08005909 " forward-locked app.");
5910 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5911 } finally {
5912 //TODO clean up the extracted public files
5913 }
5914 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005915 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005916 newPackage.applicationInfo.uid);
5917 } else {
5918 final int filePermissions =
5919 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005920 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005921 newPackage.applicationInfo.uid);
5922 }
5923 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005924 // The permissions on the resource file was set when it was copied for
5925 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005926 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005927
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005928 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005929 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005930 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005931 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005932 // TODO Define new internal error
5933 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005934 }
5935 return PackageManager.INSTALL_SUCCEEDED;
5936 }
5937
Kenny Root85387d72010-08-26 10:13:11 -07005938 private static boolean isForwardLocked(PackageParser.Package pkg) {
5939 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005940 }
5941
Kenny Root85387d72010-08-26 10:13:11 -07005942 private static boolean isExternal(PackageParser.Package pkg) {
5943 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5944 }
5945
5946 private static boolean isSystemApp(PackageParser.Package pkg) {
5947 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5948 }
5949
5950 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5951 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005952 }
5953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005954 private void extractPublicFiles(PackageParser.Package newPackage,
5955 File publicZipFile) throws IOException {
5956 final ZipOutputStream publicZipOutStream =
5957 new ZipOutputStream(new FileOutputStream(publicZipFile));
5958 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5959
5960 // Copy manifest, resources.arsc and res directory to public zip
5961
5962 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5963 while (privateZipEntries.hasMoreElements()) {
5964 final ZipEntry zipEntry = privateZipEntries.nextElement();
5965 final String zipEntryName = zipEntry.getName();
5966 if ("AndroidManifest.xml".equals(zipEntryName)
5967 || "resources.arsc".equals(zipEntryName)
5968 || zipEntryName.startsWith("res/")) {
5969 try {
5970 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5971 } catch (IOException e) {
5972 try {
5973 publicZipOutStream.close();
5974 throw e;
5975 } finally {
5976 publicZipFile.delete();
5977 }
5978 }
5979 }
5980 }
5981
5982 publicZipOutStream.close();
5983 FileUtils.setPermissions(
5984 publicZipFile.getAbsolutePath(),
5985 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5986 -1, -1);
5987 }
5988
5989 private static void copyZipEntry(ZipEntry zipEntry,
5990 ZipFile inZipFile,
5991 ZipOutputStream outZipStream) throws IOException {
5992 byte[] buffer = new byte[4096];
5993 int num;
5994
5995 ZipEntry newEntry;
5996 if (zipEntry.getMethod() == ZipEntry.STORED) {
5997 // Preserve the STORED method of the input entry.
5998 newEntry = new ZipEntry(zipEntry);
5999 } else {
6000 // Create a new entry so that the compressed len is recomputed.
6001 newEntry = new ZipEntry(zipEntry.getName());
6002 }
6003 outZipStream.putNextEntry(newEntry);
6004
6005 InputStream data = inZipFile.getInputStream(zipEntry);
6006 while ((num = data.read(buffer)) > 0) {
6007 outZipStream.write(buffer, 0, num);
6008 }
6009 outZipStream.flush();
6010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 private void deleteTempPackageFiles() {
6013 FilenameFilter filter = new FilenameFilter() {
6014 public boolean accept(File dir, String name) {
6015 return name.startsWith("vmdl") && name.endsWith(".tmp");
6016 }
6017 };
6018 String tmpFilesList[] = mAppInstallDir.list(filter);
6019 if(tmpFilesList == null) {
6020 return;
6021 }
6022 for(int i = 0; i < tmpFilesList.length; i++) {
6023 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6024 tmpFile.delete();
6025 }
6026 }
6027
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006028 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006029 File tmpPackageFile;
6030 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006031 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006032 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006033 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006034 return null;
6035 }
6036 try {
6037 FileUtils.setPermissions(
6038 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6039 -1, -1);
6040 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006041 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 return null;
6043 }
6044 return tmpPackageFile;
6045 }
6046
6047 public void deletePackage(final String packageName,
6048 final IPackageDeleteObserver observer,
6049 final int flags) {
6050 mContext.enforceCallingOrSelfPermission(
6051 android.Manifest.permission.DELETE_PACKAGES, null);
6052 // Queue up an async operation since the package deletion may take a little while.
6053 mHandler.post(new Runnable() {
6054 public void run() {
6055 mHandler.removeCallbacks(this);
6056 final boolean succeded = deletePackageX(packageName, true, true, flags);
6057 if (observer != null) {
6058 try {
6059 observer.packageDeleted(succeded);
6060 } catch (RemoteException e) {
6061 Log.i(TAG, "Observer no longer exists.");
6062 } //end catch
6063 } //end if
6064 } //end run
6065 });
6066 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006068 /**
6069 * This method is an internal method that could be get invoked either
6070 * to delete an installed package or to clean up a failed installation.
6071 * After deleting an installed package, a broadcast is sent to notify any
6072 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006073 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006074 * installation wouldn't have sent the initial broadcast either
6075 * The key steps in deleting a package are
6076 * deleting the package information in internal structures like mPackages,
6077 * deleting the packages base directories through installd
6078 * updating mSettings to reflect current status
6079 * persisting settings for later use
6080 * sending a broadcast if necessary
6081 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6083 boolean deleteCodeAndResources, int flags) {
6084 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006085 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006087 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6088 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6089 try {
6090 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006091 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006092 return false;
6093 }
6094 } catch (RemoteException e) {
6095 }
6096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006098 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006099 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006101
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006102 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006103 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006104 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006105
6106 // If the removed package was a system update, the old system packaged
6107 // was re-enabled; we need to broadcast this information
6108 if (systemUpdate) {
6109 Bundle extras = new Bundle(1);
6110 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6111 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6112
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006113 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6114 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006117 // Force a gc here.
6118 Runtime.getRuntime().gc();
6119 // Delete the resources here after sending the broadcast to let
6120 // other processes clean up before deleting resources.
6121 if (info.args != null) {
6122 synchronized (mInstallLock) {
6123 info.args.doPostDeleteLI(deleteCodeAndResources);
6124 }
6125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 return res;
6127 }
6128
6129 static class PackageRemovedInfo {
6130 String removedPackage;
6131 int uid = -1;
6132 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006133 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006134 // Clean up resources deleted packages.
6135 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006136
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006137 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006138 Bundle extras = new Bundle(1);
6139 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6140 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6141 if (replacing) {
6142 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6143 }
6144 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006145 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006146 }
6147 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006148 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006149 }
6150 }
6151 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 /*
6154 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6155 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006156 * 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 -08006157 * delete a partially installed application.
6158 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006159 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006160 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006161 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006162 if (outInfo != null) {
6163 outInfo.removedPackage = packageName;
6164 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006165 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006166 // Retrieve object to delete permissions for shared user later on
6167 PackageSetting deletedPs;
6168 synchronized (mPackages) {
6169 deletedPs = mSettings.mPackages.get(packageName);
6170 }
6171 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006172 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006174 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006175 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006176 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006177 + packageName + ", retcode=" + retCode);
6178 // we don't consider this to be a failure of the core package deletion
6179 }
6180 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006181 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 PackageParser.Package pkg = mPackages.get(packageName);
6183 File dataDir = new File(pkg.applicationInfo.dataDir);
6184 dataDir.delete();
6185 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006186 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006187 }
6188 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006189 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006190 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6191 if (outInfo != null) {
6192 outInfo.removedUid = mSettings.removePackageLP(packageName);
6193 }
6194 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006195 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006196 if (deletedPs.sharedUser != null) {
6197 // remove permissions associated with package
6198 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6199 }
6200 }
6201 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006202 // remove from preferred activities.
6203 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6204 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6205 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6206 removed.add(pa);
6207 }
6208 }
6209 for (PreferredActivity pa : removed) {
6210 mSettings.mPreferredActivities.removeFilter(pa);
6211 }
6212 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006213 if (writeSettings) {
6214 // Save settings now
6215 mSettings.writeLP();
6216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006217 }
6218 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 /*
6221 * Tries to delete system package.
6222 */
6223 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006224 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 ApplicationInfo applicationInfo = p.applicationInfo;
6226 //applicable for non-partially installed applications only
6227 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006228 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 return false;
6230 }
6231 PackageSetting ps = null;
6232 // Confirm if the system package has been updated
6233 // An updated system app can be deleted. This will also have to restore
6234 // the system pkg from system partition
6235 synchronized (mPackages) {
6236 ps = mSettings.getDisabledSystemPkg(p.packageName);
6237 }
6238 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006239 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006240 return false;
6241 } else {
6242 Log.i(TAG, "Deleting system pkg from data partition");
6243 }
6244 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006245 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006246 final boolean deleteCodeAndResources;
6247 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006248 // Delete code and resources for downgrades
6249 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006250 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006251 } else {
6252 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006253 deleteCodeAndResources = false;
6254 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006255 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006256 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6257 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006258 if (!ret) {
6259 return false;
6260 }
6261 synchronized (mPackages) {
6262 // Reinstate the old system package
6263 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006264 // Remove any native libraries from the upgraded package.
6265 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006266 }
6267 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006268 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006270 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006273 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 return false;
6275 }
6276 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006277 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006278 if (writeSettings) {
6279 mSettings.writeLP();
6280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006281 }
6282 return true;
6283 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006286 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6287 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006288 ApplicationInfo applicationInfo = p.applicationInfo;
6289 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006290 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006291 return false;
6292 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006293 if (outInfo != null) {
6294 outInfo.uid = applicationInfo.uid;
6295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006296
6297 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006298 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299
6300 // Delete application code and resources
6301 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006302 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006303 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6304 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6305 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6306 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 }
6308 return true;
6309 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 /*
6312 * This method handles package deletion in general
6313 */
6314 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006315 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6316 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006317 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006318 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006319 return false;
6320 }
6321 PackageParser.Package p;
6322 boolean dataOnly = false;
6323 synchronized (mPackages) {
6324 p = mPackages.get(packageName);
6325 if (p == null) {
6326 //this retrieves partially installed apps
6327 dataOnly = true;
6328 PackageSetting ps = mSettings.mPackages.get(packageName);
6329 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006330 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006331 return false;
6332 }
6333 p = ps.pkg;
6334 }
6335 }
6336 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006337 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 return false;
6339 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006341 if (dataOnly) {
6342 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006343 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 return true;
6345 }
6346 // At this point the package should have ApplicationInfo associated with it
6347 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006348 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006349 return false;
6350 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006351 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006352 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 Log.i(TAG, "Removing system package:"+p.packageName);
6354 // When an updated system application is deleted we delete the existing resources as well and
6355 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006356 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006357 } else {
6358 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006359 // Kill application pre-emptively especially for apps on sd.
6360 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006361 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6362 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006364 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006365 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 public void clearApplicationUserData(final String packageName,
6368 final IPackageDataObserver observer) {
6369 mContext.enforceCallingOrSelfPermission(
6370 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6371 // Queue up an async operation since the package deletion may take a little while.
6372 mHandler.post(new Runnable() {
6373 public void run() {
6374 mHandler.removeCallbacks(this);
6375 final boolean succeeded;
6376 synchronized (mInstallLock) {
6377 succeeded = clearApplicationUserDataLI(packageName);
6378 }
6379 if (succeeded) {
6380 // invoke DeviceStorageMonitor's update method to clear any notifications
6381 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6382 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6383 if (dsm != null) {
6384 dsm.updateMemory();
6385 }
6386 }
6387 if(observer != null) {
6388 try {
6389 observer.onRemoveCompleted(packageName, succeeded);
6390 } catch (RemoteException e) {
6391 Log.i(TAG, "Observer no longer exists.");
6392 }
6393 } //end if observer
6394 } //end run
6395 });
6396 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006397
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 private boolean clearApplicationUserDataLI(String packageName) {
6399 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006400 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 return false;
6402 }
6403 PackageParser.Package p;
6404 boolean dataOnly = false;
6405 synchronized (mPackages) {
6406 p = mPackages.get(packageName);
6407 if(p == null) {
6408 dataOnly = true;
6409 PackageSetting ps = mSettings.mPackages.get(packageName);
6410 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006411 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 return false;
6413 }
6414 p = ps.pkg;
6415 }
6416 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006417 boolean useEncryptedFSDir = false;
6418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 if(!dataOnly) {
6420 //need to check this only for fully installed applications
6421 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006422 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 return false;
6424 }
6425 final ApplicationInfo applicationInfo = p.applicationInfo;
6426 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006427 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 return false;
6429 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006430 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006431 }
6432 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006433 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006434 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006435 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 + packageName);
6437 return false;
6438 }
6439 }
6440 return true;
6441 }
6442
6443 public void deleteApplicationCacheFiles(final String packageName,
6444 final IPackageDataObserver observer) {
6445 mContext.enforceCallingOrSelfPermission(
6446 android.Manifest.permission.DELETE_CACHE_FILES, null);
6447 // Queue up an async operation since the package deletion may take a little while.
6448 mHandler.post(new Runnable() {
6449 public void run() {
6450 mHandler.removeCallbacks(this);
6451 final boolean succeded;
6452 synchronized (mInstallLock) {
6453 succeded = deleteApplicationCacheFilesLI(packageName);
6454 }
6455 if(observer != null) {
6456 try {
6457 observer.onRemoveCompleted(packageName, succeded);
6458 } catch (RemoteException e) {
6459 Log.i(TAG, "Observer no longer exists.");
6460 }
6461 } //end if observer
6462 } //end run
6463 });
6464 }
6465
6466 private boolean deleteApplicationCacheFilesLI(String packageName) {
6467 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006468 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 return false;
6470 }
6471 PackageParser.Package p;
6472 synchronized (mPackages) {
6473 p = mPackages.get(packageName);
6474 }
6475 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006476 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 return false;
6478 }
6479 final ApplicationInfo applicationInfo = p.applicationInfo;
6480 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006481 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006482 return false;
6483 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006484 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006486 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006488 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006489 + packageName);
6490 return false;
6491 }
6492 }
6493 return true;
6494 }
6495
6496 public void getPackageSizeInfo(final String packageName,
6497 final IPackageStatsObserver observer) {
6498 mContext.enforceCallingOrSelfPermission(
6499 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6500 // Queue up an async operation since the package deletion may take a little while.
6501 mHandler.post(new Runnable() {
6502 public void run() {
6503 mHandler.removeCallbacks(this);
6504 PackageStats lStats = new PackageStats(packageName);
6505 final boolean succeded;
6506 synchronized (mInstallLock) {
6507 succeded = getPackageSizeInfoLI(packageName, lStats);
6508 }
6509 if(observer != null) {
6510 try {
6511 observer.onGetStatsCompleted(lStats, succeded);
6512 } catch (RemoteException e) {
6513 Log.i(TAG, "Observer no longer exists.");
6514 }
6515 } //end if observer
6516 } //end run
6517 });
6518 }
6519
6520 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6521 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006522 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006523 return false;
6524 }
6525 PackageParser.Package p;
6526 boolean dataOnly = false;
6527 synchronized (mPackages) {
6528 p = mPackages.get(packageName);
6529 if(p == null) {
6530 dataOnly = true;
6531 PackageSetting ps = mSettings.mPackages.get(packageName);
6532 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006533 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 return false;
6535 }
6536 p = ps.pkg;
6537 }
6538 }
6539 String publicSrcDir = null;
6540 if(!dataOnly) {
6541 final ApplicationInfo applicationInfo = p.applicationInfo;
6542 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006543 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006544 return false;
6545 }
6546 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6547 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006548 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006549 if (mInstaller != null) {
6550 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006551 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 if (res < 0) {
6553 return false;
6554 } else {
6555 return true;
6556 }
6557 }
6558 return true;
6559 }
6560
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006562 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006563 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 }
6565
6566 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006567 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 }
6569
6570 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006571 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006572 }
6573
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006574 int getUidTargetSdkVersionLockedLP(int uid) {
6575 Object obj = mSettings.getUserIdLP(uid);
6576 if (obj instanceof SharedUserSetting) {
6577 SharedUserSetting sus = (SharedUserSetting)obj;
6578 final int N = sus.packages.size();
6579 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6580 Iterator<PackageSetting> it = sus.packages.iterator();
6581 int i=0;
6582 while (it.hasNext()) {
6583 PackageSetting ps = it.next();
6584 if (ps.pkg != null) {
6585 int v = ps.pkg.applicationInfo.targetSdkVersion;
6586 if (v < vers) vers = v;
6587 }
6588 }
6589 return vers;
6590 } else if (obj instanceof PackageSetting) {
6591 PackageSetting ps = (PackageSetting)obj;
6592 if (ps.pkg != null) {
6593 return ps.pkg.applicationInfo.targetSdkVersion;
6594 }
6595 }
6596 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6597 }
6598
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006599 public void addPreferredActivity(IntentFilter filter, int match,
6600 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006601 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006602 if (mContext.checkCallingOrSelfPermission(
6603 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6604 != PackageManager.PERMISSION_GRANTED) {
6605 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6606 < Build.VERSION_CODES.FROYO) {
6607 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6608 + Binder.getCallingUid());
6609 return;
6610 }
6611 mContext.enforceCallingOrSelfPermission(
6612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6613 }
6614
6615 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006616 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6617 mSettings.mPreferredActivities.addFilter(
6618 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006619 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 }
6621 }
6622
Satish Sampath8dbe6122009-06-02 23:35:54 +01006623 public void replacePreferredActivity(IntentFilter filter, int match,
6624 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006625 if (filter.countActions() != 1) {
6626 throw new IllegalArgumentException(
6627 "replacePreferredActivity expects filter to have only 1 action.");
6628 }
6629 if (filter.countCategories() != 1) {
6630 throw new IllegalArgumentException(
6631 "replacePreferredActivity expects filter to have only 1 category.");
6632 }
6633 if (filter.countDataAuthorities() != 0
6634 || filter.countDataPaths() != 0
6635 || filter.countDataSchemes() != 0
6636 || filter.countDataTypes() != 0) {
6637 throw new IllegalArgumentException(
6638 "replacePreferredActivity expects filter to have no data authorities, " +
6639 "paths, schemes or types.");
6640 }
6641 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006642 if (mContext.checkCallingOrSelfPermission(
6643 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6644 != PackageManager.PERMISSION_GRANTED) {
6645 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6646 < Build.VERSION_CODES.FROYO) {
6647 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6648 + Binder.getCallingUid());
6649 return;
6650 }
6651 mContext.enforceCallingOrSelfPermission(
6652 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6653 }
6654
Satish Sampath8dbe6122009-06-02 23:35:54 +01006655 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6656 String action = filter.getAction(0);
6657 String category = filter.getCategory(0);
6658 while (it.hasNext()) {
6659 PreferredActivity pa = it.next();
6660 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6661 it.remove();
6662 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6663 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6664 }
6665 }
6666 addPreferredActivity(filter, match, set, activity);
6667 }
6668 }
6669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006670 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006672 int uid = Binder.getCallingUid();
6673 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006674 if (pkg == null || pkg.applicationInfo.uid != uid) {
6675 if (mContext.checkCallingOrSelfPermission(
6676 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6677 != PackageManager.PERMISSION_GRANTED) {
6678 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6679 < Build.VERSION_CODES.FROYO) {
6680 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6681 + Binder.getCallingUid());
6682 return;
6683 }
6684 mContext.enforceCallingOrSelfPermission(
6685 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6686 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006687 }
6688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006689 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006690 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006691 }
6692 }
6693 }
6694
6695 boolean clearPackagePreferredActivitiesLP(String packageName) {
6696 boolean changed = false;
6697 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6698 while (it.hasNext()) {
6699 PreferredActivity pa = it.next();
6700 if (pa.mActivity.getPackageName().equals(packageName)) {
6701 it.remove();
6702 changed = true;
6703 }
6704 }
6705 return changed;
6706 }
6707
6708 public int getPreferredActivities(List<IntentFilter> outFilters,
6709 List<ComponentName> outActivities, String packageName) {
6710
6711 int num = 0;
6712 synchronized (mPackages) {
6713 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6714 while (it.hasNext()) {
6715 PreferredActivity pa = it.next();
6716 if (packageName == null
6717 || pa.mActivity.getPackageName().equals(packageName)) {
6718 if (outFilters != null) {
6719 outFilters.add(new IntentFilter(pa));
6720 }
6721 if (outActivities != null) {
6722 outActivities.add(pa.mActivity);
6723 }
6724 }
6725 }
6726 }
6727
6728 return num;
6729 }
6730
6731 public void setApplicationEnabledSetting(String appPackageName,
6732 int newState, int flags) {
6733 setEnabledSetting(appPackageName, null, newState, flags);
6734 }
6735
6736 public void setComponentEnabledSetting(ComponentName componentName,
6737 int newState, int flags) {
6738 setEnabledSetting(componentName.getPackageName(),
6739 componentName.getClassName(), newState, flags);
6740 }
6741
6742 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006743 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006744 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6745 || newState == COMPONENT_ENABLED_STATE_ENABLED
6746 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6747 throw new IllegalArgumentException("Invalid new component state: "
6748 + newState);
6749 }
6750 PackageSetting pkgSetting;
6751 final int uid = Binder.getCallingUid();
6752 final int permission = mContext.checkCallingPermission(
6753 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6754 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006755 boolean sendNow = false;
6756 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006757 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006758 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006759 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006760 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006761 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006762 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006763 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006765 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 }
6767 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006768 "Unknown component: " + packageName
6769 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 }
6771 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6772 throw new SecurityException(
6773 "Permission Denial: attempt to change component state from pid="
6774 + Binder.getCallingPid()
6775 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6776 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006777 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006779 if (pkgSetting.enabled == newState) {
6780 // Nothing to do
6781 return;
6782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006783 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006784 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006785 } else {
6786 // We're dealing with a component level state change
6787 switch (newState) {
6788 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006789 if (!pkgSetting.enableComponentLP(className)) {
6790 return;
6791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006792 break;
6793 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006794 if (!pkgSetting.disableComponentLP(className)) {
6795 return;
6796 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006797 break;
6798 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006799 if (!pkgSetting.restoreComponentLP(className)) {
6800 return;
6801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006802 break;
6803 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006804 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006805 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006806 }
6807 }
6808 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006809 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006810 components = mPendingBroadcasts.get(packageName);
6811 boolean newPackage = components == null;
6812 if (newPackage) {
6813 components = new ArrayList<String>();
6814 }
6815 if (!components.contains(componentName)) {
6816 components.add(componentName);
6817 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006818 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6819 sendNow = true;
6820 // Purge entry from pending broadcast list if another one exists already
6821 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006822 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006823 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006824 if (newPackage) {
6825 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006826 }
6827 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6828 // Schedule a message
6829 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6830 }
6831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006832 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006834 long callingId = Binder.clearCallingIdentity();
6835 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006836 if (sendNow) {
6837 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006838 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 } finally {
6841 Binder.restoreCallingIdentity(callingId);
6842 }
6843 }
6844
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006845 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006846 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6847 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6848 + " components=" + componentNames);
6849 Bundle extras = new Bundle(4);
6850 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6851 String nameList[] = new String[componentNames.size()];
6852 componentNames.toArray(nameList);
6853 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006854 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6855 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006856 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006857 }
6858
Jacek Surazski65e13172009-04-28 15:26:38 +02006859 public String getInstallerPackageName(String packageName) {
6860 synchronized (mPackages) {
6861 PackageSetting pkg = mSettings.mPackages.get(packageName);
6862 if (pkg == null) {
6863 throw new IllegalArgumentException("Unknown package: " + packageName);
6864 }
6865 return pkg.installerPackageName;
6866 }
6867 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006869 public int getApplicationEnabledSetting(String appPackageName) {
6870 synchronized (mPackages) {
6871 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6872 if (pkg == null) {
6873 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6874 }
6875 return pkg.enabled;
6876 }
6877 }
6878
6879 public int getComponentEnabledSetting(ComponentName componentName) {
6880 synchronized (mPackages) {
6881 final String packageNameStr = componentName.getPackageName();
6882 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6883 if (pkg == null) {
6884 throw new IllegalArgumentException("Unknown component: " + componentName);
6885 }
6886 final String classNameStr = componentName.getClassName();
6887 return pkg.currentEnabledStateLP(classNameStr);
6888 }
6889 }
6890
6891 public void enterSafeMode() {
6892 if (!mSystemReady) {
6893 mSafeMode = true;
6894 }
6895 }
6896
6897 public void systemReady() {
6898 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006899
6900 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006901 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006902 mContext.getContentResolver(),
6903 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006904 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006905 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006906 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006907 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006908 }
6909
6910 public boolean isSafeMode() {
6911 return mSafeMode;
6912 }
6913
6914 public boolean hasSystemUidErrors() {
6915 return mHasSystemUidErrors;
6916 }
6917
6918 static String arrayToString(int[] array) {
6919 StringBuffer buf = new StringBuffer(128);
6920 buf.append('[');
6921 if (array != null) {
6922 for (int i=0; i<array.length; i++) {
6923 if (i > 0) buf.append(", ");
6924 buf.append(array[i]);
6925 }
6926 }
6927 buf.append(']');
6928 return buf.toString();
6929 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931 @Override
6932 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6933 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6934 != PackageManager.PERMISSION_GRANTED) {
6935 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6936 + Binder.getCallingPid()
6937 + ", uid=" + Binder.getCallingUid()
6938 + " without permission "
6939 + android.Manifest.permission.DUMP);
6940 return;
6941 }
6942
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006943 boolean dumpStar = true;
6944 boolean dumpLibs = false;
6945 boolean dumpFeatures = false;
6946 boolean dumpResolvers = false;
6947 boolean dumpPermissions = false;
6948 boolean dumpPackages = false;
6949 boolean dumpSharedUsers = false;
6950 boolean dumpMessages = false;
6951 boolean dumpProviders = false;
6952
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006953 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006954 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006955
6956 int opti = 0;
6957 while (opti < args.length) {
6958 String opt = args[opti];
6959 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6960 break;
6961 }
6962 opti++;
6963 if ("-a".equals(opt)) {
6964 // Right now we only know how to print all.
6965 } else if ("-h".equals(opt)) {
6966 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006967 pw.println(" [-h] [-f] [cmd] ...");
6968 pw.println(" -f: print details of intent filters");
6969 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006970 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006971 pw.println(" l[ibraries]: list known shared libraries");
6972 pw.println(" f[ibraries]: list device features");
6973 pw.println(" r[esolvers]: dump intent resolvers");
6974 pw.println(" perm[issions]: dump permissions");
6975 pw.println(" prov[iders]: dump content providers");
6976 pw.println(" p[ackages]: dump installed packages");
6977 pw.println(" s[hared-users]: dump shared user IDs");
6978 pw.println(" m[essages]: print collected runtime messages");
6979 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006980 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006981 } else if ("-f".equals(opt)) {
6982 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006983 } else {
6984 pw.println("Unknown argument: " + opt + "; use -h for help");
6985 }
6986 }
6987
6988 // Is the caller requesting to dump a particular piece of data?
6989 if (opti < args.length) {
6990 String cmd = args[opti];
6991 opti++;
6992 // Is this a package name?
6993 if ("android".equals(cmd) || cmd.contains(".")) {
6994 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07006995 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
6996 dumpStar = false;
6997 dumpLibs = true;
6998 } else if ("f".equals(cmd) || "features".equals(cmd)) {
6999 dumpStar = false;
7000 dumpFeatures = true;
7001 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
7002 dumpStar = false;
7003 dumpResolvers = true;
7004 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
7005 dumpStar = false;
7006 dumpPermissions = true;
7007 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
7008 dumpStar = false;
7009 dumpPackages = true;
7010 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
7011 dumpStar = false;
7012 dumpSharedUsers = true;
7013 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
7014 dumpStar = false;
7015 dumpProviders = true;
7016 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
7017 dumpStar = false;
7018 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007019 }
7020 }
7021
7022 boolean printedTitle = false;
7023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007024 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007025 if ((dumpStar || dumpLibs) && packageName == null) {
7026 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007027 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007028 pw.println("Libraries:");
7029 Iterator<String> it = mSharedLibraries.keySet().iterator();
7030 while (it.hasNext()) {
7031 String name = it.next();
7032 pw.print(" ");
7033 pw.print(name);
7034 pw.print(" -> ");
7035 pw.println(mSharedLibraries.get(name));
7036 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007037 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007038
7039 if ((dumpStar || dumpFeatures) && packageName == null) {
7040 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007041 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007042 pw.println("Features:");
7043 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7044 while (it.hasNext()) {
7045 String name = it.next();
7046 pw.print(" ");
7047 pw.println(name);
7048 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007049 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007050
7051 if (dumpStar || dumpResolvers) {
7052 if (mActivities.dump(pw, printedTitle
7053 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7054 " ", packageName, showFilters)) {
7055 printedTitle = true;
7056 }
7057 if (mReceivers.dump(pw, printedTitle
7058 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7059 " ", packageName, showFilters)) {
7060 printedTitle = true;
7061 }
7062 if (mServices.dump(pw, printedTitle
7063 ? "\nService Resolver Table:" : "Service Resolver Table:",
7064 " ", packageName, showFilters)) {
7065 printedTitle = true;
7066 }
7067 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7068 ? "\nPreferred Activities:" : "Preferred Activities:",
7069 " ", packageName, showFilters)) {
7070 printedTitle = true;
7071 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007072 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007073
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007074 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007075 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007076 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007077 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7078 continue;
7079 }
7080 if (!printedSomething) {
7081 if (printedTitle) pw.println(" ");
7082 pw.println("Permissions:");
7083 printedSomething = true;
7084 printedTitle = true;
7085 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007086 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7087 pw.print(Integer.toHexString(System.identityHashCode(p)));
7088 pw.println("):");
7089 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7090 pw.print(" uid="); pw.print(p.uid);
7091 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007092 pw.print(" type="); pw.print(p.type);
7093 pw.print(" prot="); pw.println(p.protectionLevel);
7094 if (p.packageSetting != null) {
7095 pw.print(" packageSetting="); pw.println(p.packageSetting);
7096 }
7097 if (p.perm != null) {
7098 pw.print(" perm="); pw.println(p.perm);
7099 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007100 }
7101 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007102
7103 if (dumpStar || dumpProviders) {
7104 printedSomething = false;
7105 for (PackageParser.Provider p : mProviders.values()) {
7106 if (packageName != null && !packageName.equals(p.info.packageName)) {
7107 continue;
7108 }
7109 if (!printedSomething) {
7110 if (printedTitle) pw.println(" ");
7111 pw.println("Registered ContentProviders:");
7112 printedSomething = true;
7113 printedTitle = true;
7114 }
7115 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7116 pw.println(p.toString());
7117 }
7118 }
7119
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007120 printedSomething = false;
7121 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007122 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007123 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7124 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007125 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007126 if (packageName != null && !packageName.equals(ps.realName)
7127 && !packageName.equals(ps.name)) {
7128 continue;
7129 }
7130 if (!printedSomething) {
7131 if (printedTitle) pw.println(" ");
7132 pw.println("Packages:");
7133 printedSomething = true;
7134 printedTitle = true;
7135 }
7136 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007137 pw.print(" Package [");
7138 pw.print(ps.realName != null ? ps.realName : ps.name);
7139 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007140 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7141 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007142 if (ps.realName != null) {
7143 pw.print(" compat name="); pw.println(ps.name);
7144 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007145 pw.print(" userId="); pw.print(ps.userId);
7146 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7147 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7148 pw.print(" pkg="); pw.println(ps.pkg);
7149 pw.print(" codePath="); pw.println(ps.codePathString);
7150 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007151 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007152 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007154 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007155 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007156 if (ps.pkg.mOperationPending) {
7157 pw.println(" mOperationPending=true");
7158 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007159 pw.print(" supportsScreens=[");
7160 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007161 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007162 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7163 if (!first) pw.print(", ");
7164 first = false;
7165 pw.print("small");
7166 }
7167 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007168 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007169 if (!first) pw.print(", ");
7170 first = false;
7171 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007172 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007173 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007174 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007175 if (!first) pw.print(", ");
7176 first = false;
7177 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007178 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007179 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007180 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007181 if (!first) pw.print(", ");
7182 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007183 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007184 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007185 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007186 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007187 if (!first) pw.print(", ");
7188 first = false;
7189 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007190 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007191 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007192 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7193 if (!first) pw.print(", ");
7194 first = false;
7195 pw.print("anyDensity");
7196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007197 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007198 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007199 pw.print(" timeStamp=");
7200 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7201 pw.print(" firstInstallTime=");
7202 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7203 pw.print(" lastUpdateTime=");
7204 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007205 pw.print(" signatures="); pw.println(ps.signatures);
7206 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007207 pw.print(" haveGids="); pw.println(ps.haveGids);
7208 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007209 pw.print(" installStatus="); pw.print(ps.installStatus);
7210 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 if (ps.disabledComponents.size() > 0) {
7212 pw.println(" disabledComponents:");
7213 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007214 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007215 }
7216 }
7217 if (ps.enabledComponents.size() > 0) {
7218 pw.println(" enabledComponents:");
7219 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007220 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007221 }
7222 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007223 if (ps.grantedPermissions.size() > 0) {
7224 pw.println(" grantedPermissions:");
7225 for (String s : ps.grantedPermissions) {
7226 pw.print(" "); pw.println(s);
7227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007229 }
7230 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007231 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007232 if (dumpStar || dumpPackages) {
7233 if (mSettings.mRenamedPackages.size() > 0) {
7234 for (HashMap.Entry<String, String> e
7235 : mSettings.mRenamedPackages.entrySet()) {
7236 if (packageName != null && !packageName.equals(e.getKey())
7237 && !packageName.equals(e.getValue())) {
7238 continue;
7239 }
7240 if (!printedSomething) {
7241 if (printedTitle) pw.println(" ");
7242 pw.println("Renamed packages:");
7243 printedSomething = true;
7244 printedTitle = true;
7245 }
7246 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7247 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007248 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007249 }
7250 printedSomething = false;
7251 if (mSettings.mDisabledSysPackages.size() > 0) {
7252 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7253 if (packageName != null && !packageName.equals(ps.realName)
7254 && !packageName.equals(ps.name)) {
7255 continue;
7256 }
7257 if (!printedSomething) {
7258 if (printedTitle) pw.println(" ");
7259 pw.println("Hidden system packages:");
7260 printedSomething = true;
7261 printedTitle = true;
7262 }
7263 pw.print(" Package [");
7264 pw.print(ps.realName != null ? ps.realName : ps.name);
7265 pw.print("] (");
7266 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7267 pw.println("):");
7268 if (ps.realName != null) {
7269 pw.print(" compat name="); pw.println(ps.name);
7270 }
7271 pw.print(" userId="); pw.println(ps.userId);
7272 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7273 pw.print(" codePath="); pw.println(ps.codePathString);
7274 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007275 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007276 }
7277 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007278 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007279 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007280 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007281 if (packageName != null && su != packageSharedUser) {
7282 continue;
7283 }
7284 if (!printedSomething) {
7285 if (printedTitle) pw.println(" ");
7286 pw.println("Shared users:");
7287 printedSomething = true;
7288 printedTitle = true;
7289 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007290 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7291 pw.print(Integer.toHexString(System.identityHashCode(su)));
7292 pw.println("):");
7293 pw.print(" userId="); pw.print(su.userId);
7294 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007295 pw.println(" grantedPermissions:");
7296 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007297 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007299 }
7300 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007301
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007302 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007303 if (printedTitle) pw.println(" ");
7304 printedTitle = true;
7305 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007306 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007307
7308 pw.println(" ");
7309 pw.println("Package warning messages:");
7310 File fname = getSettingsProblemFile();
7311 FileInputStream in;
7312 try {
7313 in = new FileInputStream(fname);
7314 int avail = in.available();
7315 byte[] data = new byte[avail];
7316 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007317 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007318 } catch (FileNotFoundException e) {
7319 } catch (IOException e) {
7320 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007322 }
7323 }
7324
7325 static final class BasePermission {
7326 final static int TYPE_NORMAL = 0;
7327 final static int TYPE_BUILTIN = 1;
7328 final static int TYPE_DYNAMIC = 2;
7329
7330 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007331 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007332 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007333 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007334 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007335 PackageParser.Permission perm;
7336 PermissionInfo pendingInfo;
7337 int uid;
7338 int[] gids;
7339
7340 BasePermission(String _name, String _sourcePackage, int _type) {
7341 name = _name;
7342 sourcePackage = _sourcePackage;
7343 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007344 // Default to most conservative protection level.
7345 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7346 }
7347
7348 public String toString() {
7349 return "BasePermission{"
7350 + Integer.toHexString(System.identityHashCode(this))
7351 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007352 }
7353 }
7354
7355 static class PackageSignatures {
7356 private Signature[] mSignatures;
7357
7358 PackageSignatures(Signature[] sigs) {
7359 assignSignatures(sigs);
7360 }
7361
7362 PackageSignatures() {
7363 }
7364
7365 void writeXml(XmlSerializer serializer, String tagName,
7366 ArrayList<Signature> pastSignatures) throws IOException {
7367 if (mSignatures == null) {
7368 return;
7369 }
7370 serializer.startTag(null, tagName);
7371 serializer.attribute(null, "count",
7372 Integer.toString(mSignatures.length));
7373 for (int i=0; i<mSignatures.length; i++) {
7374 serializer.startTag(null, "cert");
7375 final Signature sig = mSignatures[i];
7376 final int sigHash = sig.hashCode();
7377 final int numPast = pastSignatures.size();
7378 int j;
7379 for (j=0; j<numPast; j++) {
7380 Signature pastSig = pastSignatures.get(j);
7381 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7382 serializer.attribute(null, "index", Integer.toString(j));
7383 break;
7384 }
7385 }
7386 if (j >= numPast) {
7387 pastSignatures.add(sig);
7388 serializer.attribute(null, "index", Integer.toString(numPast));
7389 serializer.attribute(null, "key", sig.toCharsString());
7390 }
7391 serializer.endTag(null, "cert");
7392 }
7393 serializer.endTag(null, tagName);
7394 }
7395
7396 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7397 throws IOException, XmlPullParserException {
7398 String countStr = parser.getAttributeValue(null, "count");
7399 if (countStr == null) {
7400 reportSettingsProblem(Log.WARN,
7401 "Error in package manager settings: <signatures> has"
7402 + " no count at " + parser.getPositionDescription());
7403 XmlUtils.skipCurrentTag(parser);
7404 }
7405 final int count = Integer.parseInt(countStr);
7406 mSignatures = new Signature[count];
7407 int pos = 0;
7408
7409 int outerDepth = parser.getDepth();
7410 int type;
7411 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7412 && (type != XmlPullParser.END_TAG
7413 || parser.getDepth() > outerDepth)) {
7414 if (type == XmlPullParser.END_TAG
7415 || type == XmlPullParser.TEXT) {
7416 continue;
7417 }
7418
7419 String tagName = parser.getName();
7420 if (tagName.equals("cert")) {
7421 if (pos < count) {
7422 String index = parser.getAttributeValue(null, "index");
7423 if (index != null) {
7424 try {
7425 int idx = Integer.parseInt(index);
7426 String key = parser.getAttributeValue(null, "key");
7427 if (key == null) {
7428 if (idx >= 0 && idx < pastSignatures.size()) {
7429 Signature sig = pastSignatures.get(idx);
7430 if (sig != null) {
7431 mSignatures[pos] = pastSignatures.get(idx);
7432 pos++;
7433 } else {
7434 reportSettingsProblem(Log.WARN,
7435 "Error in package manager settings: <cert> "
7436 + "index " + index + " is not defined at "
7437 + parser.getPositionDescription());
7438 }
7439 } else {
7440 reportSettingsProblem(Log.WARN,
7441 "Error in package manager settings: <cert> "
7442 + "index " + index + " is out of bounds at "
7443 + parser.getPositionDescription());
7444 }
7445 } else {
7446 while (pastSignatures.size() <= idx) {
7447 pastSignatures.add(null);
7448 }
7449 Signature sig = new Signature(key);
7450 pastSignatures.set(idx, sig);
7451 mSignatures[pos] = sig;
7452 pos++;
7453 }
7454 } catch (NumberFormatException e) {
7455 reportSettingsProblem(Log.WARN,
7456 "Error in package manager settings: <cert> "
7457 + "index " + index + " is not a number at "
7458 + parser.getPositionDescription());
7459 }
7460 } else {
7461 reportSettingsProblem(Log.WARN,
7462 "Error in package manager settings: <cert> has"
7463 + " no index at " + parser.getPositionDescription());
7464 }
7465 } else {
7466 reportSettingsProblem(Log.WARN,
7467 "Error in package manager settings: too "
7468 + "many <cert> tags, expected " + count
7469 + " at " + parser.getPositionDescription());
7470 }
7471 } else {
7472 reportSettingsProblem(Log.WARN,
7473 "Unknown element under <cert>: "
7474 + parser.getName());
7475 }
7476 XmlUtils.skipCurrentTag(parser);
7477 }
7478
7479 if (pos < count) {
7480 // Should never happen -- there is an error in the written
7481 // settings -- but if it does we don't want to generate
7482 // a bad array.
7483 Signature[] newSigs = new Signature[pos];
7484 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7485 mSignatures = newSigs;
7486 }
7487 }
7488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007489 private void assignSignatures(Signature[] sigs) {
7490 if (sigs == null) {
7491 mSignatures = null;
7492 return;
7493 }
7494 mSignatures = new Signature[sigs.length];
7495 for (int i=0; i<sigs.length; i++) {
7496 mSignatures[i] = sigs[i];
7497 }
7498 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007499
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007500 @Override
7501 public String toString() {
7502 StringBuffer buf = new StringBuffer(128);
7503 buf.append("PackageSignatures{");
7504 buf.append(Integer.toHexString(System.identityHashCode(this)));
7505 buf.append(" [");
7506 if (mSignatures != null) {
7507 for (int i=0; i<mSignatures.length; i++) {
7508 if (i > 0) buf.append(", ");
7509 buf.append(Integer.toHexString(
7510 System.identityHashCode(mSignatures[i])));
7511 }
7512 }
7513 buf.append("]}");
7514 return buf.toString();
7515 }
7516 }
7517
7518 static class PreferredActivity extends IntentFilter {
7519 final int mMatch;
7520 final String[] mSetPackages;
7521 final String[] mSetClasses;
7522 final String[] mSetComponents;
7523 final ComponentName mActivity;
7524 final String mShortActivity;
7525 String mParseError;
7526
7527 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7528 ComponentName activity) {
7529 super(filter);
7530 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7531 mActivity = activity;
7532 mShortActivity = activity.flattenToShortString();
7533 mParseError = null;
7534 if (set != null) {
7535 final int N = set.length;
7536 String[] myPackages = new String[N];
7537 String[] myClasses = new String[N];
7538 String[] myComponents = new String[N];
7539 for (int i=0; i<N; i++) {
7540 ComponentName cn = set[i];
7541 if (cn == null) {
7542 mSetPackages = null;
7543 mSetClasses = null;
7544 mSetComponents = null;
7545 return;
7546 }
7547 myPackages[i] = cn.getPackageName().intern();
7548 myClasses[i] = cn.getClassName().intern();
7549 myComponents[i] = cn.flattenToShortString().intern();
7550 }
7551 mSetPackages = myPackages;
7552 mSetClasses = myClasses;
7553 mSetComponents = myComponents;
7554 } else {
7555 mSetPackages = null;
7556 mSetClasses = null;
7557 mSetComponents = null;
7558 }
7559 }
7560
7561 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7562 IOException {
7563 mShortActivity = parser.getAttributeValue(null, "name");
7564 mActivity = ComponentName.unflattenFromString(mShortActivity);
7565 if (mActivity == null) {
7566 mParseError = "Bad activity name " + mShortActivity;
7567 }
7568 String matchStr = parser.getAttributeValue(null, "match");
7569 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7570 String setCountStr = parser.getAttributeValue(null, "set");
7571 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7572
7573 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7574 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7575 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7576
7577 int setPos = 0;
7578
7579 int outerDepth = parser.getDepth();
7580 int type;
7581 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7582 && (type != XmlPullParser.END_TAG
7583 || parser.getDepth() > outerDepth)) {
7584 if (type == XmlPullParser.END_TAG
7585 || type == XmlPullParser.TEXT) {
7586 continue;
7587 }
7588
7589 String tagName = parser.getName();
7590 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7591 // + parser.getDepth() + " tag=" + tagName);
7592 if (tagName.equals("set")) {
7593 String name = parser.getAttributeValue(null, "name");
7594 if (name == null) {
7595 if (mParseError == null) {
7596 mParseError = "No name in set tag in preferred activity "
7597 + mShortActivity;
7598 }
7599 } else if (setPos >= setCount) {
7600 if (mParseError == null) {
7601 mParseError = "Too many set tags in preferred activity "
7602 + mShortActivity;
7603 }
7604 } else {
7605 ComponentName cn = ComponentName.unflattenFromString(name);
7606 if (cn == null) {
7607 if (mParseError == null) {
7608 mParseError = "Bad set name " + name + " in preferred activity "
7609 + mShortActivity;
7610 }
7611 } else {
7612 myPackages[setPos] = cn.getPackageName();
7613 myClasses[setPos] = cn.getClassName();
7614 myComponents[setPos] = name;
7615 setPos++;
7616 }
7617 }
7618 XmlUtils.skipCurrentTag(parser);
7619 } else if (tagName.equals("filter")) {
7620 //Log.i(TAG, "Starting to parse filter...");
7621 readFromXml(parser);
7622 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7623 // + parser.getDepth() + " tag=" + parser.getName());
7624 } else {
7625 reportSettingsProblem(Log.WARN,
7626 "Unknown element under <preferred-activities>: "
7627 + parser.getName());
7628 XmlUtils.skipCurrentTag(parser);
7629 }
7630 }
7631
7632 if (setPos != setCount) {
7633 if (mParseError == null) {
7634 mParseError = "Not enough set tags (expected " + setCount
7635 + " but found " + setPos + ") in " + mShortActivity;
7636 }
7637 }
7638
7639 mSetPackages = myPackages;
7640 mSetClasses = myClasses;
7641 mSetComponents = myComponents;
7642 }
7643
7644 public void writeToXml(XmlSerializer serializer) throws IOException {
7645 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7646 serializer.attribute(null, "name", mShortActivity);
7647 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7648 serializer.attribute(null, "set", Integer.toString(NS));
7649 for (int s=0; s<NS; s++) {
7650 serializer.startTag(null, "set");
7651 serializer.attribute(null, "name", mSetComponents[s]);
7652 serializer.endTag(null, "set");
7653 }
7654 serializer.startTag(null, "filter");
7655 super.writeToXml(serializer);
7656 serializer.endTag(null, "filter");
7657 }
7658
7659 boolean sameSet(List<ResolveInfo> query, int priority) {
7660 if (mSetPackages == null) return false;
7661 final int NQ = query.size();
7662 final int NS = mSetPackages.length;
7663 int numMatch = 0;
7664 for (int i=0; i<NQ; i++) {
7665 ResolveInfo ri = query.get(i);
7666 if (ri.priority != priority) continue;
7667 ActivityInfo ai = ri.activityInfo;
7668 boolean good = false;
7669 for (int j=0; j<NS; j++) {
7670 if (mSetPackages[j].equals(ai.packageName)
7671 && mSetClasses[j].equals(ai.name)) {
7672 numMatch++;
7673 good = true;
7674 break;
7675 }
7676 }
7677 if (!good) return false;
7678 }
7679 return numMatch == NS;
7680 }
7681 }
7682
7683 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007684 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007686 HashSet<String> grantedPermissions = new HashSet<String>();
7687 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007689 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007690 setFlags(pkgFlags);
7691 }
7692
7693 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007694 this.pkgFlags = pkgFlags & (
7695 ApplicationInfo.FLAG_SYSTEM |
7696 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007697 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007698 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007699 }
7700 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007702 /**
7703 * Settings base class for pending and resolved classes.
7704 */
7705 static class PackageSettingBase extends GrantedPermissions {
7706 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007707 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007708 File codePath;
7709 String codePathString;
7710 File resourcePath;
7711 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007712 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007713 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007714 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007715 long firstInstallTime;
7716 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007717 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007719 boolean uidError;
7720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721 PackageSignatures signatures = new PackageSignatures();
7722
7723 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007724 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007726 /* Explicitly disabled components */
7727 HashSet<String> disabledComponents = new HashSet<String>(0);
7728 /* Explicitly enabled components */
7729 HashSet<String> enabledComponents = new HashSet<String>(0);
7730 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7731 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007732
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007733 PackageSettingBase origPackage;
7734
Jacek Surazski65e13172009-04-28 15:26:38 +02007735 /* package name of the app that installed this package */
7736 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007737
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007738 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007739 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740 super(pkgFlags);
7741 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007742 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007743 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007744 }
7745
Kenny Root806cc132010-09-12 08:34:19 -07007746 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7747 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007748 this.codePath = codePath;
7749 this.codePathString = codePath.toString();
7750 this.resourcePath = resourcePath;
7751 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007752 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007753 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007754 }
Kenny Root85387d72010-08-26 10:13:11 -07007755
Jacek Surazski65e13172009-04-28 15:26:38 +02007756 public void setInstallerPackageName(String packageName) {
7757 installerPackageName = packageName;
7758 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007759
Jacek Surazski65e13172009-04-28 15:26:38 +02007760 String getInstallerPackageName() {
7761 return installerPackageName;
7762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 public void setInstallStatus(int newStatus) {
7765 installStatus = newStatus;
7766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007768 public int getInstallStatus() {
7769 return installStatus;
7770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007772 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 }
7775
7776 public void copyFrom(PackageSettingBase base) {
7777 grantedPermissions = base.grantedPermissions;
7778 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007779
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007780 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007781 firstInstallTime = base.firstInstallTime;
7782 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007783 signatures = base.signatures;
7784 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007785 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007786 disabledComponents = base.disabledComponents;
7787 enabledComponents = base.enabledComponents;
7788 enabled = base.enabled;
7789 installStatus = base.installStatus;
7790 }
7791
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007792 boolean enableComponentLP(String componentClassName) {
7793 boolean changed = disabledComponents.remove(componentClassName);
7794 changed |= enabledComponents.add(componentClassName);
7795 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 }
7797
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007798 boolean disableComponentLP(String componentClassName) {
7799 boolean changed = enabledComponents.remove(componentClassName);
7800 changed |= disabledComponents.add(componentClassName);
7801 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 }
7803
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007804 boolean restoreComponentLP(String componentClassName) {
7805 boolean changed = enabledComponents.remove(componentClassName);
7806 changed |= disabledComponents.remove(componentClassName);
7807 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007808 }
7809
7810 int currentEnabledStateLP(String componentName) {
7811 if (enabledComponents.contains(componentName)) {
7812 return COMPONENT_ENABLED_STATE_ENABLED;
7813 } else if (disabledComponents.contains(componentName)) {
7814 return COMPONENT_ENABLED_STATE_DISABLED;
7815 } else {
7816 return COMPONENT_ENABLED_STATE_DEFAULT;
7817 }
7818 }
7819 }
7820
7821 /**
7822 * Settings data for a particular package we know about.
7823 */
7824 static final class PackageSetting extends PackageSettingBase {
7825 int userId;
7826 PackageParser.Package pkg;
7827 SharedUserSetting sharedUser;
7828
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007829 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007830 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7831 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7832 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007833 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007835 @Override
7836 public String toString() {
7837 return "PackageSetting{"
7838 + Integer.toHexString(System.identityHashCode(this))
7839 + " " + name + "/" + userId + "}";
7840 }
7841 }
7842
7843 /**
7844 * Settings data for a particular shared user ID we know about.
7845 */
7846 static final class SharedUserSetting extends GrantedPermissions {
7847 final String name;
7848 int userId;
7849 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7850 final PackageSignatures signatures = new PackageSignatures();
7851
7852 SharedUserSetting(String _name, int _pkgFlags) {
7853 super(_pkgFlags);
7854 name = _name;
7855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007857 @Override
7858 public String toString() {
7859 return "SharedUserSetting{"
7860 + Integer.toHexString(System.identityHashCode(this))
7861 + " " + name + "/" + userId + "}";
7862 }
7863 }
7864
7865 /**
7866 * Holds information about dynamic settings.
7867 */
7868 private static final class Settings {
7869 private final File mSettingsFilename;
7870 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007871 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 private final HashMap<String, PackageSetting> mPackages =
7873 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 // List of replaced system applications
7875 final HashMap<String, PackageSetting> mDisabledSysPackages =
7876 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007877
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007878 // These are the last platform API version we were using for
7879 // the apps installed on internal and external storage. It is
7880 // used to grant newer permissions one time during a system upgrade.
7881 int mInternalSdkPlatform;
7882 int mExternalSdkPlatform;
7883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 // The user's preferred activities associated with particular intent
7885 // filters.
7886 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7887 new IntentResolver<PreferredActivity, PreferredActivity>() {
7888 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007889 protected String packageForFilter(PreferredActivity filter) {
7890 return filter.mActivity.getPackageName();
7891 }
7892 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007893 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007894 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007895 out.print(prefix); out.print(
7896 Integer.toHexString(System.identityHashCode(filter)));
7897 out.print(' ');
7898 out.print(filter.mActivity.flattenToShortString());
7899 out.print(" match=0x");
7900 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007901 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007902 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007903 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007904 out.print(prefix); out.print(" ");
7905 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007906 }
7907 }
7908 }
7909 };
7910 private final HashMap<String, SharedUserSetting> mSharedUsers =
7911 new HashMap<String, SharedUserSetting>();
7912 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7913 private final SparseArray<Object> mOtherUserIds =
7914 new SparseArray<Object>();
7915
7916 // For reading/writing settings file.
7917 private final ArrayList<Signature> mPastSignatures =
7918 new ArrayList<Signature>();
7919
7920 // Mapping from permission names to info about them.
7921 final HashMap<String, BasePermission> mPermissions =
7922 new HashMap<String, BasePermission>();
7923
7924 // Mapping from permission tree names to info about them.
7925 final HashMap<String, BasePermission> mPermissionTrees =
7926 new HashMap<String, BasePermission>();
7927
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007928 // Packages that have been uninstalled and still need their external
7929 // storage data deleted.
7930 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7931
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007932 // Packages that have been renamed since they were first installed.
7933 // Keys are the new names of the packages, values are the original
7934 // names. The packages appear everwhere else under their original
7935 // names.
7936 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007938 private final StringBuilder mReadMessages = new StringBuilder();
7939
7940 private static final class PendingPackage extends PackageSettingBase {
7941 final int sharedId;
7942
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007943 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007944 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7945 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7946 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007947 this.sharedId = sharedId;
7948 }
7949 }
7950 private final ArrayList<PendingPackage> mPendingPackages
7951 = new ArrayList<PendingPackage>();
7952
7953 Settings() {
7954 File dataDir = Environment.getDataDirectory();
7955 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007956 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7957 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007958 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007959 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007960 FileUtils.setPermissions(systemDir.toString(),
7961 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7962 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7963 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007964 FileUtils.setPermissions(systemSecureDir.toString(),
7965 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7966 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7967 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007968 mSettingsFilename = new File(systemDir, "packages.xml");
7969 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007970 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007971 }
7972
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007973 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007974 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007975 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007977 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007978 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007979 return p;
7980 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007981
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007982 PackageSetting peekPackageLP(String name) {
7983 return mPackages.get(name);
7984 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007985 PackageSetting p = mPackages.get(name);
7986 if (p != null && p.codePath.getPath().equals(codePath)) {
7987 return p;
7988 }
7989 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007990 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007991 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007992
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007993 void setInstallStatus(String pkgName, int status) {
7994 PackageSetting p = mPackages.get(pkgName);
7995 if(p != null) {
7996 if(p.getInstallStatus() != status) {
7997 p.setInstallStatus(status);
7998 }
7999 }
8000 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008001
Jacek Surazski65e13172009-04-28 15:26:38 +02008002 void setInstallerPackageName(String pkgName,
8003 String installerPkgName) {
8004 PackageSetting p = mPackages.get(pkgName);
8005 if(p != null) {
8006 p.setInstallerPackageName(installerPkgName);
8007 }
8008 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008009
Jacek Surazski65e13172009-04-28 15:26:38 +02008010 String getInstallerPackageName(String pkgName) {
8011 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008012 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008013 }
8014
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 int getInstallStatus(String pkgName) {
8016 PackageSetting p = mPackages.get(pkgName);
8017 if(p != null) {
8018 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008020 return -1;
8021 }
8022
8023 SharedUserSetting getSharedUserLP(String name,
8024 int pkgFlags, boolean create) {
8025 SharedUserSetting s = mSharedUsers.get(name);
8026 if (s == null) {
8027 if (!create) {
8028 return null;
8029 }
8030 s = new SharedUserSetting(name, pkgFlags);
8031 if (MULTIPLE_APPLICATION_UIDS) {
8032 s.userId = newUserIdLP(s);
8033 } else {
8034 s.userId = FIRST_APPLICATION_UID;
8035 }
8036 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8037 // < 0 means we couldn't assign a userid; fall out and return
8038 // s, which is currently null
8039 if (s.userId >= 0) {
8040 mSharedUsers.put(name, s);
8041 }
8042 }
8043
8044 return s;
8045 }
8046
8047 int disableSystemPackageLP(String name) {
8048 PackageSetting p = mPackages.get(name);
8049 if(p == null) {
8050 Log.w(TAG, "Package:"+name+" is not an installed package");
8051 return -1;
8052 }
8053 PackageSetting dp = mDisabledSysPackages.get(name);
8054 // always make sure the system package code and resource paths dont change
8055 if(dp == null) {
8056 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8057 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8058 }
8059 mDisabledSysPackages.put(name, p);
8060 }
8061 return removePackageLP(name);
8062 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008064 PackageSetting enableSystemPackageLP(String name) {
8065 PackageSetting p = mDisabledSysPackages.get(name);
8066 if(p == null) {
8067 Log.w(TAG, "Package:"+name+" is not disabled");
8068 return null;
8069 }
8070 // Reset flag in ApplicationInfo object
8071 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8072 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8073 }
Kenny Root806cc132010-09-12 08:34:19 -07008074 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8075 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008076 mDisabledSysPackages.remove(name);
8077 return ret;
8078 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008079
Kenny Root806cc132010-09-12 08:34:19 -07008080 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8081 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 PackageSetting p = mPackages.get(name);
8083 if (p != null) {
8084 if (p.userId == uid) {
8085 return p;
8086 }
8087 reportSettingsProblem(Log.ERROR,
8088 "Adding duplicate package, keeping first: " + name);
8089 return null;
8090 }
Kenny Root806cc132010-09-12 08:34:19 -07008091 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8092 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008093 p.userId = uid;
8094 if (addUserIdLP(uid, p, name)) {
8095 mPackages.put(name, p);
8096 return p;
8097 }
8098 return null;
8099 }
8100
8101 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8102 SharedUserSetting s = mSharedUsers.get(name);
8103 if (s != null) {
8104 if (s.userId == uid) {
8105 return s;
8106 }
8107 reportSettingsProblem(Log.ERROR,
8108 "Adding duplicate shared user, keeping first: " + name);
8109 return null;
8110 }
8111 s = new SharedUserSetting(name, pkgFlags);
8112 s.userId = uid;
8113 if (addUserIdLP(uid, s, name)) {
8114 mSharedUsers.put(name, s);
8115 return s;
8116 }
8117 return null;
8118 }
8119
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008120 // Transfer ownership of permissions from one package to another.
8121 private void transferPermissions(String origPkg, String newPkg) {
8122 // Transfer ownership of permissions to the new package.
8123 for (int i=0; i<2; i++) {
8124 HashMap<String, BasePermission> permissions =
8125 i == 0 ? mPermissionTrees : mPermissions;
8126 for (BasePermission bp : permissions.values()) {
8127 if (origPkg.equals(bp.sourcePackage)) {
8128 if (DEBUG_UPGRADE) Log.v(TAG,
8129 "Moving permission " + bp.name
8130 + " from pkg " + bp.sourcePackage
8131 + " to " + newPkg);
8132 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008133 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008134 bp.perm = null;
8135 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008136 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008137 }
8138 bp.uid = 0;
8139 bp.gids = null;
8140 }
8141 }
8142 }
8143 }
8144
8145 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008146 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008147 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008148 PackageSetting p = mPackages.get(name);
8149 if (p != null) {
8150 if (!p.codePath.equals(codePath)) {
8151 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008152 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008153 // This is an updated system app with versions in both system
8154 // and data partition. Just let the most recent version
8155 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008156 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008157 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008158 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008159 // Just a change in the code path is not an issue, but
8160 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008161 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008162 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008163 /*
8164 * Since we've changed paths, we need to prefer the new
8165 * native library path over the one stored in the
8166 * package settings since we might have moved from
8167 * internal to external storage or vice versa.
8168 */
8169 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008171 }
8172 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008173 reportSettingsProblem(Log.WARN,
8174 "Package " + name + " shared user changed from "
8175 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8176 + " to "
8177 + (sharedUser != null ? sharedUser.name : "<nothing>")
8178 + "; replacing with new");
8179 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008180 } else {
8181 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8182 // If what we are scanning is a system package, then
8183 // make it so, regardless of whether it was previously
8184 // installed only in the data partition.
8185 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008187 }
8188 }
8189 if (p == null) {
8190 // Create a new PackageSettings entry. this can end up here because
8191 // of code path mismatch or user id mismatch of an updated system partition
8192 if (!create) {
8193 return null;
8194 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008195 if (origPackage != null) {
8196 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008197 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8198 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008199 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8200 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008201 // Note that we will retain the new package's signature so
8202 // that we can keep its data.
8203 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008204 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008205 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008206 p.sharedUser = origPackage.sharedUser;
8207 p.userId = origPackage.userId;
8208 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008209 mRenamedPackages.put(name, origPackage.name);
8210 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008211 // Update new package state.
8212 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008213 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008214 p = new PackageSetting(name, realName, codePath, resourcePath,
8215 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008216 p.setTimeStamp(codePath.lastModified());
8217 p.sharedUser = sharedUser;
8218 if (sharedUser != null) {
8219 p.userId = sharedUser.userId;
8220 } else if (MULTIPLE_APPLICATION_UIDS) {
8221 // Clone the setting here for disabled system packages
8222 PackageSetting dis = mDisabledSysPackages.get(name);
8223 if (dis != null) {
8224 // For disabled packages a new setting is created
8225 // from the existing user id. This still has to be
8226 // added to list of user id's
8227 // Copy signatures from previous setting
8228 if (dis.signatures.mSignatures != null) {
8229 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8230 }
8231 p.userId = dis.userId;
8232 // Clone permissions
8233 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008234 // Clone component info
8235 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8236 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8237 // Add new setting to list of user ids
8238 addUserIdLP(p.userId, p, name);
8239 } else {
8240 // Assign new user id
8241 p.userId = newUserIdLP(p);
8242 }
8243 } else {
8244 p.userId = FIRST_APPLICATION_UID;
8245 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008246 }
8247 if (p.userId < 0) {
8248 reportSettingsProblem(Log.WARN,
8249 "Package " + name + " could not be assigned a valid uid");
8250 return null;
8251 }
8252 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008253 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008254 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008255 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008256 }
8257 }
8258 return p;
8259 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008260
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008261 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008262 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008263 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008264 final String codePath = pkg.applicationInfo.sourceDir;
8265 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008266 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008267 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008268 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008269 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008270 p.codePath = new File(codePath);
8271 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008272 }
8273 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008274 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008275 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008276 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008277 p.resourcePath = new File(resourcePath);
8278 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008279 }
Kenny Root85387d72010-08-26 10:13:11 -07008280 // Update the native library path if needed
8281 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8282 if (nativeLibraryPath != null
8283 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8284 p.nativeLibraryPathString = nativeLibraryPath;
8285 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008286 // Update version code if needed
8287 if (pkg.mVersionCode != p.versionCode) {
8288 p.versionCode = pkg.mVersionCode;
8289 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008290 // Update signatures if needed.
8291 if (p.signatures.mSignatures == null) {
8292 p.signatures.assignSignatures(pkg.mSignatures);
8293 }
8294 // If this app defines a shared user id initialize
8295 // the shared user signatures as well.
8296 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8297 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8298 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008299 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8300 }
8301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 // Utility method that adds a PackageSetting to mPackages and
8303 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008304 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008305 SharedUserSetting sharedUser) {
8306 mPackages.put(name, p);
8307 if (sharedUser != null) {
8308 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8309 reportSettingsProblem(Log.ERROR,
8310 "Package " + p.name + " was user "
8311 + p.sharedUser + " but is now " + sharedUser
8312 + "; I am not changing its files so it will probably fail!");
8313 p.sharedUser.packages.remove(p);
8314 } else if (p.userId != sharedUser.userId) {
8315 reportSettingsProblem(Log.ERROR,
8316 "Package " + p.name + " was user id " + p.userId
8317 + " but is now user " + sharedUser
8318 + " with id " + sharedUser.userId
8319 + "; I am not changing its files so it will probably fail!");
8320 }
8321
8322 sharedUser.packages.add(p);
8323 p.sharedUser = sharedUser;
8324 p.userId = sharedUser.userId;
8325 }
8326 }
8327
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008328 /*
8329 * Update the shared user setting when a package using
8330 * specifying the shared user id is removed. The gids
8331 * associated with each permission of the deleted package
8332 * are removed from the shared user's gid list only if its
8333 * not in use by other permissions of packages in the
8334 * shared user setting.
8335 */
8336 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008337 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008338 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008339 return;
8340 }
8341 // No sharedUserId
8342 if (deletedPs.sharedUser == null) {
8343 return;
8344 }
8345 SharedUserSetting sus = deletedPs.sharedUser;
8346 // Update permissions
8347 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8348 boolean used = false;
8349 if (!sus.grantedPermissions.contains (eachPerm)) {
8350 continue;
8351 }
8352 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008353 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008354 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008355 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008356 used = true;
8357 break;
8358 }
8359 }
8360 if (!used) {
8361 // can safely delete this permission from list
8362 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008363 }
8364 }
8365 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008366 int newGids[] = globalGids;
8367 for (String eachPerm : sus.grantedPermissions) {
8368 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008369 if (bp != null) {
8370 newGids = appendInts(newGids, bp.gids);
8371 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008372 }
8373 sus.gids = newGids;
8374 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008376 private int removePackageLP(String name) {
8377 PackageSetting p = mPackages.get(name);
8378 if (p != null) {
8379 mPackages.remove(name);
8380 if (p.sharedUser != null) {
8381 p.sharedUser.packages.remove(p);
8382 if (p.sharedUser.packages.size() == 0) {
8383 mSharedUsers.remove(p.sharedUser.name);
8384 removeUserIdLP(p.sharedUser.userId);
8385 return p.sharedUser.userId;
8386 }
8387 } else {
8388 removeUserIdLP(p.userId);
8389 return p.userId;
8390 }
8391 }
8392 return -1;
8393 }
8394
8395 private boolean addUserIdLP(int uid, Object obj, Object name) {
8396 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8397 return false;
8398 }
8399
8400 if (uid >= FIRST_APPLICATION_UID) {
8401 int N = mUserIds.size();
8402 final int index = uid - FIRST_APPLICATION_UID;
8403 while (index >= N) {
8404 mUserIds.add(null);
8405 N++;
8406 }
8407 if (mUserIds.get(index) != null) {
8408 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008409 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008410 + " name=" + name);
8411 return false;
8412 }
8413 mUserIds.set(index, obj);
8414 } else {
8415 if (mOtherUserIds.get(uid) != null) {
8416 reportSettingsProblem(Log.ERROR,
8417 "Adding duplicate shared id: " + uid
8418 + " name=" + name);
8419 return false;
8420 }
8421 mOtherUserIds.put(uid, obj);
8422 }
8423 return true;
8424 }
8425
8426 public Object getUserIdLP(int uid) {
8427 if (uid >= FIRST_APPLICATION_UID) {
8428 int N = mUserIds.size();
8429 final int index = uid - FIRST_APPLICATION_UID;
8430 return index < N ? mUserIds.get(index) : null;
8431 } else {
8432 return mOtherUserIds.get(uid);
8433 }
8434 }
8435
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008436 private Set<String> findPackagesWithFlag(int flag) {
8437 Set<String> ret = new HashSet<String>();
8438 for (PackageSetting ps : mPackages.values()) {
8439 // Has to match atleast all the flag bits set on flag
8440 if ((ps.pkgFlags & flag) == flag) {
8441 ret.add(ps.name);
8442 }
8443 }
8444 return ret;
8445 }
8446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008447 private void removeUserIdLP(int uid) {
8448 if (uid >= FIRST_APPLICATION_UID) {
8449 int N = mUserIds.size();
8450 final int index = uid - FIRST_APPLICATION_UID;
8451 if (index < N) mUserIds.set(index, null);
8452 } else {
8453 mOtherUserIds.remove(uid);
8454 }
8455 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008457 void writeLP() {
8458 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8459
8460 // Keep the old settings around until we know the new ones have
8461 // been successfully written.
8462 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008463 // Presence of backup settings file indicates that we failed
8464 // to persist settings earlier. So preserve the older
8465 // backup for future reference since the current settings
8466 // might have been corrupted.
8467 if (!mBackupSettingsFilename.exists()) {
8468 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008469 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008470 return;
8471 }
8472 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008473 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008474 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476 }
8477
8478 mPastSignatures.clear();
8479
8480 try {
Kenny Root9f306d72010-09-26 11:19:47 -07008481 BufferedOutputStream str = new BufferedOutputStream(new FileOutputStream(
8482 mSettingsFilename));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008483
8484 //XmlSerializer serializer = XmlUtils.serializerInstance();
8485 XmlSerializer serializer = new FastXmlSerializer();
8486 serializer.setOutput(str, "utf-8");
8487 serializer.startDocument(null, true);
8488 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8489
8490 serializer.startTag(null, "packages");
8491
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008492 serializer.startTag(null, "last-platform-version");
8493 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8494 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8495 serializer.endTag(null, "last-platform-version");
8496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008497 serializer.startTag(null, "permission-trees");
8498 for (BasePermission bp : mPermissionTrees.values()) {
8499 writePermission(serializer, bp);
8500 }
8501 serializer.endTag(null, "permission-trees");
8502
8503 serializer.startTag(null, "permissions");
8504 for (BasePermission bp : mPermissions.values()) {
8505 writePermission(serializer, bp);
8506 }
8507 serializer.endTag(null, "permissions");
8508
8509 for (PackageSetting pkg : mPackages.values()) {
8510 writePackage(serializer, pkg);
8511 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008513 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8514 writeDisabledSysPackage(serializer, pkg);
8515 }
8516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 serializer.startTag(null, "preferred-activities");
8518 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8519 serializer.startTag(null, "item");
8520 pa.writeToXml(serializer);
8521 serializer.endTag(null, "item");
8522 }
8523 serializer.endTag(null, "preferred-activities");
8524
8525 for (SharedUserSetting usr : mSharedUsers.values()) {
8526 serializer.startTag(null, "shared-user");
8527 serializer.attribute(null, "name", usr.name);
8528 serializer.attribute(null, "userId",
8529 Integer.toString(usr.userId));
8530 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8531 serializer.startTag(null, "perms");
8532 for (String name : usr.grantedPermissions) {
8533 serializer.startTag(null, "item");
8534 serializer.attribute(null, "name", name);
8535 serializer.endTag(null, "item");
8536 }
8537 serializer.endTag(null, "perms");
8538 serializer.endTag(null, "shared-user");
8539 }
8540
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008541 if (mPackagesToBeCleaned.size() > 0) {
8542 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8543 serializer.startTag(null, "cleaning-package");
8544 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8545 serializer.endTag(null, "cleaning-package");
8546 }
8547 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008548
8549 if (mRenamedPackages.size() > 0) {
8550 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8551 serializer.startTag(null, "renamed-package");
8552 serializer.attribute(null, "new", e.getKey());
8553 serializer.attribute(null, "old", e.getValue());
8554 serializer.endTag(null, "renamed-package");
8555 }
8556 }
8557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008558 serializer.endTag(null, "packages");
8559
8560 serializer.endDocument();
8561
8562 str.flush();
8563 str.close();
8564
8565 // New settings successfully written, old ones are no longer
8566 // needed.
8567 mBackupSettingsFilename.delete();
8568 FileUtils.setPermissions(mSettingsFilename.toString(),
8569 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8570 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8571 |FileUtils.S_IROTH,
8572 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008573
8574 // Write package list file now, use a JournaledFile.
8575 //
8576 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8577 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8578
Kenny Root9f306d72010-09-26 11:19:47 -07008579 str = new BufferedOutputStream(new FileOutputStream(journal.chooseForWrite()));
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008580 try {
8581 StringBuilder sb = new StringBuilder();
8582 for (PackageSetting pkg : mPackages.values()) {
8583 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008584 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008585 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8586
8587 // Avoid any application that has a space in its path
8588 // or that is handled by the system.
8589 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8590 continue;
8591
8592 // we store on each line the following information for now:
8593 //
8594 // pkgName - package name
8595 // userId - application-specific user id
8596 // debugFlag - 0 or 1 if the package is debuggable.
8597 // dataPath - path to package's data path
8598 //
8599 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8600 //
8601 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8602 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8603 // system/core/run-as/run-as.c
8604 //
8605 sb.setLength(0);
8606 sb.append(ai.packageName);
8607 sb.append(" ");
8608 sb.append((int)ai.uid);
8609 sb.append(isDebug ? " 1 " : " 0 ");
8610 sb.append(dataPath);
8611 sb.append("\n");
8612 str.write(sb.toString().getBytes());
8613 }
8614 str.flush();
8615 str.close();
8616 journal.commit();
8617 }
8618 catch (Exception e) {
8619 journal.rollback();
8620 }
8621
8622 FileUtils.setPermissions(mPackageListFilename.toString(),
8623 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8624 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8625 |FileUtils.S_IROTH,
8626 -1, -1);
8627
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008628 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008629
8630 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008631 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 -08008632 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008633 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 -08008634 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008635 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008636 if (mSettingsFilename.exists()) {
8637 if (!mSettingsFilename.delete()) {
8638 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8639 }
8640 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 //Debug.stopMethodTracing();
8642 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008643
8644 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008645 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 serializer.startTag(null, "updated-package");
8647 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008648 if (pkg.realName != null) {
8649 serializer.attribute(null, "realName", pkg.realName);
8650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008651 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008652 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8653 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8654 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008655 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8657 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8658 }
Kenny Root85387d72010-08-26 10:13:11 -07008659 if (pkg.nativeLibraryPathString != null) {
8660 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008662 if (pkg.sharedUser == null) {
8663 serializer.attribute(null, "userId",
8664 Integer.toString(pkg.userId));
8665 } else {
8666 serializer.attribute(null, "sharedUserId",
8667 Integer.toString(pkg.userId));
8668 }
8669 serializer.startTag(null, "perms");
8670 if (pkg.sharedUser == null) {
8671 // If this is a shared user, the permissions will
8672 // be written there. We still need to write an
8673 // empty permissions list so permissionsFixed will
8674 // be set.
8675 for (final String name : pkg.grantedPermissions) {
8676 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008677 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008678 // We only need to write signature or system permissions but this wont
8679 // match the semantics of grantedPermissions. So write all permissions.
8680 serializer.startTag(null, "item");
8681 serializer.attribute(null, "name", name);
8682 serializer.endTag(null, "item");
8683 }
8684 }
8685 }
8686 serializer.endTag(null, "perms");
8687 serializer.endTag(null, "updated-package");
8688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008689
8690 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008691 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008692 serializer.startTag(null, "package");
8693 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008694 if (pkg.realName != null) {
8695 serializer.attribute(null, "realName", pkg.realName);
8696 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008697 serializer.attribute(null, "codePath", pkg.codePathString);
8698 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8699 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8700 }
Kenny Root85387d72010-08-26 10:13:11 -07008701 if (pkg.nativeLibraryPathString != null) {
8702 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8703 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008704 serializer.attribute(null, "flags",
8705 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008706 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8707 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8708 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008709 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008710 if (pkg.sharedUser == null) {
8711 serializer.attribute(null, "userId",
8712 Integer.toString(pkg.userId));
8713 } else {
8714 serializer.attribute(null, "sharedUserId",
8715 Integer.toString(pkg.userId));
8716 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008717 if (pkg.uidError) {
8718 serializer.attribute(null, "uidError", "true");
8719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008720 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8721 serializer.attribute(null, "enabled",
8722 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8723 ? "true" : "false");
8724 }
8725 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8726 serializer.attribute(null, "installStatus", "false");
8727 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008728 if (pkg.installerPackageName != null) {
8729 serializer.attribute(null, "installer", pkg.installerPackageName);
8730 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008731 if (pkg.obbPathString != null) {
8732 serializer.attribute(null, "obbPath", pkg.obbPathString);
8733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008734 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8735 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8736 serializer.startTag(null, "perms");
8737 if (pkg.sharedUser == null) {
8738 // If this is a shared user, the permissions will
8739 // be written there. We still need to write an
8740 // empty permissions list so permissionsFixed will
8741 // be set.
8742 for (final String name : pkg.grantedPermissions) {
8743 serializer.startTag(null, "item");
8744 serializer.attribute(null, "name", name);
8745 serializer.endTag(null, "item");
8746 }
8747 }
8748 serializer.endTag(null, "perms");
8749 }
8750 if (pkg.disabledComponents.size() > 0) {
8751 serializer.startTag(null, "disabled-components");
8752 for (final String name : pkg.disabledComponents) {
8753 serializer.startTag(null, "item");
8754 serializer.attribute(null, "name", name);
8755 serializer.endTag(null, "item");
8756 }
8757 serializer.endTag(null, "disabled-components");
8758 }
8759 if (pkg.enabledComponents.size() > 0) {
8760 serializer.startTag(null, "enabled-components");
8761 for (final String name : pkg.enabledComponents) {
8762 serializer.startTag(null, "item");
8763 serializer.attribute(null, "name", name);
8764 serializer.endTag(null, "item");
8765 }
8766 serializer.endTag(null, "enabled-components");
8767 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008769 serializer.endTag(null, "package");
8770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008771
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772 void writePermission(XmlSerializer serializer, BasePermission bp)
8773 throws XmlPullParserException, java.io.IOException {
8774 if (bp.type != BasePermission.TYPE_BUILTIN
8775 && bp.sourcePackage != null) {
8776 serializer.startTag(null, "item");
8777 serializer.attribute(null, "name", bp.name);
8778 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008779 if (bp.protectionLevel !=
8780 PermissionInfo.PROTECTION_NORMAL) {
8781 serializer.attribute(null, "protection",
8782 Integer.toString(bp.protectionLevel));
8783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008784 if (DEBUG_SETTINGS) Log.v(TAG,
8785 "Writing perm: name=" + bp.name + " type=" + bp.type);
8786 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8787 PermissionInfo pi = bp.perm != null ? bp.perm.info
8788 : bp.pendingInfo;
8789 if (pi != null) {
8790 serializer.attribute(null, "type", "dynamic");
8791 if (pi.icon != 0) {
8792 serializer.attribute(null, "icon",
8793 Integer.toString(pi.icon));
8794 }
8795 if (pi.nonLocalizedLabel != null) {
8796 serializer.attribute(null, "label",
8797 pi.nonLocalizedLabel.toString());
8798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 }
8800 }
8801 serializer.endTag(null, "item");
8802 }
8803 }
8804
8805 String getReadMessagesLP() {
8806 return mReadMessages.toString();
8807 }
8808
Oscar Montemayora8529f62009-11-18 10:14:20 -08008809 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008810 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8811 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008812 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008813 while(its.hasNext()) {
8814 String key = its.next();
8815 PackageSetting ps = mPackages.get(key);
8816 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008817 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008818 }
8819 }
8820 return ret;
8821 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008823 boolean readLP() {
8824 FileInputStream str = null;
8825 if (mBackupSettingsFilename.exists()) {
8826 try {
8827 str = new FileInputStream(mBackupSettingsFilename);
8828 mReadMessages.append("Reading from backup settings file\n");
8829 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008830 if (mSettingsFilename.exists()) {
8831 // If both the backup and settings file exist, we
8832 // ignore the settings since it might have been
8833 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008834 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008835 mSettingsFilename.delete();
8836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 } catch (java.io.IOException e) {
8838 // We'll try for the normal settings file.
8839 }
8840 }
8841
8842 mPastSignatures.clear();
8843
8844 try {
8845 if (str == null) {
8846 if (!mSettingsFilename.exists()) {
8847 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008848 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008849 return false;
8850 }
8851 str = new FileInputStream(mSettingsFilename);
8852 }
8853 XmlPullParser parser = Xml.newPullParser();
8854 parser.setInput(str, null);
8855
8856 int type;
8857 while ((type=parser.next()) != XmlPullParser.START_TAG
8858 && type != XmlPullParser.END_DOCUMENT) {
8859 ;
8860 }
8861
8862 if (type != XmlPullParser.START_TAG) {
8863 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008864 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008865 return false;
8866 }
8867
8868 int outerDepth = parser.getDepth();
8869 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8870 && (type != XmlPullParser.END_TAG
8871 || parser.getDepth() > outerDepth)) {
8872 if (type == XmlPullParser.END_TAG
8873 || type == XmlPullParser.TEXT) {
8874 continue;
8875 }
8876
8877 String tagName = parser.getName();
8878 if (tagName.equals("package")) {
8879 readPackageLP(parser);
8880 } else if (tagName.equals("permissions")) {
8881 readPermissionsLP(mPermissions, parser);
8882 } else if (tagName.equals("permission-trees")) {
8883 readPermissionsLP(mPermissionTrees, parser);
8884 } else if (tagName.equals("shared-user")) {
8885 readSharedUserLP(parser);
8886 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008887 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888 } else if (tagName.equals("preferred-activities")) {
8889 readPreferredActivitiesLP(parser);
8890 } else if(tagName.equals("updated-package")) {
8891 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008892 } else if (tagName.equals("cleaning-package")) {
8893 String name = parser.getAttributeValue(null, "name");
8894 if (name != null) {
8895 mPackagesToBeCleaned.add(name);
8896 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008897 } else if (tagName.equals("renamed-package")) {
8898 String nname = parser.getAttributeValue(null, "new");
8899 String oname = parser.getAttributeValue(null, "old");
8900 if (nname != null && oname != null) {
8901 mRenamedPackages.put(nname, oname);
8902 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008903 } else if (tagName.equals("last-platform-version")) {
8904 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8905 try {
8906 String internal = parser.getAttributeValue(null, "internal");
8907 if (internal != null) {
8908 mInternalSdkPlatform = Integer.parseInt(internal);
8909 }
8910 String external = parser.getAttributeValue(null, "external");
8911 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008912 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008913 }
8914 } catch (NumberFormatException e) {
8915 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008916 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008917 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008918 + parser.getName());
8919 XmlUtils.skipCurrentTag(parser);
8920 }
8921 }
8922
8923 str.close();
8924
8925 } catch(XmlPullParserException e) {
8926 mReadMessages.append("Error reading: " + e.toString());
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 Hackborna2fd9d12010-03-11 23:40:24 -08008931 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008932
8933 }
8934
8935 int N = mPendingPackages.size();
8936 for (int i=0; i<N; i++) {
8937 final PendingPackage pp = mPendingPackages.get(i);
8938 Object idObj = getUserIdLP(pp.sharedId);
8939 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008940 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008941 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8942 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008944 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 + pp.name);
8946 continue;
8947 }
8948 p.copyFrom(pp);
8949 } else if (idObj != null) {
8950 String msg = "Bad package setting: package " + pp.name
8951 + " has shared uid " + pp.sharedId
8952 + " that is not a shared uid\n";
8953 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008954 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 } else {
8956 String msg = "Bad package setting: package " + pp.name
8957 + " has shared uid " + pp.sharedId
8958 + " that is not defined\n";
8959 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008960 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 }
8962 }
8963 mPendingPackages.clear();
8964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 mReadMessages.append("Read completed successfully: "
8966 + mPackages.size() + " packages, "
8967 + mSharedUsers.size() + " shared uids\n");
8968
8969 return true;
8970 }
8971
8972 private int readInt(XmlPullParser parser, String ns, String name,
8973 int defValue) {
8974 String v = parser.getAttributeValue(ns, name);
8975 try {
8976 if (v == null) {
8977 return defValue;
8978 }
8979 return Integer.parseInt(v);
8980 } catch (NumberFormatException e) {
8981 reportSettingsProblem(Log.WARN,
8982 "Error in package manager settings: attribute " +
8983 name + " has bad integer value " + v + " at "
8984 + parser.getPositionDescription());
8985 }
8986 return defValue;
8987 }
8988
8989 private void readPermissionsLP(HashMap<String, BasePermission> out,
8990 XmlPullParser parser)
8991 throws IOException, XmlPullParserException {
8992 int outerDepth = parser.getDepth();
8993 int type;
8994 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8995 && (type != XmlPullParser.END_TAG
8996 || parser.getDepth() > outerDepth)) {
8997 if (type == XmlPullParser.END_TAG
8998 || type == XmlPullParser.TEXT) {
8999 continue;
9000 }
9001
9002 String tagName = parser.getName();
9003 if (tagName.equals("item")) {
9004 String name = parser.getAttributeValue(null, "name");
9005 String sourcePackage = parser.getAttributeValue(null, "package");
9006 String ptype = parser.getAttributeValue(null, "type");
9007 if (name != null && sourcePackage != null) {
9008 boolean dynamic = "dynamic".equals(ptype);
9009 BasePermission bp = new BasePermission(name, sourcePackage,
9010 dynamic
9011 ? BasePermission.TYPE_DYNAMIC
9012 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009013 bp.protectionLevel = readInt(parser, null, "protection",
9014 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009015 if (dynamic) {
9016 PermissionInfo pi = new PermissionInfo();
9017 pi.packageName = sourcePackage.intern();
9018 pi.name = name.intern();
9019 pi.icon = readInt(parser, null, "icon", 0);
9020 pi.nonLocalizedLabel = parser.getAttributeValue(
9021 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009022 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009023 bp.pendingInfo = pi;
9024 }
9025 out.put(bp.name, bp);
9026 } else {
9027 reportSettingsProblem(Log.WARN,
9028 "Error in package manager settings: permissions has"
9029 + " no name at " + parser.getPositionDescription());
9030 }
9031 } else {
9032 reportSettingsProblem(Log.WARN,
9033 "Unknown element reading permissions: "
9034 + parser.getName() + " at "
9035 + parser.getPositionDescription());
9036 }
9037 XmlUtils.skipCurrentTag(parser);
9038 }
9039 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009041 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009042 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009043 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009044 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045 String codePathStr = parser.getAttributeValue(null, "codePath");
9046 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009047 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009048 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009049 resourcePathStr = codePathStr;
9050 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009051 String version = parser.getAttributeValue(null, "version");
9052 int versionCode = 0;
9053 if (version != null) {
9054 try {
9055 versionCode = Integer.parseInt(version);
9056 } catch (NumberFormatException e) {
9057 }
9058 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009060 int pkgFlags = 0;
9061 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009062 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9063 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009064 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065 if (timeStampStr != null) {
9066 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009067 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009068 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009069 } catch (NumberFormatException e) {
9070 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009071 } else {
9072 timeStampStr = parser.getAttributeValue(null, "ts");
9073 if (timeStampStr != null) {
9074 try {
9075 long timeStamp = Long.parseLong(timeStampStr);
9076 ps.setTimeStamp(timeStamp);
9077 } catch (NumberFormatException e) {
9078 }
9079 }
9080 }
9081 timeStampStr = parser.getAttributeValue(null, "it");
9082 if (timeStampStr != null) {
9083 try {
9084 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9085 } catch (NumberFormatException e) {
9086 }
9087 }
9088 timeStampStr = parser.getAttributeValue(null, "ut");
9089 if (timeStampStr != null) {
9090 try {
9091 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9092 } catch (NumberFormatException e) {
9093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009094 }
9095 String idStr = parser.getAttributeValue(null, "userId");
9096 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9097 if(ps.userId <= 0) {
9098 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9099 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9100 }
9101 int outerDepth = parser.getDepth();
9102 int type;
9103 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9104 && (type != XmlPullParser.END_TAG
9105 || parser.getDepth() > outerDepth)) {
9106 if (type == XmlPullParser.END_TAG
9107 || type == XmlPullParser.TEXT) {
9108 continue;
9109 }
9110
9111 String tagName = parser.getName();
9112 if (tagName.equals("perms")) {
9113 readGrantedPermissionsLP(parser,
9114 ps.grantedPermissions);
9115 } else {
9116 reportSettingsProblem(Log.WARN,
9117 "Unknown element under <updated-package>: "
9118 + parser.getName());
9119 XmlUtils.skipCurrentTag(parser);
9120 }
9121 }
9122 mDisabledSysPackages.put(name, ps);
9123 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009125 private void readPackageLP(XmlPullParser parser)
9126 throws XmlPullParserException, IOException {
9127 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009128 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009129 String idStr = null;
9130 String sharedIdStr = null;
9131 String codePathStr = null;
9132 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009133 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009134 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009135 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009136 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009137 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009138 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009139 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009140 long firstInstallTime = 0;
9141 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009143 String version = null;
9144 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009145 try {
9146 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009147 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009148 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009149 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009150 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9151 codePathStr = parser.getAttributeValue(null, "codePath");
9152 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009153 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009154 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009155 version = parser.getAttributeValue(null, "version");
9156 if (version != null) {
9157 try {
9158 versionCode = Integer.parseInt(version);
9159 } catch (NumberFormatException e) {
9160 }
9161 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009162 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009163
9164 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009165 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009166 try {
9167 pkgFlags = Integer.parseInt(systemStr);
9168 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009169 }
9170 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009171 // For backward compatibility
9172 systemStr = parser.getAttributeValue(null, "system");
9173 if (systemStr != null) {
9174 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9175 } else {
9176 // Old settings that don't specify system... just treat
9177 // them as system, good enough.
9178 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009180 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009181 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009182 if (timeStampStr != null) {
9183 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009184 timeStamp = Long.parseLong(timeStampStr, 16);
9185 } catch (NumberFormatException e) {
9186 }
9187 } else {
9188 timeStampStr = parser.getAttributeValue(null, "ts");
9189 if (timeStampStr != null) {
9190 try {
9191 timeStamp = Long.parseLong(timeStampStr);
9192 } catch (NumberFormatException e) {
9193 }
9194 }
9195 }
9196 timeStampStr = parser.getAttributeValue(null, "it");
9197 if (timeStampStr != null) {
9198 try {
9199 firstInstallTime = Long.parseLong(timeStampStr, 16);
9200 } catch (NumberFormatException e) {
9201 }
9202 }
9203 timeStampStr = parser.getAttributeValue(null, "ut");
9204 if (timeStampStr != null) {
9205 try {
9206 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009207 } catch (NumberFormatException e) {
9208 }
9209 }
9210 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9211 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9212 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9213 if (resourcePathStr == null) {
9214 resourcePathStr = codePathStr;
9215 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009216 if (realName != null) {
9217 realName = realName.intern();
9218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009219 if (name == null) {
9220 reportSettingsProblem(Log.WARN,
9221 "Error in package manager settings: <package> has no name at "
9222 + parser.getPositionDescription());
9223 } else if (codePathStr == null) {
9224 reportSettingsProblem(Log.WARN,
9225 "Error in package manager settings: <package> has no codePath at "
9226 + parser.getPositionDescription());
9227 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009228 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9229 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9230 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009231 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9232 + ": userId=" + userId + " pkg=" + packageSetting);
9233 if (packageSetting == null) {
9234 reportSettingsProblem(Log.ERROR,
9235 "Failure adding uid " + userId
9236 + " while parsing settings at "
9237 + parser.getPositionDescription());
9238 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009239 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009240 packageSetting.firstInstallTime = firstInstallTime;
9241 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009242 }
9243 } else if (sharedIdStr != null) {
9244 userId = sharedIdStr != null
9245 ? Integer.parseInt(sharedIdStr) : 0;
9246 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009247 packageSetting = new PendingPackage(name.intern(), realName,
9248 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009249 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009250 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009251 packageSetting.firstInstallTime = firstInstallTime;
9252 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009253 mPendingPackages.add((PendingPackage) packageSetting);
9254 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9255 + ": sharedUserId=" + userId + " pkg="
9256 + packageSetting);
9257 } else {
9258 reportSettingsProblem(Log.WARN,
9259 "Error in package manager settings: package "
9260 + name + " has bad sharedId " + sharedIdStr
9261 + " at " + parser.getPositionDescription());
9262 }
9263 } else {
9264 reportSettingsProblem(Log.WARN,
9265 "Error in package manager settings: package "
9266 + name + " has bad userId " + idStr + " at "
9267 + parser.getPositionDescription());
9268 }
9269 } catch (NumberFormatException e) {
9270 reportSettingsProblem(Log.WARN,
9271 "Error in package manager settings: package "
9272 + name + " has bad userId " + idStr + " at "
9273 + parser.getPositionDescription());
9274 }
9275 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009276 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009277 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009278 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009279 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009280 final String enabledStr = parser.getAttributeValue(null, "enabled");
9281 if (enabledStr != null) {
9282 if (enabledStr.equalsIgnoreCase("true")) {
9283 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9284 } else if (enabledStr.equalsIgnoreCase("false")) {
9285 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9286 } else if (enabledStr.equalsIgnoreCase("default")) {
9287 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9288 } else {
9289 reportSettingsProblem(Log.WARN,
9290 "Error in package manager settings: package "
9291 + name + " has bad enabled value: " + idStr
9292 + " at " + parser.getPositionDescription());
9293 }
9294 } else {
9295 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9296 }
9297 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9298 if (installStatusStr != null) {
9299 if (installStatusStr.equalsIgnoreCase("false")) {
9300 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9301 } else {
9302 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9303 }
9304 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009306 int outerDepth = parser.getDepth();
9307 int type;
9308 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9309 && (type != XmlPullParser.END_TAG
9310 || parser.getDepth() > outerDepth)) {
9311 if (type == XmlPullParser.END_TAG
9312 || type == XmlPullParser.TEXT) {
9313 continue;
9314 }
9315
9316 String tagName = parser.getName();
9317 if (tagName.equals("disabled-components")) {
9318 readDisabledComponentsLP(packageSetting, parser);
9319 } else if (tagName.equals("enabled-components")) {
9320 readEnabledComponentsLP(packageSetting, parser);
9321 } else if (tagName.equals("sigs")) {
9322 packageSetting.signatures.readXml(parser, mPastSignatures);
9323 } else if (tagName.equals("perms")) {
9324 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009325 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009326 packageSetting.permissionsFixed = true;
9327 } else {
9328 reportSettingsProblem(Log.WARN,
9329 "Unknown element under <package>: "
9330 + parser.getName());
9331 XmlUtils.skipCurrentTag(parser);
9332 }
9333 }
9334 } else {
9335 XmlUtils.skipCurrentTag(parser);
9336 }
9337 }
9338
9339 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9340 XmlPullParser parser)
9341 throws IOException, XmlPullParserException {
9342 int outerDepth = parser.getDepth();
9343 int type;
9344 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9345 && (type != XmlPullParser.END_TAG
9346 || parser.getDepth() > outerDepth)) {
9347 if (type == XmlPullParser.END_TAG
9348 || type == XmlPullParser.TEXT) {
9349 continue;
9350 }
9351
9352 String tagName = parser.getName();
9353 if (tagName.equals("item")) {
9354 String name = parser.getAttributeValue(null, "name");
9355 if (name != null) {
9356 packageSetting.disabledComponents.add(name.intern());
9357 } else {
9358 reportSettingsProblem(Log.WARN,
9359 "Error in package manager settings: <disabled-components> has"
9360 + " no name at " + parser.getPositionDescription());
9361 }
9362 } else {
9363 reportSettingsProblem(Log.WARN,
9364 "Unknown element under <disabled-components>: "
9365 + parser.getName());
9366 }
9367 XmlUtils.skipCurrentTag(parser);
9368 }
9369 }
9370
9371 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9372 XmlPullParser parser)
9373 throws IOException, XmlPullParserException {
9374 int outerDepth = parser.getDepth();
9375 int type;
9376 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9377 && (type != XmlPullParser.END_TAG
9378 || parser.getDepth() > outerDepth)) {
9379 if (type == XmlPullParser.END_TAG
9380 || type == XmlPullParser.TEXT) {
9381 continue;
9382 }
9383
9384 String tagName = parser.getName();
9385 if (tagName.equals("item")) {
9386 String name = parser.getAttributeValue(null, "name");
9387 if (name != null) {
9388 packageSetting.enabledComponents.add(name.intern());
9389 } else {
9390 reportSettingsProblem(Log.WARN,
9391 "Error in package manager settings: <enabled-components> has"
9392 + " no name at " + parser.getPositionDescription());
9393 }
9394 } else {
9395 reportSettingsProblem(Log.WARN,
9396 "Unknown element under <enabled-components>: "
9397 + parser.getName());
9398 }
9399 XmlUtils.skipCurrentTag(parser);
9400 }
9401 }
9402
9403 private void readSharedUserLP(XmlPullParser parser)
9404 throws XmlPullParserException, IOException {
9405 String name = null;
9406 String idStr = null;
9407 int pkgFlags = 0;
9408 SharedUserSetting su = null;
9409 try {
9410 name = parser.getAttributeValue(null, "name");
9411 idStr = parser.getAttributeValue(null, "userId");
9412 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9413 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9414 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9415 }
9416 if (name == null) {
9417 reportSettingsProblem(Log.WARN,
9418 "Error in package manager settings: <shared-user> has no name at "
9419 + parser.getPositionDescription());
9420 } else if (userId == 0) {
9421 reportSettingsProblem(Log.WARN,
9422 "Error in package manager settings: shared-user "
9423 + name + " has bad userId " + idStr + " at "
9424 + parser.getPositionDescription());
9425 } else {
9426 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9427 reportSettingsProblem(Log.ERROR,
9428 "Occurred while parsing settings at "
9429 + parser.getPositionDescription());
9430 }
9431 }
9432 } catch (NumberFormatException e) {
9433 reportSettingsProblem(Log.WARN,
9434 "Error in package manager settings: package "
9435 + name + " has bad userId " + idStr + " at "
9436 + parser.getPositionDescription());
9437 };
9438
9439 if (su != null) {
9440 int outerDepth = parser.getDepth();
9441 int type;
9442 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9443 && (type != XmlPullParser.END_TAG
9444 || parser.getDepth() > outerDepth)) {
9445 if (type == XmlPullParser.END_TAG
9446 || type == XmlPullParser.TEXT) {
9447 continue;
9448 }
9449
9450 String tagName = parser.getName();
9451 if (tagName.equals("sigs")) {
9452 su.signatures.readXml(parser, mPastSignatures);
9453 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009454 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009455 } else {
9456 reportSettingsProblem(Log.WARN,
9457 "Unknown element under <shared-user>: "
9458 + parser.getName());
9459 XmlUtils.skipCurrentTag(parser);
9460 }
9461 }
9462
9463 } else {
9464 XmlUtils.skipCurrentTag(parser);
9465 }
9466 }
9467
9468 private void readGrantedPermissionsLP(XmlPullParser parser,
9469 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9470 int outerDepth = parser.getDepth();
9471 int type;
9472 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9473 && (type != XmlPullParser.END_TAG
9474 || parser.getDepth() > outerDepth)) {
9475 if (type == XmlPullParser.END_TAG
9476 || type == XmlPullParser.TEXT) {
9477 continue;
9478 }
9479
9480 String tagName = parser.getName();
9481 if (tagName.equals("item")) {
9482 String name = parser.getAttributeValue(null, "name");
9483 if (name != null) {
9484 outPerms.add(name.intern());
9485 } else {
9486 reportSettingsProblem(Log.WARN,
9487 "Error in package manager settings: <perms> has"
9488 + " no name at " + parser.getPositionDescription());
9489 }
9490 } else {
9491 reportSettingsProblem(Log.WARN,
9492 "Unknown element under <perms>: "
9493 + parser.getName());
9494 }
9495 XmlUtils.skipCurrentTag(parser);
9496 }
9497 }
9498
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009499 private void readPreferredActivitiesLP(XmlPullParser parser)
9500 throws XmlPullParserException, IOException {
9501 int outerDepth = parser.getDepth();
9502 int type;
9503 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9504 && (type != XmlPullParser.END_TAG
9505 || parser.getDepth() > outerDepth)) {
9506 if (type == XmlPullParser.END_TAG
9507 || type == XmlPullParser.TEXT) {
9508 continue;
9509 }
9510
9511 String tagName = parser.getName();
9512 if (tagName.equals("item")) {
9513 PreferredActivity pa = new PreferredActivity(parser);
9514 if (pa.mParseError == null) {
9515 mPreferredActivities.addFilter(pa);
9516 } else {
9517 reportSettingsProblem(Log.WARN,
9518 "Error in package manager settings: <preferred-activity> "
9519 + pa.mParseError + " at "
9520 + parser.getPositionDescription());
9521 }
9522 } else {
9523 reportSettingsProblem(Log.WARN,
9524 "Unknown element under <preferred-activities>: "
9525 + parser.getName());
9526 XmlUtils.skipCurrentTag(parser);
9527 }
9528 }
9529 }
9530
9531 // Returns -1 if we could not find an available UserId to assign
9532 private int newUserIdLP(Object obj) {
9533 // Let's be stupidly inefficient for now...
9534 final int N = mUserIds.size();
9535 for (int i=0; i<N; i++) {
9536 if (mUserIds.get(i) == null) {
9537 mUserIds.set(i, obj);
9538 return FIRST_APPLICATION_UID + i;
9539 }
9540 }
9541
9542 // None left?
9543 if (N >= MAX_APPLICATION_UIDS) {
9544 return -1;
9545 }
9546
9547 mUserIds.add(obj);
9548 return FIRST_APPLICATION_UID + N;
9549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009551 public PackageSetting getDisabledSystemPkg(String name) {
9552 synchronized(mPackages) {
9553 PackageSetting ps = mDisabledSysPackages.get(name);
9554 return ps;
9555 }
9556 }
9557
9558 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009559 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9560 return true;
9561 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009562 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9563 if (Config.LOGV) {
9564 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9565 + " componentName = " + componentInfo.name);
9566 Log.v(TAG, "enabledComponents: "
9567 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9568 Log.v(TAG, "disabledComponents: "
9569 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9570 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009571 if (packageSettings == null) {
9572 if (false) {
9573 Log.w(TAG, "WAITING FOR DEBUGGER");
9574 Debug.waitForDebugger();
9575 Log.i(TAG, "We will crash!");
9576 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009577 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009578 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009579 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9580 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9581 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9582 return false;
9583 }
9584 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9585 return true;
9586 }
9587 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9588 return false;
9589 }
9590 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009591 }
9592 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009593
9594 // ------- apps on sdcard specific code -------
9595 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009596 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9597 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9598 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009599 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009600
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009601 private String getEncryptKey() {
9602 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009603 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9604 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009605 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009606 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9607 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009608 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009609 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009610 return null;
9611 }
9612 }
9613 return sdEncKey;
9614 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009615 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009616 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009617 } catch (IOException ioe) {
9618 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9619 + ioe);
9620 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009621 }
Rich Cannings8d578832010-09-09 15:12:40 -07009622
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009623 }
9624
Kenny Rootc78a8072010-07-27 15:18:38 -07009625 /* package */ static String getTempContainerId() {
9626 int tmpIdx = 1;
9627 String list[] = PackageHelper.getSecureContainerList();
9628 if (list != null) {
9629 for (final String name : list) {
9630 // Ignore null and non-temporary container entries
9631 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9632 continue;
9633 }
9634
9635 String subStr = name.substring(mTempContainerPrefix.length());
9636 try {
9637 int cid = Integer.parseInt(subStr);
9638 if (cid >= tmpIdx) {
9639 tmpIdx = cid + 1;
9640 }
9641 } catch (NumberFormatException e) {
9642 }
9643 }
9644 }
9645 return mTempContainerPrefix + tmpIdx;
9646 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009647
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009648 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009649 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009650 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009651 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9652 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9653 throw new SecurityException("Media status can only be updated by the system");
9654 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009655 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009656 Log.i(TAG, "Updating external media status from " +
9657 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9658 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009659 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9660 mediaStatus+", mMediaMounted=" + mMediaMounted);
9661 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009662 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9663 reportStatus ? 1 : 0, -1);
9664 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009665 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009666 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009667 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009668 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009669 // Queue up an async operation since the package installation may take a little while.
9670 mHandler.post(new Runnable() {
9671 public void run() {
9672 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009673 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009674 }
9675 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009676 }
9677
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009678 /*
9679 * Collect information of applications on external media, map them
9680 * against existing containers and update information based on current
9681 * mount status. Please note that we always have to report status
9682 * if reportStatus has been set to true especially when unloading packages.
9683 */
9684 private void updateExternalMediaStatusInner(boolean mediaStatus,
9685 boolean reportStatus) {
9686 // Collection of uids
9687 int uidArr[] = null;
9688 // Collection of stale containers
9689 HashSet<String> removeCids = new HashSet<String>();
9690 // Collection of packages on external media with valid containers.
9691 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9692 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009693 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009694 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009695 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009696 } else {
9697 // Process list of secure containers and categorize them
9698 // as active or stale based on their package internal state.
9699 int uidList[] = new int[list.length];
9700 int num = 0;
9701 synchronized (mPackages) {
9702 for (String cid : list) {
9703 SdInstallArgs args = new SdInstallArgs(cid);
9704 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009705 String pkgName = args.getPackageName();
9706 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009707 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9708 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009709 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009710 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009711 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9712 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009713 // The package status is changed only if the code path
9714 // matches between settings and the container id.
9715 if (ps != null && ps.codePathString != null &&
9716 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009717 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9718 " corresponds to pkg : " + pkgName +
9719 " at code path: " + ps.codePathString);
9720 // We do have a valid package installed on sdcard
9721 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009722 int uid = ps.userId;
9723 if (uid != -1) {
9724 uidList[num++] = uid;
9725 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009726 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009727 // Stale container on sdcard. Just delete
9728 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9729 removeCids.add(cid);
9730 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009731 }
9732 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009733
9734 if (num > 0) {
9735 // Sort uid list
9736 Arrays.sort(uidList, 0, num);
9737 // Throw away duplicates
9738 uidArr = new int[num];
9739 uidArr[0] = uidList[0];
9740 int di = 0;
9741 for (int i = 1; i < num; i++) {
9742 if (uidList[i-1] != uidList[i]) {
9743 uidArr[di++] = uidList[i];
9744 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009745 }
9746 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009747 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009748 // Process packages with valid entries.
9749 if (mediaStatus) {
9750 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009751 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009752 startCleaningPackages();
9753 } else {
9754 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009755 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009756 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009757 }
9758
9759 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009760 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009761 int size = pkgList.size();
9762 if (size > 0) {
9763 // Send broadcasts here
9764 Bundle extras = new Bundle();
9765 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9766 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009767 if (uidArr != null) {
9768 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9769 }
9770 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9771 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009772 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009773 }
9774 }
9775
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009776 /*
9777 * Look at potentially valid container ids from processCids
9778 * If package information doesn't match the one on record
9779 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009780 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009781 */
9782 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009783 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009784 ArrayList<String> pkgList = new ArrayList<String>();
9785 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009786 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009787 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009788 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009789 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9790 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009791 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009792 try {
9793 // Make sure there are no container errors first.
9794 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9795 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009796 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009797 " when installing from sdcard");
9798 continue;
9799 }
9800 // Check code path here.
9801 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009802 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009803 " does not match one in settings " + codePath);
9804 continue;
9805 }
9806 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009807 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009808 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009809 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009810 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009811 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009812 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009813 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009814 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009815 retCode = PackageManager.INSTALL_SUCCEEDED;
9816 pkgList.add(pkg.packageName);
9817 // Post process args
9818 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9819 }
9820 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009821 Slog.i(TAG, "Failed to install pkg from " +
9822 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009823 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009824 }
9825
9826 } finally {
9827 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9828 // Don't destroy container here. Wait till gc clears things up.
9829 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009830 }
9831 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009832 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009833 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009834 // If the platform SDK has changed since the last time we booted,
9835 // we need to re-grant app permission to catch any new ones that
9836 // appear. This is really a hack, and means that apps can in some
9837 // cases get permissions that the user didn't initially explicitly
9838 // allow... it would be nice to have some better way to handle
9839 // this situation.
9840 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9841 != mSdkVersion;
9842 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9843 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9844 + "; regranting permissions for external storage");
9845 mSettings.mExternalSdkPlatform = mSdkVersion;
9846
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009847 // Make sure group IDs have been assigned, and any permission
9848 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009849 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009850 // Persist settings
9851 mSettings.writeLP();
9852 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009853 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009854 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009855 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009856 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009857 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009858 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009859 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009860 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009861 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009862 if (removeCids != null) {
9863 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009864 if (cid.startsWith(mTempContainerPrefix)) {
9865 Log.i(TAG, "Destroying stale temporary container " + cid);
9866 PackageHelper.destroySdDir(cid);
9867 } else {
9868 Log.w(TAG, "Container " + cid + " is stale");
9869 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009870 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009871 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009872 }
9873
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009874 /*
9875 * Utility method to unload a list of specified containers
9876 */
9877 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9878 // Just unmount all valid containers.
9879 for (SdInstallArgs arg : cidArgs) {
9880 synchronized (mInstallLock) {
9881 arg.doPostDeleteLI(false);
9882 }
9883 }
9884 }
9885
9886 /*
9887 * Unload packages mounted on external media. This involves deleting
9888 * package data from internal structures, sending broadcasts about
9889 * diabled packages, gc'ing to free up references, unmounting all
9890 * secure containers corresponding to packages on external media, and
9891 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9892 * Please note that we always have to post this message if status has
9893 * been requested no matter what.
9894 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009895 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009896 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009897 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009898 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009899 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009900 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009901 for (SdInstallArgs args : keys) {
9902 String cid = args.cid;
9903 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009904 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009905 // Delete package internally
9906 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9907 synchronized (mInstallLock) {
9908 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009909 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009910 if (res) {
9911 pkgList.add(pkgName);
9912 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009913 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009914 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009915 }
9916 }
9917 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07009918
9919 synchronized (mPackages) {
9920 // We didn't update the settings after removing each package;
9921 // write them now for all packages.
9922 mSettings.writeLP();
9923 }
9924
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009925 // We have to absolutely send UPDATED_MEDIA_STATUS only
9926 // after confirming that all the receivers processed the ordered
9927 // broadcast when packages get disabled, force a gc to clean things up.
9928 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009929 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009930 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9931 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9932 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009933 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9934 reportStatus ? 1 : 0, 1, keys);
9935 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009936 }
9937 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009938 } else {
9939 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9940 reportStatus ? 1 : 0, -1, keys);
9941 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009942 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009943 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009944
9945 public void movePackage(final String packageName,
9946 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009947 mContext.enforceCallingOrSelfPermission(
9948 android.Manifest.permission.MOVE_PACKAGE, null);
9949 int returnCode = PackageManager.MOVE_SUCCEEDED;
9950 int currFlags = 0;
9951 int newFlags = 0;
9952 synchronized (mPackages) {
9953 PackageParser.Package pkg = mPackages.get(packageName);
9954 if (pkg == null) {
9955 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009956 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009957 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009958 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009959 Slog.w(TAG, "Cannot move system application");
9960 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009961 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009962 Slog.w(TAG, "Cannot move forward locked app.");
9963 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009964 } else if (pkg.mOperationPending) {
9965 Slog.w(TAG, "Attempt to move package which has pending operations");
9966 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009967 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009968 // Find install location first
9969 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9970 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9971 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009972 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009973 } else {
9974 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9975 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009976 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9977 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009978 if (newFlags == currFlags) {
9979 Slog.w(TAG, "No move required. Trying to move to same location");
9980 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9981 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009982 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009983 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9984 pkg.mOperationPending = true;
9985 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009986 }
9987 }
9988 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009989 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009990 } else {
9991 Message msg = mHandler.obtainMessage(INIT_COPY);
9992 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009993 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9994 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9995 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009996 msg.obj = mp;
9997 mHandler.sendMessage(msg);
9998 }
9999 }
10000 }
10001
10002 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10003 // Queue up an async operation since the package deletion may take a little while.
10004 mHandler.post(new Runnable() {
10005 public void run() {
10006 mHandler.removeCallbacks(this);
10007 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010008 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10009 int uidArr[] = null;
10010 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010011 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010012 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010013 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010014 Slog.w(TAG, " Package " + mp.packageName +
10015 " doesn't exist. Aborting move");
10016 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10017 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10018 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10019 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10020 " Aborting move and returning error");
10021 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10022 } else {
10023 uidArr = new int[] { pkg.applicationInfo.uid };
10024 pkgList = new ArrayList<String>();
10025 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010026 }
10027 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010028 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10029 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010030 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010031 // Update package code and resource paths
10032 synchronized (mInstallLock) {
10033 synchronized (mPackages) {
10034 PackageParser.Package pkg = mPackages.get(mp.packageName);
10035 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010036 if (pkg == null) {
10037 Slog.w(TAG, " Package " + mp.packageName
10038 + " doesn't exist. Aborting move");
10039 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010040 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10041 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10042 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10043 " Aborting move and returning error");
10044 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10045 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010046 final String oldCodePath = pkg.mPath;
10047 final String newCodePath = mp.targetArgs.getCodePath();
10048 final String newResPath = mp.targetArgs.getResourcePath();
10049 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010050
10051 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10052 if (mInstaller
10053 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10054 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10055 } else {
10056 NativeLibraryHelper.copyNativeBinariesLI(
10057 new File(newCodePath), new File(newNativePath));
10058 }
10059 } else {
10060 if (mInstaller.linkNativeLibraryDirectory(
10061 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10062 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10063 }
10064 }
10065
10066 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10067 pkg.mPath = newCodePath;
10068 // Move dex files around
10069 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10070 // Moving of dex files failed. Set
10071 // error code and abort move.
10072 pkg.mPath = pkg.mScanPath;
10073 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10074 }
10075 }
10076
10077 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010078 pkg.mScanPath = newCodePath;
10079 pkg.applicationInfo.sourceDir = newCodePath;
10080 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010081 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010082 PackageSetting ps = (PackageSetting) pkg.mExtras;
10083 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10084 ps.codePathString = ps.codePath.getPath();
10085 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10086 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010087 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010088 // Set the application info flag correctly.
10089 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10090 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10091 } else {
10092 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10093 }
10094 ps.setFlags(pkg.applicationInfo.flags);
10095 mAppDirs.remove(oldCodePath);
10096 mAppDirs.put(newCodePath, pkg);
10097 // Persist settings
10098 mSettings.writeLP();
10099 }
10100 }
10101 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010102 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010103 // Send resources available broadcast
10104 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010105 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010106 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010107 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010108 // Clean up failed installation
10109 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010110 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010111 }
10112 } else {
10113 // Force a gc to clear things up.
10114 Runtime.getRuntime().gc();
10115 // Delete older code
10116 synchronized (mInstallLock) {
10117 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010118 }
10119 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010120
10121 // Allow more operations on this file if we didn't fail because
10122 // an operation was already pending for this package.
10123 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10124 synchronized (mPackages) {
10125 PackageParser.Package pkg = mPackages.get(mp.packageName);
10126 if (pkg != null) {
10127 pkg.mOperationPending = false;
10128 }
10129 }
10130 }
10131
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010132 IPackageMoveObserver observer = mp.observer;
10133 if (observer != null) {
10134 try {
10135 observer.packageMoved(mp.packageName, returnCode);
10136 } catch (RemoteException e) {
10137 Log.i(TAG, "Observer no longer exists.");
10138 }
10139 }
10140 }
10141 });
10142 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010143
10144 public boolean setInstallLocation(int loc) {
10145 mContext.enforceCallingOrSelfPermission(
10146 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10147 if (getInstallLocation() == loc) {
10148 return true;
10149 }
10150 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10151 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10152 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10153 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10154 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10155 return true;
10156 }
10157 return false;
10158 }
10159
10160 public int getInstallLocation() {
10161 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10162 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010164}