blob: e323b3b5bd1bbcd90187842a0c8d8b8dc968b4dc [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;
Nick Pellycd0e8392010-10-13 17:25:24 -0700147 private static final int NFC_UID = Process.NFC_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 private static final int FIRST_APPLICATION_UID =
149 Process.FIRST_APPLICATION_UID;
150 private static final int MAX_APPLICATION_UIDS = 1000;
151
152 private static final boolean SHOW_INFO = false;
153
154 private static final boolean GET_CERTIFICATES = true;
155
Oscar Montemayora8529f62009-11-18 10:14:20 -0800156 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158 private static final int REMOVE_EVENTS =
159 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
160 private static final int ADD_EVENTS =
161 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
162
163 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800164 // Suffix used during package installation when copying/moving
165 // package apks to install directory.
166 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800168 /**
169 * Indicates the state of installation. Used by PackageManager to
170 * figure out incomplete installations. Say a package is being installed
171 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
172 * the package installation is successful or unsuccesful lin which case
173 * the PackageManager will no longer maintain state information associated
174 * with the package. If some exception(like device freeze or battery being
175 * pulled out) occurs during installation of a package, the PackageManager
176 * needs this information to clean up the previously failed installation.
177 */
178 private static final int PKG_INSTALL_INCOMPLETE = 0;
179 private static final int PKG_INSTALL_COMPLETE = 1;
180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181 static final int SCAN_MONITOR = 1<<0;
182 static final int SCAN_NO_DEX = 1<<1;
183 static final int SCAN_FORCE_DEX = 1<<2;
184 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800185 static final int SCAN_NEW_INSTALL = 1<<4;
186 static final int SCAN_NO_PATHS = 1<<5;
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700187 static final int SCAN_UPDATE_TIME = 1<<6;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700189 static final int REMOVE_CHATTY = 1<<16;
Kenny Root11128572010-10-11 10:51:32 -0700190
191 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
192
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800193 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
Kenny Root11128572010-10-11 10:51:32 -0700194 DEFAULT_CONTAINER_PACKAGE,
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800195 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700196
Kenny Root85387d72010-08-26 10:13:11 -0700197 private static final String LIB_DIR_NAME = "lib";
198
Kenny Rootc78a8072010-07-27 15:18:38 -0700199 static final String mTempContainerPrefix = "smdl2tmp";
200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
202 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700203 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Dianne Hackborn851a5412009-05-08 12:06:44 -0700205 final int mSdkVersion = Build.VERSION.SDK_INT;
206 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
207 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 final Context mContext;
210 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700211 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 final DisplayMetrics mMetrics;
213 final int mDefParseFlags;
214 final String[] mSeparateProcesses;
215
216 // This is where all application persistent data goes.
217 final File mAppDataDir;
218
Oscar Montemayora8529f62009-11-18 10:14:20 -0800219 // If Encrypted File System feature is enabled, all application persistent data
220 // should go here instead.
221 final File mSecureAppDataDir;
222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 // This is the object monitoring the framework dir.
224 final FileObserver mFrameworkInstallObserver;
225
226 // This is the object monitoring the system app dir.
227 final FileObserver mSystemInstallObserver;
228
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700229 // This is the object monitoring the system app dir.
230 final FileObserver mVendorInstallObserver;
231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 // This is the object monitoring mAppInstallDir.
233 final FileObserver mAppInstallObserver;
234
235 // This is the object monitoring mDrmAppPrivateInstallDir.
236 final FileObserver mDrmAppInstallObserver;
237
238 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
239 // LOCK HELD. Can be called with mInstallLock held.
240 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 final File mFrameworkDir;
243 final File mSystemAppDir;
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700244 final File mVendorAppDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700246 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
248 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
249 // apps.
250 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800254 // Lock for state used when installing and doing other long running
255 // operations. Methods that must be called with this lock held have
256 // the prefix "LI".
257 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800259 // These are the directories in the 3rd party applications installed dir
260 // that we have currently loaded packages from. Keys are the application's
261 // installed zip file (absolute codePath), and values are Package.
262 final HashMap<String, PackageParser.Package> mAppDirs =
263 new HashMap<String, PackageParser.Package>();
264
265 // Information for the parser to write more useful error messages.
266 File mScanningPath;
267 int mLastScanError;
268
269 final int[] mOutPermissions = new int[3];
270
271 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273 // Keys are String (package name), values are Package. This also serves
274 // as the lock for the global state. Methods that must be called with
275 // this lock held have the prefix "LP".
276 final HashMap<String, PackageParser.Package> mPackages =
277 new HashMap<String, PackageParser.Package>();
278
279 final Settings mSettings;
280 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800281
282 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
283 int[] mGlobalGids;
284
285 // These are the built-in uid -> permission mappings that were read from the
286 // etc/permissions.xml file.
287 final SparseArray<HashSet<String>> mSystemPermissions =
288 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 // These are the built-in shared libraries that were read from the
291 // etc/permissions.xml file.
292 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
Dianne Hackborn49237342009-08-27 20:08:01 -0700294 // Temporary for building the final shared libraries for an .apk.
295 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800296
Dianne Hackborn49237342009-08-27 20:08:01 -0700297 // These are the features this devices supports that were read from the
298 // etc/permissions.xml file.
299 final HashMap<String, FeatureInfo> mAvailableFeatures =
300 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800302 // All available activities, for your resolving pleasure.
303 final ActivityIntentResolver mActivities =
304 new ActivityIntentResolver();
305
306 // All available receivers, for your resolving pleasure.
307 final ActivityIntentResolver mReceivers =
308 new ActivityIntentResolver();
309
310 // All available services, for your resolving pleasure.
311 final ServiceIntentResolver mServices = new ServiceIntentResolver();
312
313 // Keys are String (provider class name), values are Provider.
314 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
315 new HashMap<ComponentName, PackageParser.Provider>();
316
317 // Mapping from provider base names (first directory in content URI codePath)
318 // to the provider information.
319 final HashMap<String, PackageParser.Provider> mProviders =
320 new HashMap<String, PackageParser.Provider>();
321
322 // Mapping from instrumentation class names to info about them.
323 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
324 new HashMap<ComponentName, PackageParser.Instrumentation>();
325
326 // Mapping from permission names to info about them.
327 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
328 new HashMap<String, PackageParser.PermissionGroup>();
329
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800330 // Packages whose data we have transfered into another package, thus
331 // should no longer exist.
332 final HashSet<String> mTransferedPackages = new HashSet<String>();
333
Dianne Hackborn854060af2009-07-09 18:14:31 -0700334 // Broadcast actions that are only available to the system.
335 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 boolean mSystemReady;
338 boolean mSafeMode;
339 boolean mHasSystemUidErrors;
340
341 ApplicationInfo mAndroidApplication;
342 final ActivityInfo mResolveActivity = new ActivityInfo();
343 final ResolveInfo mResolveInfo = new ResolveInfo();
344 ComponentName mResolveComponentName;
345 PackageParser.Package mPlatformPackage;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800348 final HashMap<String, ArrayList<String>> mPendingBroadcasts
349 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800350 // Service Connection to remote media container service to copy
351 // package uri's from external media onto secure containers
352 // or internal storage.
353 private IMediaContainerService mContainerService = null;
354
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700355 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800356 static final int MCS_BOUND = 3;
357 static final int END_COPY = 4;
358 static final int INIT_COPY = 5;
359 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800360 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800361 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800362 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800363 static final int MCS_RECONNECT = 10;
364 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700365 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700366 static final int WRITE_SETTINGS = 13;
367
368 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800369
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700370 // Delay time in millisecs
371 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800372 final private DefaultContainerConnection mDefContainerConn =
373 new DefaultContainerConnection();
374 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800375 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800376 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800377 IMediaContainerService imcs =
378 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800379 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800380 }
381
382 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800383 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800384 }
385 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700386
Christopher Tate1bb69062010-02-19 17:02:12 -0800387 // Recordkeeping of restore-after-install operations that are currently in flight
388 // between the Package Manager and the Backup Manager
389 class PostInstallData {
390 public InstallArgs args;
391 public PackageInstalledInfo res;
392
393 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
394 args = _a;
395 res = _r;
396 }
397 };
398 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
399 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
400
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700401 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800403 final ArrayList<HandlerParams> mPendingInstalls =
404 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800405
406 private boolean connectToService() {
407 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
408 " DefaultContainerService");
409 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700410 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800411 if (mContext.bindService(service, mDefContainerConn,
412 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700413 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800414 mBound = true;
415 return true;
416 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700417 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800418 return false;
419 }
420
421 private void disconnectService() {
422 mContainerService = null;
423 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700424 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800425 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800427 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800428
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700429 PackageHandler(Looper looper) {
430 super(looper);
431 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700432
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700433 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700434 try {
435 doHandleMessage(msg);
436 } finally {
437 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
438 }
439 }
440
441 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700442 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800443 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800444 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800445 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800446 int idx = mPendingInstalls.size();
447 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
448 // If a bind was already initiated we dont really
449 // need to do anything. The pending install
450 // will be processed later on.
451 if (!mBound) {
452 // If this is the only one pending we might
453 // have to bind to the service again.
454 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800455 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800456 params.serviceError();
457 return;
458 } else {
459 // Once we bind to the service, the first
460 // pending request will be processed.
461 mPendingInstalls.add(idx, params);
462 }
463 } else {
464 mPendingInstalls.add(idx, params);
465 // Already bound to the service. Just make
466 // sure we trigger off processing the first request.
467 if (idx == 0) {
468 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800469 }
470 }
471 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800472 }
473 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800474 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800475 if (msg.obj != null) {
476 mContainerService = (IMediaContainerService) msg.obj;
477 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 if (mContainerService == null) {
479 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800480 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800481 for (HandlerParams params : mPendingInstalls) {
482 mPendingInstalls.remove(0);
483 // Indicate service bind error
484 params.serviceError();
485 }
486 mPendingInstalls.clear();
487 } else if (mPendingInstalls.size() > 0) {
488 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800489 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800490 params.startCopy();
491 }
492 } else {
493 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800494 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800495 }
496 break;
497 }
498 case MCS_RECONNECT : {
499 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
500 if (mPendingInstalls.size() > 0) {
501 if (mBound) {
502 disconnectService();
503 }
504 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800505 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800506 for (HandlerParams params : mPendingInstalls) {
507 mPendingInstalls.remove(0);
508 // Indicate service bind error
509 params.serviceError();
510 }
511 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800512 }
513 }
514 break;
515 }
516 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800517 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
518 // Delete pending install
519 if (mPendingInstalls.size() > 0) {
520 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800521 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800522 if (mPendingInstalls.size() == 0) {
523 if (mBound) {
524 disconnectService();
525 }
526 } else {
527 // There are more pending requests in queue.
528 // Just post MCS_BOUND message to trigger processing
529 // of next pending install.
530 mHandler.sendEmptyMessage(MCS_BOUND);
531 }
532 break;
533 }
534 case MCS_GIVE_UP: {
535 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
536 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800537 break;
538 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700539 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800540 String packages[];
541 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700542 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700543 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700544 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700545 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800546 if (mPendingBroadcasts == null) {
547 return;
548 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700549 size = mPendingBroadcasts.size();
550 if (size <= 0) {
551 // Nothing to be done. Just return
552 return;
553 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 packages = new String[size];
555 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700556 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800557 Iterator<HashMap.Entry<String, ArrayList<String>>>
558 it = mPendingBroadcasts.entrySet().iterator();
559 int i = 0;
560 while (it.hasNext() && i < size) {
561 HashMap.Entry<String, ArrayList<String>> ent = it.next();
562 packages[i] = ent.getKey();
563 components[i] = ent.getValue();
564 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700565 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800566 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700567 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800568 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700569 mPendingBroadcasts.clear();
570 }
571 // Send broadcasts
572 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800573 sendPackageChangedBroadcast(packages[i], true,
574 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700575 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700577 break;
578 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800579 case START_CLEANING_PACKAGE: {
580 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700581 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800582 synchronized (mPackages) {
583 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
584 mSettings.mPackagesToBeCleaned.add(packageName);
585 }
586 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700587 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800588 startCleaningPackages();
589 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800590 case POST_INSTALL: {
591 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
592 PostInstallData data = mRunningInstalls.get(msg.arg1);
593 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700594 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800595
596 if (data != null) {
597 InstallArgs args = data.args;
598 PackageInstalledInfo res = data.res;
599
600 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700601 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800602 Bundle extras = new Bundle(1);
603 extras.putInt(Intent.EXTRA_UID, res.uid);
604 final boolean update = res.removedInfo.removedPackage != null;
605 if (update) {
606 extras.putBoolean(Intent.EXTRA_REPLACING, true);
607 }
608 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
609 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700610 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800611 if (update) {
612 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
613 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700614 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800615 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700616 if (res.removedInfo.args != null) {
617 // Remove the replaced package's older resources safely now
618 deleteOld = true;
619 }
620 }
621 // Force a gc to clear up things
622 Runtime.getRuntime().gc();
623 // We delete after a gc for applications on sdcard.
624 if (deleteOld) {
625 synchronized (mInstallLock) {
626 res.removedInfo.args.doPostDeleteLI(true);
627 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800628 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800629 if (args.observer != null) {
630 try {
631 args.observer.packageInstalled(res.name, res.returnCode);
632 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800633 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800634 }
635 }
636 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800637 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800638 }
639 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700640 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700641 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
642 boolean reportStatus = msg.arg1 == 1;
643 boolean doGc = msg.arg2 == 1;
644 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
645 if (doGc) {
646 // Force a gc to clear up stale containers.
647 Runtime.getRuntime().gc();
648 }
649 if (msg.obj != null) {
650 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
651 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
652 // Unload containers
653 unloadAllContainers(args);
654 }
655 if (reportStatus) {
656 try {
657 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
658 PackageHelper.getMountService().finishMediaUpdate();
659 } catch (RemoteException e) {
660 Log.e(TAG, "MountService not running?");
661 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700662 }
663 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700664 case WRITE_SETTINGS: {
665 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
666 synchronized (mPackages) {
667 removeMessages(WRITE_SETTINGS);
668 mSettings.writeLP();
669 }
670 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
671 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700672 }
673 }
674 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800675
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700676 void scheduleWriteSettingsLocked() {
677 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
678 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
679 }
680 }
681
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800682 static boolean installOnSd(int flags) {
683 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700684 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800685 return false;
686 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700687 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
688 return true;
689 }
690 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800691 }
692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693 public static final IPackageManager main(Context context, boolean factoryTest) {
694 PackageManagerService m = new PackageManagerService(context, factoryTest);
695 ServiceManager.addService("package", m);
696 return m;
697 }
698
699 static String[] splitString(String str, char sep) {
700 int count = 1;
701 int i = 0;
702 while ((i=str.indexOf(sep, i)) >= 0) {
703 count++;
704 i++;
705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 String[] res = new String[count];
708 i=0;
709 count = 0;
710 int lastI=0;
711 while ((i=str.indexOf(sep, i)) >= 0) {
712 res[count] = str.substring(lastI, i);
713 count++;
714 i++;
715 lastI = i;
716 }
717 res[count] = str.substring(lastI, str.length());
718 return res;
719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800722 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800725 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800726 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 mContext = context;
730 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700731 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732 mMetrics = new DisplayMetrics();
733 mSettings = new Settings();
734 mSettings.addSharedUserLP("android.uid.system",
735 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
736 mSettings.addSharedUserLP("android.uid.phone",
737 MULTIPLE_APPLICATION_UIDS
738 ? RADIO_UID : FIRST_APPLICATION_UID,
739 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400740 mSettings.addSharedUserLP("android.uid.log",
741 MULTIPLE_APPLICATION_UIDS
742 ? LOG_UID : FIRST_APPLICATION_UID,
743 ApplicationInfo.FLAG_SYSTEM);
Nick Pellycd0e8392010-10-13 17:25:24 -0700744 mSettings.addSharedUserLP("android.uid.nfc",
745 MULTIPLE_APPLICATION_UIDS
746 ? NFC_UID : FIRST_APPLICATION_UID,
747 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748
749 String separateProcesses = SystemProperties.get("debug.separate_processes");
750 if (separateProcesses != null && separateProcesses.length() > 0) {
751 if ("*".equals(separateProcesses)) {
752 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
753 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800754 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800755 } else {
756 mDefParseFlags = 0;
757 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800758 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800759 + separateProcesses);
760 }
761 } else {
762 mDefParseFlags = 0;
763 mSeparateProcesses = null;
764 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 Installer installer = new Installer();
767 // Little hacky thing to check if installd is here, to determine
768 // whether we are running on the simulator and thus need to take
769 // care of building the /data file structure ourself.
770 // (apparently the sim now has a working installer)
771 if (installer.ping() && Process.supportsProcesses()) {
772 mInstaller = installer;
773 } else {
774 mInstaller = null;
775 }
776
777 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
778 Display d = wm.getDefaultDisplay();
779 d.getMetrics(mMetrics);
780
781 synchronized (mInstallLock) {
782 synchronized (mPackages) {
783 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700784 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800786 File dataDir = Environment.getDataDirectory();
787 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800788 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800789 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
790
791 if (mInstaller == null) {
792 // Make sure these dirs exist, when we are running in
793 // the simulator.
794 // Make a wide-open directory for random misc stuff.
795 File miscDir = new File(dataDir, "misc");
796 miscDir.mkdirs();
797 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800798 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 mDrmAppPrivateInstallDir.mkdirs();
800 }
801
802 readPermissions();
803
804 mRestoredSettings = mSettings.readLP();
805 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806
807 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800809
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800810 // Set flag to monitor and not change apk file paths when
811 // scanning install directories.
812 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700813 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800814 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800815 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700816 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800819
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700821 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800822
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700824 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 /**
827 * Out of paranoia, ensure that everything in the boot class
828 * path has been dexed.
829 */
830 String bootClassPath = System.getProperty("java.boot.class.path");
831 if (bootClassPath != null) {
832 String[] paths = splitString(bootClassPath, ':');
833 for (int i=0; i<paths.length; i++) {
834 try {
835 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
836 libFiles.add(paths[i]);
837 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700838 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
840 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800841 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800843 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 }
845 }
846 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800847 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 /**
851 * Also ensure all external libraries have had dexopt run on them.
852 */
853 if (mSharedLibraries.size() > 0) {
854 Iterator<String> libs = mSharedLibraries.values().iterator();
855 while (libs.hasNext()) {
856 String lib = libs.next();
857 try {
858 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
859 libFiles.add(lib);
860 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700861 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 }
863 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800864 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800866 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
868 }
869 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 // Gross hack for now: we know this file doesn't contain any
872 // code, so don't dexopt it to avoid the resulting log spew.
873 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 /**
876 * And there are a number of commands implemented in Java, which
877 * we currently need to do the dexopt on so that they can be
878 * run from a non-root shell.
879 */
880 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700881 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800882 for (int i=0; i<frameworkFiles.length; i++) {
883 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
884 String path = libPath.getPath();
885 // Skip the file if we alrady did it.
886 if (libFiles.contains(path)) {
887 continue;
888 }
889 // Skip the file if it is not a type we want to dexopt.
890 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
891 continue;
892 }
893 try {
894 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
895 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700896 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 }
898 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800899 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800900 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800901 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
903 }
904 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800905
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700906 if (didDexOpt) {
907 // If we had to do a dexopt of one of the previous
908 // things, then something on the system has changed.
909 // Consider this significant, and wipe away all other
910 // existing dexopt files to ensure we don't leave any
911 // dangling around.
912 String[] files = mDalvikCacheDir.list();
913 if (files != null) {
914 for (int i=0; i<files.length; i++) {
915 String fn = files[i];
916 if (fn.startsWith("data@app@")
917 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800918 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700919 (new File(mDalvikCacheDir, fn)).delete();
920 }
921 }
922 }
923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800925
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800926 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800927 mFrameworkInstallObserver = new AppDirObserver(
928 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
929 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700930 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
931 | PackageParser.PARSE_IS_SYSTEM_DIR,
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700932 scanMode | SCAN_NO_DEX, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800933
934 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
936 mSystemInstallObserver = new AppDirObserver(
937 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
938 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700939 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700940 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800941
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700942 // Collect all vendor packages.
943 mVendorAppDir = new File("/vendor/app");
944 mVendorInstallObserver = new AppDirObserver(
945 mVendorAppDir.getPath(), OBSERVER_EVENTS, true);
946 mVendorInstallObserver.startWatching();
947 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700948 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
Dianne Hackborn3b4bac72010-09-20 11:37:52 -0700949
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800950 if (mInstaller != null) {
951 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
952 mInstaller.moveFiles();
953 }
954
955 // Prune any system packages that no longer exist.
956 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
957 while (psit.hasNext()) {
958 PackageSetting ps = psit.next();
959 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800960 && !mPackages.containsKey(ps.name)
961 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800962 psit.remove();
963 String msg = "System package " + ps.name
964 + " no longer exists; wiping its data";
965 reportSettingsProblem(Log.WARN, msg);
966 if (mInstaller != null) {
967 // XXX how to set useEncryptedFSDir for packages that
968 // are not encrypted?
969 mInstaller.remove(ps.name, true);
970 }
971 }
972 }
973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 mAppInstallDir = new File(dataDir, "app");
975 if (mInstaller == null) {
976 // Make sure these dirs exist, when we are running in
977 // the simulator.
978 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
979 }
980 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800981 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 //clean up list
983 for(int i = 0; i < deletePkgsList.size(); i++) {
984 //clean up here
985 cleanupInstallFailedPackage(deletePkgsList.get(i));
986 }
987 //delete tmp files
988 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800989
990 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800991 SystemClock.uptimeMillis());
992 mAppInstallObserver = new AppDirObserver(
993 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
994 mAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -0700995 scanDirLI(mAppInstallDir, 0, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996
997 mDrmAppInstallObserver = new AppDirObserver(
998 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
999 mDrmAppInstallObserver.startWatching();
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001000 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1001 scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001003 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001005 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 + ((SystemClock.uptimeMillis()-startTime)/1000f)
1007 + " seconds");
1008
Dianne Hackbornf22221f2010-04-05 18:35:42 -07001009 // If the platform SDK has changed since the last time we booted,
1010 // we need to re-grant app permission to catch any new ones that
1011 // appear. This is really a hack, and means that apps can in some
1012 // cases get permissions that the user didn't initially explicitly
1013 // allow... it would be nice to have some better way to handle
1014 // this situation.
1015 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1016 != mSdkVersion;
1017 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1018 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1019 + "; regranting permissions for internal storage");
1020 mSettings.mInternalSdkPlatform = mSdkVersion;
1021
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001022 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023
1024 mSettings.writeLP();
1025
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001026 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 // Now after opening every single application zip, make sure they
1030 // are all flushed. Not really needed, but keeps things nice and
1031 // tidy.
1032 Runtime.getRuntime().gc();
1033 } // synchronized (mPackages)
1034 } // synchronized (mInstallLock)
1035 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 @Override
1038 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1039 throws RemoteException {
1040 try {
1041 return super.onTransact(code, data, reply, flags);
1042 } catch (RuntimeException e) {
1043 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001044 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046 throw e;
1047 }
1048 }
1049
Dianne Hackborne6620b22010-01-22 14:46:21 -08001050 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001053 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1054 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001056 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001057 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
1059 } else {
1060 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001061 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 File dataDir = new File(pkg.applicationInfo.dataDir);
1063 dataDir.delete();
1064 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001065 if (ps.codePath != null) {
1066 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001067 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001068 }
1069 }
1070 if (ps.resourcePath != null) {
1071 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001072 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001073 }
1074 }
1075 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
1077
1078 void readPermissions() {
1079 // Read permissions from .../etc/permission directory.
1080 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1081 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001082 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 return;
1084 }
1085 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001086 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001087 return;
1088 }
1089
1090 // Iterate over the files in the directory and scan .xml files
1091 for (File f : libraryDir.listFiles()) {
1092 // We'll read platform.xml last
1093 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1094 continue;
1095 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001098 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 continue;
1100 }
1101 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001102 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 continue;
1104 }
1105
1106 readPermissionsFromXml(f);
1107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1110 final File permFile = new File(Environment.getRootDirectory(),
1111 "etc/permissions/platform.xml");
1112 readPermissionsFromXml(permFile);
1113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
1115 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 FileReader permReader = null;
1117 try {
1118 permReader = new FileReader(permFile);
1119 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001120 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 return;
1122 }
1123
1124 try {
1125 XmlPullParser parser = Xml.newPullParser();
1126 parser.setInput(permReader);
1127
1128 XmlUtils.beginDocument(parser, "permissions");
1129
1130 while (true) {
1131 XmlUtils.nextElement(parser);
1132 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1133 break;
1134 }
1135
1136 String name = parser.getName();
1137 if ("group".equals(name)) {
1138 String gidStr = parser.getAttributeValue(null, "gid");
1139 if (gidStr != null) {
1140 int gid = Integer.parseInt(gidStr);
1141 mGlobalGids = appendInt(mGlobalGids, gid);
1142 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + parser.getPositionDescription());
1145 }
1146
1147 XmlUtils.skipCurrentTag(parser);
1148 continue;
1149 } else if ("permission".equals(name)) {
1150 String perm = parser.getAttributeValue(null, "name");
1151 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 + parser.getPositionDescription());
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157 perm = perm.intern();
1158 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 } else if ("assign-permission".equals(name)) {
1161 String perm = parser.getAttributeValue(null, "name");
1162 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001163 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 + parser.getPositionDescription());
1165 XmlUtils.skipCurrentTag(parser);
1166 continue;
1167 }
1168 String uidStr = parser.getAttributeValue(null, "uid");
1169 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001170 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 + parser.getPositionDescription());
1172 XmlUtils.skipCurrentTag(parser);
1173 continue;
1174 }
1175 int uid = Process.getUidForName(uidStr);
1176 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 + uidStr + "\" at "
1179 + parser.getPositionDescription());
1180 XmlUtils.skipCurrentTag(parser);
1181 continue;
1182 }
1183 perm = perm.intern();
1184 HashSet<String> perms = mSystemPermissions.get(uid);
1185 if (perms == null) {
1186 perms = new HashSet<String>();
1187 mSystemPermissions.put(uid, perms);
1188 }
1189 perms.add(perm);
1190 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 } else if ("library".equals(name)) {
1193 String lname = parser.getAttributeValue(null, "name");
1194 String lfile = parser.getAttributeValue(null, "file");
1195 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001196 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 + parser.getPositionDescription());
1198 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 + parser.getPositionDescription());
1201 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001202 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 mSharedLibraries.put(lname, lfile);
1204 }
1205 XmlUtils.skipCurrentTag(parser);
1206 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001207
Dianne Hackborn49237342009-08-27 20:08:01 -07001208 } else if ("feature".equals(name)) {
1209 String fname = parser.getAttributeValue(null, "name");
1210 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001211 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001212 + parser.getPositionDescription());
1213 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001214 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 FeatureInfo fi = new FeatureInfo();
1216 fi.name = fname;
1217 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219 XmlUtils.skipCurrentTag(parser);
1220 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } else {
1223 XmlUtils.skipCurrentTag(parser);
1224 continue;
1225 }
1226
1227 }
Brian Carlstromfd9ddd12010-11-04 11:24:58 -07001228 permReader.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001230 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001232 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
1234 }
1235
1236 void readPermission(XmlPullParser parser, String name)
1237 throws IOException, XmlPullParserException {
1238
1239 name = name.intern();
1240
1241 BasePermission bp = mSettings.mPermissions.get(name);
1242 if (bp == null) {
1243 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1244 mSettings.mPermissions.put(name, bp);
1245 }
1246 int outerDepth = parser.getDepth();
1247 int type;
1248 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1249 && (type != XmlPullParser.END_TAG
1250 || parser.getDepth() > outerDepth)) {
1251 if (type == XmlPullParser.END_TAG
1252 || type == XmlPullParser.TEXT) {
1253 continue;
1254 }
1255
1256 String tagName = parser.getName();
1257 if ("group".equals(tagName)) {
1258 String gidStr = parser.getAttributeValue(null, "gid");
1259 if (gidStr != null) {
1260 int gid = Process.getGidForName(gidStr);
1261 bp.gids = appendInt(bp.gids, gid);
1262 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001263 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 + parser.getPositionDescription());
1265 }
1266 }
1267 XmlUtils.skipCurrentTag(parser);
1268 }
1269 }
1270
1271 static int[] appendInt(int[] cur, int val) {
1272 if (cur == null) {
1273 return new int[] { val };
1274 }
1275 final int N = cur.length;
1276 for (int i=0; i<N; i++) {
1277 if (cur[i] == val) {
1278 return cur;
1279 }
1280 }
1281 int[] ret = new int[N+1];
1282 System.arraycopy(cur, 0, ret, 0, N);
1283 ret[N] = val;
1284 return ret;
1285 }
1286
1287 static int[] appendInts(int[] cur, int[] add) {
1288 if (add == null) return cur;
1289 if (cur == null) return add;
1290 final int N = add.length;
1291 for (int i=0; i<N; i++) {
1292 cur = appendInt(cur, add[i]);
1293 }
1294 return cur;
1295 }
1296
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001297 static int[] removeInt(int[] cur, int val) {
1298 if (cur == null) {
1299 return null;
1300 }
1301 final int N = cur.length;
1302 for (int i=0; i<N; i++) {
1303 if (cur[i] == val) {
1304 int[] ret = new int[N-1];
1305 if (i > 0) {
1306 System.arraycopy(cur, 0, ret, 0, i);
1307 }
1308 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001309 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001310 }
1311 return ret;
1312 }
1313 }
1314 return cur;
1315 }
1316
1317 static int[] removeInts(int[] cur, int[] rem) {
1318 if (rem == null) return cur;
1319 if (cur == null) return cur;
1320 final int N = rem.length;
1321 for (int i=0; i<N; i++) {
1322 cur = removeInt(cur, rem[i]);
1323 }
1324 return cur;
1325 }
1326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001327 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001328 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1329 // The package has been uninstalled but has retained data and resources.
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001330 return PackageParser.generatePackageInfo(p, null, flags, 0, 0);
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 final PackageSetting ps = (PackageSetting)p.mExtras;
1333 if (ps == null) {
1334 return null;
1335 }
1336 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07001337 return PackageParser.generatePackageInfo(p, gp.gids, flags,
1338 ps.firstInstallTime, ps.lastUpdateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
1340
1341 public PackageInfo getPackageInfo(String packageName, int flags) {
1342 synchronized (mPackages) {
1343 PackageParser.Package p = mPackages.get(packageName);
1344 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001345 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 + ": " + p);
1347 if (p != null) {
1348 return generatePackageInfo(p, flags);
1349 }
1350 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1351 return generatePackageInfoFromSettingsLP(packageName, flags);
1352 }
1353 }
1354 return null;
1355 }
1356
Dianne Hackborn47096932010-02-11 15:57:09 -08001357 public String[] currentToCanonicalPackageNames(String[] names) {
1358 String[] out = new String[names.length];
1359 synchronized (mPackages) {
1360 for (int i=names.length-1; i>=0; i--) {
1361 PackageSetting ps = mSettings.mPackages.get(names[i]);
1362 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1363 }
1364 }
1365 return out;
1366 }
1367
1368 public String[] canonicalToCurrentPackageNames(String[] names) {
1369 String[] out = new String[names.length];
1370 synchronized (mPackages) {
1371 for (int i=names.length-1; i>=0; i--) {
1372 String cur = mSettings.mRenamedPackages.get(names[i]);
1373 out[i] = cur != null ? cur : names[i];
1374 }
1375 }
1376 return out;
1377 }
1378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 public int getPackageUid(String packageName) {
1380 synchronized (mPackages) {
1381 PackageParser.Package p = mPackages.get(packageName);
1382 if(p != null) {
1383 return p.applicationInfo.uid;
1384 }
1385 PackageSetting ps = mSettings.mPackages.get(packageName);
1386 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1387 return -1;
1388 }
1389 p = ps.pkg;
1390 return p != null ? p.applicationInfo.uid : -1;
1391 }
1392 }
1393
1394 public int[] getPackageGids(String packageName) {
1395 synchronized (mPackages) {
1396 PackageParser.Package p = mPackages.get(packageName);
1397 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001398 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 + ": " + p);
1400 if (p != null) {
1401 final PackageSetting ps = (PackageSetting)p.mExtras;
1402 final SharedUserSetting suid = ps.sharedUser;
1403 return suid != null ? suid.gids : ps.gids;
1404 }
1405 }
1406 // stupid thing to indicate an error.
1407 return new int[0];
1408 }
1409
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001410 static final PermissionInfo generatePermissionInfo(
1411 BasePermission bp, int flags) {
1412 if (bp.perm != null) {
1413 return PackageParser.generatePermissionInfo(bp.perm, flags);
1414 }
1415 PermissionInfo pi = new PermissionInfo();
1416 pi.name = bp.name;
1417 pi.packageName = bp.sourcePackage;
1418 pi.nonLocalizedLabel = bp.name;
1419 pi.protectionLevel = bp.protectionLevel;
1420 return pi;
1421 }
1422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 public PermissionInfo getPermissionInfo(String name, int flags) {
1424 synchronized (mPackages) {
1425 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001426 if (p != null) {
1427 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429 return null;
1430 }
1431 }
1432
1433 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1434 synchronized (mPackages) {
1435 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1436 for (BasePermission p : mSettings.mPermissions.values()) {
1437 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001438 if (p.perm == null || p.perm.info.group == null) {
1439 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001442 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1444 }
1445 }
1446 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001447
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 if (out.size() > 0) {
1449 return out;
1450 }
1451 return mPermissionGroups.containsKey(group) ? out : null;
1452 }
1453 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001454
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1456 synchronized (mPackages) {
1457 return PackageParser.generatePermissionGroupInfo(
1458 mPermissionGroups.get(name), flags);
1459 }
1460 }
1461
1462 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1463 synchronized (mPackages) {
1464 final int N = mPermissionGroups.size();
1465 ArrayList<PermissionGroupInfo> out
1466 = new ArrayList<PermissionGroupInfo>(N);
1467 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1468 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1469 }
1470 return out;
1471 }
1472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001474 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1475 PackageSetting ps = mSettings.mPackages.get(packageName);
1476 if(ps != null) {
1477 if(ps.pkg == null) {
1478 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1479 if(pInfo != null) {
1480 return pInfo.applicationInfo;
1481 }
1482 return null;
1483 }
1484 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1485 }
1486 return null;
1487 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1490 PackageSetting ps = mSettings.mPackages.get(packageName);
1491 if(ps != null) {
1492 if(ps.pkg == null) {
1493 ps.pkg = new PackageParser.Package(packageName);
1494 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001495 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1496 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1497 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1498 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001499 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001500 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
1502 return generatePackageInfo(ps.pkg, flags);
1503 }
1504 return null;
1505 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1508 synchronized (mPackages) {
1509 PackageParser.Package p = mPackages.get(packageName);
1510 if (Config.LOGV) Log.v(
1511 TAG, "getApplicationInfo " + packageName
1512 + ": " + p);
1513 if (p != null) {
1514 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001515 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517 if ("android".equals(packageName)||"system".equals(packageName)) {
1518 return mAndroidApplication;
1519 }
1520 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1521 return generateApplicationInfoFromSettingsLP(packageName, flags);
1522 }
1523 }
1524 return null;
1525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001526
1527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1529 mContext.enforceCallingOrSelfPermission(
1530 android.Manifest.permission.CLEAR_APP_CACHE, null);
1531 // Queue up an async operation since clearing cache may take a little while.
1532 mHandler.post(new Runnable() {
1533 public void run() {
1534 mHandler.removeCallbacks(this);
1535 int retCode = -1;
1536 if (mInstaller != null) {
1537 retCode = mInstaller.freeCache(freeStorageSize);
1538 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001539 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541 } //end if mInstaller
1542 if (observer != null) {
1543 try {
1544 observer.onRemoveCompleted(null, (retCode >= 0));
1545 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001546 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548 }
1549 }
1550 });
1551 }
1552
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001553 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001554 mContext.enforceCallingOrSelfPermission(
1555 android.Manifest.permission.CLEAR_APP_CACHE, null);
1556 // Queue up an async operation since clearing cache may take a little while.
1557 mHandler.post(new Runnable() {
1558 public void run() {
1559 mHandler.removeCallbacks(this);
1560 int retCode = -1;
1561 if (mInstaller != null) {
1562 retCode = mInstaller.freeCache(freeStorageSize);
1563 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001564 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001565 }
1566 }
1567 if(pi != null) {
1568 try {
1569 // Callback via pending intent
1570 int code = (retCode >= 0) ? 1 : 0;
1571 pi.sendIntent(null, code, null,
1572 null, null);
1573 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001574 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001575 }
1576 }
1577 }
1578 });
1579 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1582 synchronized (mPackages) {
1583 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001584
1585 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001587 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 }
1589 if (mResolveComponentName.equals(component)) {
1590 return mResolveActivity;
1591 }
1592 }
1593 return null;
1594 }
1595
1596 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1597 synchronized (mPackages) {
1598 PackageParser.Activity a = mReceivers.mActivities.get(component);
1599 if (Config.LOGV) Log.v(
1600 TAG, "getReceiverInfo " + component + ": " + a);
1601 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1602 return PackageParser.generateActivityInfo(a, flags);
1603 }
1604 }
1605 return null;
1606 }
1607
1608 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1609 synchronized (mPackages) {
1610 PackageParser.Service s = mServices.mServices.get(component);
1611 if (Config.LOGV) Log.v(
1612 TAG, "getServiceInfo " + component + ": " + s);
1613 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1614 return PackageParser.generateServiceInfo(s, flags);
1615 }
1616 }
1617 return null;
1618 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001619
Dianne Hackborn361199b2010-08-30 17:42:07 -07001620 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1621 synchronized (mPackages) {
1622 PackageParser.Provider p = mProvidersByComponent.get(component);
1623 if (Config.LOGV) Log.v(
1624 TAG, "getProviderInfo " + component + ": " + p);
1625 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1626 return PackageParser.generateProviderInfo(p, flags);
1627 }
1628 }
1629 return null;
1630 }
1631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001632 public String[] getSystemSharedLibraryNames() {
1633 Set<String> libSet;
1634 synchronized (mPackages) {
1635 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001636 int size = libSet.size();
1637 if (size > 0) {
1638 String[] libs = new String[size];
1639 libSet.toArray(libs);
1640 return libs;
1641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001642 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001643 return null;
1644 }
1645
1646 public FeatureInfo[] getSystemAvailableFeatures() {
1647 Collection<FeatureInfo> featSet;
1648 synchronized (mPackages) {
1649 featSet = mAvailableFeatures.values();
1650 int size = featSet.size();
1651 if (size > 0) {
1652 FeatureInfo[] features = new FeatureInfo[size+1];
1653 featSet.toArray(features);
1654 FeatureInfo fi = new FeatureInfo();
1655 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1656 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1657 features[size] = fi;
1658 return features;
1659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
1661 return null;
1662 }
1663
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001664 public boolean hasSystemFeature(String name) {
1665 synchronized (mPackages) {
1666 return mAvailableFeatures.containsKey(name);
1667 }
1668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 public int checkPermission(String permName, String pkgName) {
1671 synchronized (mPackages) {
1672 PackageParser.Package p = mPackages.get(pkgName);
1673 if (p != null && p.mExtras != null) {
1674 PackageSetting ps = (PackageSetting)p.mExtras;
1675 if (ps.sharedUser != null) {
1676 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1677 return PackageManager.PERMISSION_GRANTED;
1678 }
1679 } else if (ps.grantedPermissions.contains(permName)) {
1680 return PackageManager.PERMISSION_GRANTED;
1681 }
1682 }
1683 }
1684 return PackageManager.PERMISSION_DENIED;
1685 }
1686
1687 public int checkUidPermission(String permName, int uid) {
1688 synchronized (mPackages) {
1689 Object obj = mSettings.getUserIdLP(uid);
1690 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001691 GrantedPermissions gp = (GrantedPermissions)obj;
1692 if (gp.grantedPermissions.contains(permName)) {
1693 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 }
1695 } else {
1696 HashSet<String> perms = mSystemPermissions.get(uid);
1697 if (perms != null && perms.contains(permName)) {
1698 return PackageManager.PERMISSION_GRANTED;
1699 }
1700 }
1701 }
1702 return PackageManager.PERMISSION_DENIED;
1703 }
1704
1705 private BasePermission findPermissionTreeLP(String permName) {
1706 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1707 if (permName.startsWith(bp.name) &&
1708 permName.length() > bp.name.length() &&
1709 permName.charAt(bp.name.length()) == '.') {
1710 return bp;
1711 }
1712 }
1713 return null;
1714 }
1715
1716 private BasePermission checkPermissionTreeLP(String permName) {
1717 if (permName != null) {
1718 BasePermission bp = findPermissionTreeLP(permName);
1719 if (bp != null) {
1720 if (bp.uid == Binder.getCallingUid()) {
1721 return bp;
1722 }
1723 throw new SecurityException("Calling uid "
1724 + Binder.getCallingUid()
1725 + " is not allowed to add to permission tree "
1726 + bp.name + " owned by uid " + bp.uid);
1727 }
1728 }
1729 throw new SecurityException("No permission tree found for " + permName);
1730 }
1731
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001732 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1733 if (s1 == null) {
1734 return s2 == null;
1735 }
1736 if (s2 == null) {
1737 return false;
1738 }
1739 if (s1.getClass() != s2.getClass()) {
1740 return false;
1741 }
1742 return s1.equals(s2);
1743 }
1744
1745 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1746 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001747 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001748 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1749 if (!compareStrings(pi1.name, pi2.name)) return false;
1750 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1751 // We'll take care of setting this one.
1752 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1753 // These are not currently stored in settings.
1754 //if (!compareStrings(pi1.group, pi2.group)) return false;
1755 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1756 //if (pi1.labelRes != pi2.labelRes) return false;
1757 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1758 return true;
1759 }
1760
1761 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1762 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1763 throw new SecurityException("Label must be specified in permission");
1764 }
1765 BasePermission tree = checkPermissionTreeLP(info.name);
1766 BasePermission bp = mSettings.mPermissions.get(info.name);
1767 boolean added = bp == null;
1768 boolean changed = true;
1769 if (added) {
1770 bp = new BasePermission(info.name, tree.sourcePackage,
1771 BasePermission.TYPE_DYNAMIC);
1772 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1773 throw new SecurityException(
1774 "Not allowed to modify non-dynamic permission "
1775 + info.name);
1776 } else {
1777 if (bp.protectionLevel == info.protectionLevel
1778 && bp.perm.owner.equals(tree.perm.owner)
1779 && bp.uid == tree.uid
1780 && comparePermissionInfos(bp.perm.info, info)) {
1781 changed = false;
1782 }
1783 }
1784 bp.protectionLevel = info.protectionLevel;
1785 bp.perm = new PackageParser.Permission(tree.perm.owner,
1786 new PermissionInfo(info));
1787 bp.perm.info.packageName = tree.perm.info.packageName;
1788 bp.uid = tree.uid;
1789 if (added) {
1790 mSettings.mPermissions.put(info.name, bp);
1791 }
1792 if (changed) {
1793 if (!async) {
1794 mSettings.writeLP();
1795 } else {
1796 scheduleWriteSettingsLocked();
1797 }
1798 }
1799 return added;
1800 }
1801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 public boolean addPermission(PermissionInfo info) {
1803 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001804 return addPermissionLocked(info, false);
1805 }
1806 }
1807
1808 public boolean addPermissionAsync(PermissionInfo info) {
1809 synchronized (mPackages) {
1810 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001811 }
1812 }
1813
1814 public void removePermission(String name) {
1815 synchronized (mPackages) {
1816 checkPermissionTreeLP(name);
1817 BasePermission bp = mSettings.mPermissions.get(name);
1818 if (bp != null) {
1819 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1820 throw new SecurityException(
1821 "Not allowed to modify non-dynamic permission "
1822 + name);
1823 }
1824 mSettings.mPermissions.remove(name);
1825 mSettings.writeLP();
1826 }
1827 }
1828 }
1829
Dianne Hackborn854060af2009-07-09 18:14:31 -07001830 public boolean isProtectedBroadcast(String actionName) {
1831 synchronized (mPackages) {
1832 return mProtectedBroadcasts.contains(actionName);
1833 }
1834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001835
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 public int checkSignatures(String pkg1, String pkg2) {
1837 synchronized (mPackages) {
1838 PackageParser.Package p1 = mPackages.get(pkg1);
1839 PackageParser.Package p2 = mPackages.get(pkg2);
1840 if (p1 == null || p1.mExtras == null
1841 || p2 == null || p2.mExtras == null) {
1842 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1843 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001844 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846 }
1847
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001848 public int checkUidSignatures(int uid1, int uid2) {
1849 synchronized (mPackages) {
1850 Signature[] s1;
1851 Signature[] s2;
1852 Object obj = mSettings.getUserIdLP(uid1);
1853 if (obj != null) {
1854 if (obj instanceof SharedUserSetting) {
1855 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1856 } else if (obj instanceof PackageSetting) {
1857 s1 = ((PackageSetting)obj).signatures.mSignatures;
1858 } else {
1859 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1860 }
1861 } else {
1862 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1863 }
1864 obj = mSettings.getUserIdLP(uid2);
1865 if (obj != null) {
1866 if (obj instanceof SharedUserSetting) {
1867 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1868 } else if (obj instanceof PackageSetting) {
1869 s2 = ((PackageSetting)obj).signatures.mSignatures;
1870 } else {
1871 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1872 }
1873 } else {
1874 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1875 }
1876 return checkSignaturesLP(s1, s2);
1877 }
1878 }
1879
1880 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1881 if (s1 == null) {
1882 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1884 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1885 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001886 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1888 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001889 HashSet<Signature> set1 = new HashSet<Signature>();
1890 for (Signature sig : s1) {
1891 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001893 HashSet<Signature> set2 = new HashSet<Signature>();
1894 for (Signature sig : s2) {
1895 set2.add(sig);
1896 }
1897 // Make sure s2 contains all signatures in s1.
1898 if (set1.equals(set2)) {
1899 return PackageManager.SIGNATURE_MATCH;
1900 }
1901 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
1903
1904 public String[] getPackagesForUid(int uid) {
1905 synchronized (mPackages) {
1906 Object obj = mSettings.getUserIdLP(uid);
1907 if (obj instanceof SharedUserSetting) {
1908 SharedUserSetting sus = (SharedUserSetting)obj;
1909 final int N = sus.packages.size();
1910 String[] res = new String[N];
1911 Iterator<PackageSetting> it = sus.packages.iterator();
1912 int i=0;
1913 while (it.hasNext()) {
1914 res[i++] = it.next().name;
1915 }
1916 return res;
1917 } else if (obj instanceof PackageSetting) {
1918 PackageSetting ps = (PackageSetting)obj;
1919 return new String[] { ps.name };
1920 }
1921 }
1922 return null;
1923 }
1924
1925 public String getNameForUid(int uid) {
1926 synchronized (mPackages) {
1927 Object obj = mSettings.getUserIdLP(uid);
1928 if (obj instanceof SharedUserSetting) {
1929 SharedUserSetting sus = (SharedUserSetting)obj;
1930 return sus.name + ":" + sus.userId;
1931 } else if (obj instanceof PackageSetting) {
1932 PackageSetting ps = (PackageSetting)obj;
1933 return ps.name;
1934 }
1935 }
1936 return null;
1937 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001938
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 public int getUidForSharedUser(String sharedUserName) {
1940 if(sharedUserName == null) {
1941 return -1;
1942 }
1943 synchronized (mPackages) {
1944 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1945 if(suid == null) {
1946 return -1;
1947 }
1948 return suid.userId;
1949 }
1950 }
1951
1952 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1953 int flags) {
1954 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001955 return chooseBestActivity(intent, resolvedType, flags, query);
1956 }
1957
Mihai Predaeae850c2009-05-13 10:13:48 +02001958 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1959 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 if (query != null) {
1961 final int N = query.size();
1962 if (N == 1) {
1963 return query.get(0);
1964 } else if (N > 1) {
1965 // If there is more than one activity with the same priority,
1966 // then let the user decide between them.
1967 ResolveInfo r0 = query.get(0);
1968 ResolveInfo r1 = query.get(1);
1969 if (false) {
1970 System.out.println(r0.activityInfo.name +
1971 "=" + r0.priority + " vs " +
1972 r1.activityInfo.name +
1973 "=" + r1.priority);
1974 }
1975 // If the first activity has a higher priority, or a different
1976 // default, then it is always desireable to pick it.
1977 if (r0.priority != r1.priority
1978 || r0.preferredOrder != r1.preferredOrder
1979 || r0.isDefault != r1.isDefault) {
1980 return query.get(0);
1981 }
1982 // If we have saved a preference for a preferred activity for
1983 // this Intent, use that.
1984 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1985 flags, query, r0.priority);
1986 if (ri != null) {
1987 return ri;
1988 }
1989 return mResolveInfo;
1990 }
1991 }
1992 return null;
1993 }
1994
1995 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1996 int flags, List<ResolveInfo> query, int priority) {
1997 synchronized (mPackages) {
1998 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1999 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02002000 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2002 if (prefs != null && prefs.size() > 0) {
2003 // First figure out how good the original match set is.
2004 // We will only allow preferred activities that came
2005 // from the same match quality.
2006 int match = 0;
2007 final int N = query.size();
2008 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2009 for (int j=0; j<N; j++) {
2010 ResolveInfo ri = query.get(j);
2011 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2012 + ": 0x" + Integer.toHexString(match));
2013 if (ri.match > match) match = ri.match;
2014 }
2015 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2016 + Integer.toHexString(match));
2017 match &= IntentFilter.MATCH_CATEGORY_MASK;
2018 final int M = prefs.size();
2019 for (int i=0; i<M; i++) {
2020 PreferredActivity pa = prefs.get(i);
2021 if (pa.mMatch != match) {
2022 continue;
2023 }
2024 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2025 if (DEBUG_PREFERRED) {
2026 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002027 if (ai != null) {
2028 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2029 } else {
2030 Log.v(TAG, " null");
2031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 }
2033 if (ai != null) {
2034 for (int j=0; j<N; j++) {
2035 ResolveInfo ri = query.get(j);
2036 if (!ri.activityInfo.applicationInfo.packageName
2037 .equals(ai.applicationInfo.packageName)) {
2038 continue;
2039 }
2040 if (!ri.activityInfo.name.equals(ai.name)) {
2041 continue;
2042 }
2043
2044 // Okay we found a previously set preferred app.
2045 // If the result set is different from when this
2046 // was created, we need to clear it and re-ask the
2047 // user their preference.
2048 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002049 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 + intent + " type " + resolvedType);
2051 mSettings.mPreferredActivities.removeFilter(pa);
2052 return null;
2053 }
2054
2055 // Yay!
2056 return ri;
2057 }
2058 }
2059 }
2060 }
2061 }
2062 return null;
2063 }
2064
2065 public List<ResolveInfo> queryIntentActivities(Intent intent,
2066 String resolvedType, int flags) {
2067 ComponentName comp = intent.getComponent();
2068 if (comp != null) {
2069 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2070 ActivityInfo ai = getActivityInfo(comp, flags);
2071 if (ai != null) {
2072 ResolveInfo ri = new ResolveInfo();
2073 ri.activityInfo = ai;
2074 list.add(ri);
2075 }
2076 return list;
2077 }
2078
2079 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002080 String pkgName = intent.getPackage();
2081 if (pkgName == null) {
2082 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2083 resolvedType, flags);
2084 }
2085 PackageParser.Package pkg = mPackages.get(pkgName);
2086 if (pkg != null) {
2087 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2088 resolvedType, flags, pkg.activities);
2089 }
2090 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
2093
2094 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2095 Intent[] specifics, String[] specificTypes, Intent intent,
2096 String resolvedType, int flags) {
2097 final String resultsAction = intent.getAction();
2098
2099 List<ResolveInfo> results = queryIntentActivities(
2100 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2101 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2102
2103 int specificsPos = 0;
2104 int N;
2105
2106 // todo: note that the algorithm used here is O(N^2). This
2107 // isn't a problem in our current environment, but if we start running
2108 // into situations where we have more than 5 or 10 matches then this
2109 // should probably be changed to something smarter...
2110
2111 // First we go through and resolve each of the specific items
2112 // that were supplied, taking care of removing any corresponding
2113 // duplicate items in the generic resolve list.
2114 if (specifics != null) {
2115 for (int i=0; i<specifics.length; i++) {
2116 final Intent sintent = specifics[i];
2117 if (sintent == null) {
2118 continue;
2119 }
2120
2121 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2122 String action = sintent.getAction();
2123 if (resultsAction != null && resultsAction.equals(action)) {
2124 // If this action was explicitly requested, then don't
2125 // remove things that have it.
2126 action = null;
2127 }
2128 ComponentName comp = sintent.getComponent();
2129 ResolveInfo ri = null;
2130 ActivityInfo ai = null;
2131 if (comp == null) {
2132 ri = resolveIntent(
2133 sintent,
2134 specificTypes != null ? specificTypes[i] : null,
2135 flags);
2136 if (ri == null) {
2137 continue;
2138 }
2139 if (ri == mResolveInfo) {
2140 // ACK! Must do something better with this.
2141 }
2142 ai = ri.activityInfo;
2143 comp = new ComponentName(ai.applicationInfo.packageName,
2144 ai.name);
2145 } else {
2146 ai = getActivityInfo(comp, flags);
2147 if (ai == null) {
2148 continue;
2149 }
2150 }
2151
2152 // Look for any generic query activities that are duplicates
2153 // of this specific one, and remove them from the results.
2154 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2155 N = results.size();
2156 int j;
2157 for (j=specificsPos; j<N; j++) {
2158 ResolveInfo sri = results.get(j);
2159 if ((sri.activityInfo.name.equals(comp.getClassName())
2160 && sri.activityInfo.applicationInfo.packageName.equals(
2161 comp.getPackageName()))
2162 || (action != null && sri.filter.matchAction(action))) {
2163 results.remove(j);
2164 if (Config.LOGV) Log.v(
2165 TAG, "Removing duplicate item from " + j
2166 + " due to specific " + specificsPos);
2167 if (ri == null) {
2168 ri = sri;
2169 }
2170 j--;
2171 N--;
2172 }
2173 }
2174
2175 // Add this specific item to its proper place.
2176 if (ri == null) {
2177 ri = new ResolveInfo();
2178 ri.activityInfo = ai;
2179 }
2180 results.add(specificsPos, ri);
2181 ri.specificIndex = i;
2182 specificsPos++;
2183 }
2184 }
2185
2186 // Now we go through the remaining generic results and remove any
2187 // duplicate actions that are found here.
2188 N = results.size();
2189 for (int i=specificsPos; i<N-1; i++) {
2190 final ResolveInfo rii = results.get(i);
2191 if (rii.filter == null) {
2192 continue;
2193 }
2194
2195 // Iterate over all of the actions of this result's intent
2196 // filter... typically this should be just one.
2197 final Iterator<String> it = rii.filter.actionsIterator();
2198 if (it == null) {
2199 continue;
2200 }
2201 while (it.hasNext()) {
2202 final String action = it.next();
2203 if (resultsAction != null && resultsAction.equals(action)) {
2204 // If this action was explicitly requested, then don't
2205 // remove things that have it.
2206 continue;
2207 }
2208 for (int j=i+1; j<N; j++) {
2209 final ResolveInfo rij = results.get(j);
2210 if (rij.filter != null && rij.filter.hasAction(action)) {
2211 results.remove(j);
2212 if (Config.LOGV) Log.v(
2213 TAG, "Removing duplicate item from " + j
2214 + " due to action " + action + " at " + i);
2215 j--;
2216 N--;
2217 }
2218 }
2219 }
2220
2221 // If the caller didn't request filter information, drop it now
2222 // so we don't have to marshall/unmarshall it.
2223 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2224 rii.filter = null;
2225 }
2226 }
2227
2228 // Filter out the caller activity if so requested.
2229 if (caller != null) {
2230 N = results.size();
2231 for (int i=0; i<N; i++) {
2232 ActivityInfo ainfo = results.get(i).activityInfo;
2233 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2234 && caller.getClassName().equals(ainfo.name)) {
2235 results.remove(i);
2236 break;
2237 }
2238 }
2239 }
2240
2241 // If the caller didn't request filter information,
2242 // drop them now so we don't have to
2243 // marshall/unmarshall it.
2244 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2245 N = results.size();
2246 for (int i=0; i<N; i++) {
2247 results.get(i).filter = null;
2248 }
2249 }
2250
2251 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2252 return results;
2253 }
2254
2255 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2256 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002257 ComponentName comp = intent.getComponent();
2258 if (comp != null) {
2259 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2260 ActivityInfo ai = getReceiverInfo(comp, flags);
2261 if (ai != null) {
2262 ResolveInfo ri = new ResolveInfo();
2263 ri.activityInfo = ai;
2264 list.add(ri);
2265 }
2266 return list;
2267 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002270 String pkgName = intent.getPackage();
2271 if (pkgName == null) {
2272 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2273 resolvedType, flags);
2274 }
2275 PackageParser.Package pkg = mPackages.get(pkgName);
2276 if (pkg != null) {
2277 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2278 resolvedType, flags, pkg.receivers);
2279 }
2280 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
2282 }
2283
2284 public ResolveInfo resolveService(Intent intent, String resolvedType,
2285 int flags) {
2286 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2287 flags);
2288 if (query != null) {
2289 if (query.size() >= 1) {
2290 // If there is more than one service with the same priority,
2291 // just arbitrarily pick the first one.
2292 return query.get(0);
2293 }
2294 }
2295 return null;
2296 }
2297
2298 public List<ResolveInfo> queryIntentServices(Intent intent,
2299 String resolvedType, int flags) {
2300 ComponentName comp = intent.getComponent();
2301 if (comp != null) {
2302 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2303 ServiceInfo si = getServiceInfo(comp, flags);
2304 if (si != null) {
2305 ResolveInfo ri = new ResolveInfo();
2306 ri.serviceInfo = si;
2307 list.add(ri);
2308 }
2309 return list;
2310 }
2311
2312 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002313 String pkgName = intent.getPackage();
2314 if (pkgName == null) {
2315 return (List<ResolveInfo>)mServices.queryIntent(intent,
2316 resolvedType, flags);
2317 }
2318 PackageParser.Package pkg = mPackages.get(pkgName);
2319 if (pkg != null) {
2320 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2321 resolvedType, flags, pkg.services);
2322 }
2323 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002324 }
2325 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002326
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 public List<PackageInfo> getInstalledPackages(int flags) {
2328 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2329
2330 synchronized (mPackages) {
2331 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2332 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2333 while (i.hasNext()) {
2334 final PackageSetting ps = i.next();
2335 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2336 if(psPkg != null) {
2337 finalList.add(psPkg);
2338 }
2339 }
2340 }
2341 else {
2342 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2343 while (i.hasNext()) {
2344 final PackageParser.Package p = i.next();
2345 if (p.applicationInfo != null) {
2346 PackageInfo pi = generatePackageInfo(p, flags);
2347 if(pi != null) {
2348 finalList.add(pi);
2349 }
2350 }
2351 }
2352 }
2353 }
2354 return finalList;
2355 }
2356
2357 public List<ApplicationInfo> getInstalledApplications(int flags) {
2358 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2359 synchronized(mPackages) {
2360 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2361 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2362 while (i.hasNext()) {
2363 final PackageSetting ps = i.next();
2364 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2365 if(ai != null) {
2366 finalList.add(ai);
2367 }
2368 }
2369 }
2370 else {
2371 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2372 while (i.hasNext()) {
2373 final PackageParser.Package p = i.next();
2374 if (p.applicationInfo != null) {
2375 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2376 if(ai != null) {
2377 finalList.add(ai);
2378 }
2379 }
2380 }
2381 }
2382 }
2383 return finalList;
2384 }
2385
2386 public List<ApplicationInfo> getPersistentApplications(int flags) {
2387 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2388
2389 synchronized (mPackages) {
2390 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2391 while (i.hasNext()) {
2392 PackageParser.Package p = i.next();
2393 if (p.applicationInfo != null
2394 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002395 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002396 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
2398 }
2399 }
2400
2401 return finalList;
2402 }
2403
2404 public ProviderInfo resolveContentProvider(String name, int flags) {
2405 synchronized (mPackages) {
2406 final PackageParser.Provider provider = mProviders.get(name);
2407 return provider != null
2408 && mSettings.isEnabledLP(provider.info, flags)
2409 && (!mSafeMode || (provider.info.applicationInfo.flags
2410 &ApplicationInfo.FLAG_SYSTEM) != 0)
2411 ? PackageParser.generateProviderInfo(provider, flags)
2412 : null;
2413 }
2414 }
2415
Fred Quintana718d8a22009-04-29 17:53:20 -07002416 /**
2417 * @deprecated
2418 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002419 public void querySyncProviders(List outNames, List outInfo) {
2420 synchronized (mPackages) {
2421 Iterator<Map.Entry<String, PackageParser.Provider>> i
2422 = mProviders.entrySet().iterator();
2423
2424 while (i.hasNext()) {
2425 Map.Entry<String, PackageParser.Provider> entry = i.next();
2426 PackageParser.Provider p = entry.getValue();
2427
2428 if (p.syncable
2429 && (!mSafeMode || (p.info.applicationInfo.flags
2430 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2431 outNames.add(entry.getKey());
2432 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2433 }
2434 }
2435 }
2436 }
2437
2438 public List<ProviderInfo> queryContentProviders(String processName,
2439 int uid, int flags) {
2440 ArrayList<ProviderInfo> finalList = null;
2441
2442 synchronized (mPackages) {
2443 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2444 while (i.hasNext()) {
2445 PackageParser.Provider p = i.next();
2446 if (p.info.authority != null
2447 && (processName == null ||
2448 (p.info.processName.equals(processName)
2449 && p.info.applicationInfo.uid == uid))
2450 && mSettings.isEnabledLP(p.info, flags)
2451 && (!mSafeMode || (p.info.applicationInfo.flags
2452 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2453 if (finalList == null) {
2454 finalList = new ArrayList<ProviderInfo>(3);
2455 }
2456 finalList.add(PackageParser.generateProviderInfo(p,
2457 flags));
2458 }
2459 }
2460 }
2461
2462 if (finalList != null) {
2463 Collections.sort(finalList, mProviderInitOrderSorter);
2464 }
2465
2466 return finalList;
2467 }
2468
2469 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2470 int flags) {
2471 synchronized (mPackages) {
2472 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2473 return PackageParser.generateInstrumentationInfo(i, flags);
2474 }
2475 }
2476
2477 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2478 int flags) {
2479 ArrayList<InstrumentationInfo> finalList =
2480 new ArrayList<InstrumentationInfo>();
2481
2482 synchronized (mPackages) {
2483 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2484 while (i.hasNext()) {
2485 PackageParser.Instrumentation p = i.next();
2486 if (targetPackage == null
2487 || targetPackage.equals(p.info.targetPackage)) {
2488 finalList.add(PackageParser.generateInstrumentationInfo(p,
2489 flags));
2490 }
2491 }
2492 }
2493
2494 return finalList;
2495 }
2496
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002497 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 String[] files = dir.list();
Dianne Hackborn3b4bac72010-09-20 11:37:52 -07002499 if (files == null) {
2500 Log.d(TAG, "No files in app dir " + dir);
2501 return;
2502 }
2503
Joe Onorato431bb222010-10-18 19:13:23 -04002504 if (false) {
2505 Log.d(TAG, "Scanning app dir " + dir);
2506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507
2508 int i;
2509 for (i=0; i<files.length; i++) {
2510 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002511 if (!isPackageFilename(files[i])) {
2512 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002513 continue;
2514 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002515 PackageParser.Package pkg = scanPackageLI(file,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002516 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002517 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002518 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2519 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002520 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002521 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002522 file.delete();
2523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 }
2525 }
2526
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002527 private static File getSettingsProblemFile() {
2528 File dataDir = Environment.getDataDirectory();
2529 File systemDir = new File(dataDir, "system");
2530 File fname = new File(systemDir, "uiderrors.txt");
2531 return fname;
2532 }
2533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 private static void reportSettingsProblem(int priority, String msg) {
2535 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002536 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 FileOutputStream out = new FileOutputStream(fname, true);
2538 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002539 SimpleDateFormat formatter = new SimpleDateFormat();
2540 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2541 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 pw.close();
2543 FileUtils.setPermissions(
2544 fname.toString(),
2545 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2546 -1, -1);
2547 } catch (java.io.IOException e) {
2548 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002549 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002550 }
2551
2552 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2553 PackageParser.Package pkg, File srcFile, int parseFlags) {
2554 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002555 if (ps != null
2556 && ps.codePath.equals(srcFile)
Kenny Root7d794fb2010-09-13 16:29:49 -07002557 && ps.timeStamp == srcFile.lastModified()) {
Jeff Browne7600722010-04-07 18:28:23 -07002558 if (ps.signatures.mSignatures != null
2559 && ps.signatures.mSignatures.length != 0) {
2560 // Optimization: reuse the existing cached certificates
2561 // if the package appears to be unchanged.
2562 pkg.mSignatures = ps.signatures.mSignatures;
2563 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
Jeff Browne7600722010-04-07 18:28:23 -07002565
2566 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002567 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002568 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2569 }
2570
2571 if (!pp.collectCertificates(pkg, parseFlags)) {
2572 mLastScanError = pp.getParseError();
2573 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002574 }
2575 }
2576 return true;
2577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 /*
2580 * Scan a package and return the newly parsed package.
2581 * Returns null in case of errors and the error code is stored in mLastScanError
2582 */
2583 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002584 int parseFlags, int scanMode, long currentTime) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002586 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002588 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002590 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 if (pkg == null) {
2593 mLastScanError = pp.getParseError();
2594 return null;
2595 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002596 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597 PackageSetting updatedPkg;
2598 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002599 // Look to see if we already know about this package.
2600 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002601 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002602 // This package has been renamed to its original name. Let's
2603 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002604 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002605 }
2606 // If there was no original package, see one for the real package name.
2607 if (ps == null) {
2608 ps = mSettings.peekPackageLP(pkg.packageName);
2609 }
2610 // Check to see if this package could be hiding/updating a system
2611 // package. Must look for it either under the original or real
2612 // package name depending on our state.
2613 updatedPkg = mSettings.mDisabledSysPackages.get(
2614 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002615 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 // First check if this is a system package that may involve an update
2617 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002618 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 // The path has changed from what was last scanned... check the
2620 // version of the new path against what we have stored to determine
2621 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002622 if (pkg.mVersionCode < ps.versionCode) {
2623 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002624 // Ignore entry. Skip it.
2625 Log.i(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborncef65ee2010-09-30 18:27:22 -07002626 + " ignored: updated version " + ps.versionCode
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002627 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002628 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2629 return null;
2630 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002631 // The current app on the system partion is better than
2632 // what we have updated to on the data partition; switch
2633 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002634 // At this point, its safely assumed that package installation for
2635 // apps in system partition will go through. If not there won't be a working
2636 // version of the app
2637 synchronized (mPackages) {
2638 // Just remove the loaded entries from package lists.
2639 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002640 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002641 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002642 + "reverting from " + ps.codePathString
2643 + ": new version " + pkg.mVersionCode
2644 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002645 InstallArgs args = new FileInstallArgs(ps.codePathString,
2646 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002647 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002648 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002649 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002650 }
2651 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002652 if (updatedPkg != null) {
2653 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2654 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2655 }
2656 // Verify certificates against what was last scanned
2657 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002658 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002659 return null;
2660 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002661 // The apk is forward locked (not public) if its code and resources
2662 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002663 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002665 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002666 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002667
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002668 String codePath = null;
2669 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002670 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2671 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002672 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002673 } else {
2674 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002675 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002676 }
2677 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002678 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002679 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002680 codePath = pkg.mScanPath;
2681 // Set application objects path explicitly.
2682 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 // Note that we invoke the following method only if we are about to unpack an application
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002684 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE, currentTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685 }
2686
Kenny Root85387d72010-08-26 10:13:11 -07002687 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2688 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002689 pkg.mPath = pkg.mScanPath = destCodePath;
2690 pkg.applicationInfo.sourceDir = destCodePath;
2691 pkg.applicationInfo.publicSourceDir = destResPath;
2692 }
2693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 private static String fixProcessName(String defProcessName,
2695 String processName, int uid) {
2696 if (processName == null) {
2697 return defProcessName;
2698 }
2699 return processName;
2700 }
2701
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002702 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002703 PackageParser.Package pkg) {
2704 if (pkgSetting.signatures.mSignatures != null) {
2705 // Already existing package. Make sure signatures match
2706 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2707 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002708 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002709 + " signatures do not match the previously installed version; ignoring!");
2710 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 return false;
2712 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002713 }
2714 // Check for shared user signatures
2715 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2716 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2717 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2718 Slog.e(TAG, "Package " + pkg.packageName
2719 + " has no signatures that match those in shared user "
2720 + pkgSetting.sharedUser.name + "; ignoring!");
2721 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2722 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724 }
2725 return true;
2726 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002727
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002728 public boolean performDexOpt(String packageName) {
2729 if (!mNoDexOpt) {
2730 return false;
2731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002733 PackageParser.Package p;
2734 synchronized (mPackages) {
2735 p = mPackages.get(packageName);
2736 if (p == null || p.mDidDexOpt) {
2737 return false;
2738 }
2739 }
2740 synchronized (mInstallLock) {
2741 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2742 }
2743 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002744
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002745 static final int DEX_OPT_SKIPPED = 0;
2746 static final int DEX_OPT_PERFORMED = 1;
2747 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002748
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002749 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2750 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002751 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002752 String path = pkg.mScanPath;
2753 int ret = 0;
2754 try {
2755 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002756 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002757 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002758 pkg.mDidDexOpt = true;
2759 performed = true;
2760 }
2761 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002762 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002763 ret = -1;
2764 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002765 Slog.w(TAG, "IOException reading apk: " + path, e);
2766 ret = -1;
2767 } catch (dalvik.system.StaleDexCacheError e) {
2768 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2769 ret = -1;
2770 } catch (Exception e) {
2771 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002772 ret = -1;
2773 }
2774 if (ret < 0) {
2775 //error from installer
2776 return DEX_OPT_FAILED;
2777 }
2778 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002779
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002780 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2781 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002782
2783 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2784 return Environment.isEncryptedFilesystemEnabled() &&
2785 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2786 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002787
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002788 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2789 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002790 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002791 + " to " + newPkg.packageName
2792 + ": old package not in system partition");
2793 return false;
2794 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002795 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002796 + " to " + newPkg.packageName
2797 + ": old package still exists");
2798 return false;
2799 }
2800 return true;
2801 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002802
2803 private File getDataPathForPackage(PackageParser.Package pkg) {
2804 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2805 File dataPath;
2806 if (useEncryptedFSDir) {
2807 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2808 } else {
2809 dataPath = new File(mAppDataDir, pkg.packageName);
2810 }
2811 return dataPath;
2812 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002813
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002814 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07002815 int parseFlags, int scanMode, long currentTime) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002816 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002817 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2818 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002819 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002820 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002821 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2822 return null;
2823 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 mScanningPath = scanFile;
2825 if (pkg == null) {
2826 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2827 return null;
2828 }
2829
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002830 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2831 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2832 }
2833
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002834 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835 synchronized (mPackages) {
2836 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002837 Slog.w(TAG, "*************************************************");
2838 Slog.w(TAG, "Core android package being redefined. Skipping.");
2839 Slog.w(TAG, " file=" + mScanningPath);
2840 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2842 return null;
2843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 // Set up information for our fall-back user intent resolution
2846 // activity.
2847 mPlatformPackage = pkg;
2848 pkg.mVersionCode = mSdkVersion;
2849 mAndroidApplication = pkg.applicationInfo;
2850 mResolveActivity.applicationInfo = mAndroidApplication;
2851 mResolveActivity.name = ResolverActivity.class.getName();
2852 mResolveActivity.packageName = mAndroidApplication.packageName;
2853 mResolveActivity.processName = mAndroidApplication.processName;
2854 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2855 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
Joe Onorato646f46e2010-11-08 15:08:56 -08002856 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 mResolveActivity.exported = true;
2858 mResolveActivity.enabled = true;
2859 mResolveInfo.activityInfo = mResolveActivity;
2860 mResolveInfo.priority = 0;
2861 mResolveInfo.preferredOrder = 0;
2862 mResolveInfo.match = 0;
2863 mResolveComponentName = new ComponentName(
2864 mAndroidApplication.packageName, mResolveActivity.name);
2865 }
2866 }
2867
2868 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002869 TAG, "Scanning package " + pkg.packageName);
2870 if (mPackages.containsKey(pkg.packageName)
2871 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002872 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 + " already installed. Skipping duplicate.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2875 return null;
2876 }
2877
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002878 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002879 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2880 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 SharedUserSetting suid = null;
2883 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002884
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002885 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2886 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002887 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002888 pkg.mRealPackage = null;
2889 pkg.mAdoptPermissions = null;
2890 }
2891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 synchronized (mPackages) {
2893 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002894 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2895 if (mTmpSharedLibraries == null ||
2896 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2897 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2898 }
2899 int num = 0;
2900 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2901 for (int i=0; i<N; i++) {
2902 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002904 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002906 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002907 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2908 return null;
2909 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002910 mTmpSharedLibraries[num] = file;
2911 num++;
2912 }
2913 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2914 for (int i=0; i<N; i++) {
2915 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2916 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002917 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002918 + " desires unavailable shared library "
2919 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2920 } else {
2921 mTmpSharedLibraries[num] = file;
2922 num++;
2923 }
2924 }
2925 if (num > 0) {
2926 pkg.usesLibraryFiles = new String[num];
2927 System.arraycopy(mTmpSharedLibraries, 0,
2928 pkg.usesLibraryFiles, 0, num);
2929 }
Kenny Root1683afa2011-01-07 14:27:50 -08002930 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002931
Kenny Root1683afa2011-01-07 14:27:50 -08002932 if (pkg.reqFeatures != null) {
2933 int N = pkg.reqFeatures.size();
2934 for (int i = 0; i < N; i++) {
2935 FeatureInfo fi = pkg.reqFeatures.get(i);
2936 if ((fi.flags & FeatureInfo.FLAG_REQUIRED) == 0) {
2937 // Don't care.
2938 continue;
2939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002940
Kenny Root1683afa2011-01-07 14:27:50 -08002941 if (fi.name != null) {
2942 if (mAvailableFeatures.get(fi.name) == null) {
2943 Slog.e(TAG, "Package " + pkg.packageName
2944 + " requires unavailable feature " + fi.name + "; failing!");
2945 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2946 return null;
Dianne Hackborn49237342009-08-27 20:08:01 -07002947 }
2948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 }
2950 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 if (pkg.mSharedUserId != null) {
2953 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2954 pkg.applicationInfo.flags, true);
2955 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002956 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 + " for shared user failed");
2958 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2959 return null;
2960 }
2961 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2962 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2963 + suid.userId + "): packages=" + suid.packages);
2964 }
2965 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002966
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002967 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002968 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002969 Log.w(TAG, "WAITING FOR DEBUGGER");
2970 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002971 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2972 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973 }
2974 }
2975
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002976 // Check if we are renaming from an original package name.
2977 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002978 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002979 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002980 // This package may need to be renamed to a previously
2981 // installed name. Let's check on that...
2982 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002983 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002984 // This package had originally been installed as the
2985 // original name, and we have already taken care of
2986 // transitioning to the new one. Just update the new
2987 // one to continue using the old name.
2988 realName = pkg.mRealPackage;
2989 if (!pkg.packageName.equals(renamed)) {
2990 // Callers into this function may have already taken
2991 // care of renaming the package; only do it here if
2992 // it is not already done.
2993 pkg.setPackageName(renamed);
2994 }
2995
Dianne Hackbornc1552392010-03-03 16:19:01 -08002996 } else {
2997 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2998 if ((origPackage=mSettings.peekPackageLP(
2999 pkg.mOriginalPackages.get(i))) != null) {
3000 // We do have the package already installed under its
3001 // original name... should we use it?
3002 if (!verifyPackageUpdate(origPackage, pkg)) {
3003 // New package is not compatible with original.
3004 origPackage = null;
3005 continue;
3006 } else if (origPackage.sharedUser != null) {
3007 // Make sure uid is compatible between packages.
3008 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003009 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003010 + " to " + pkg.packageName + ": old uid "
3011 + origPackage.sharedUser.name
3012 + " differs from " + pkg.mSharedUserId);
3013 origPackage = null;
3014 continue;
3015 }
3016 } else {
3017 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3018 + pkg.packageName + " to old name " + origPackage.name);
3019 }
3020 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003021 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003022 }
3023 }
3024 }
3025
3026 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003027 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003028 + " was transferred to another, but its .apk remains");
3029 }
3030
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003031 // Just create the setting, don't add it yet. For already existing packages
3032 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003033 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003034 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3035 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003036 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003037 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003038 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3039 return null;
3040 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003041
3042 if (pkgSetting.origPackage != null) {
3043 // If we are first transitioning from an original package,
3044 // fix up the new package's name now. We need to do this after
3045 // looking up the package under its new name, so getPackageLP
3046 // can take care of fiddling things correctly.
3047 pkg.setPackageName(origPackage.name);
3048
3049 // File a report about this.
3050 String msg = "New package " + pkgSetting.realName
3051 + " renamed to replace old package " + pkgSetting.name;
3052 reportSettingsProblem(Log.WARN, msg);
3053
3054 // Make a note of it.
3055 mTransferedPackages.add(origPackage.name);
3056
3057 // No longer need to retain this.
3058 pkgSetting.origPackage = null;
3059 }
3060
3061 if (realName != null) {
3062 // Make a note of it.
3063 mTransferedPackages.add(pkg.packageName);
3064 }
3065
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003066 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003067 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3068 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 pkg.applicationInfo.uid = pkgSetting.userId;
3071 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003072
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003073 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003074 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 return null;
3076 }
3077 // The signature has changed, but this package is in the system
3078 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003079 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 // However... if this package is part of a shared user, but it
3081 // doesn't match the signature of the shared user, let's fail.
3082 // What this means is that you can't change the signatures
3083 // associated with an overall shared user, which doesn't seem all
3084 // that unreasonable.
3085 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003086 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3087 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3088 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3090 return null;
3091 }
3092 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003093 // File a report about this.
3094 String msg = "System package " + pkg.packageName
3095 + " signature changed; retaining data.";
3096 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003098
The Android Open Source Project10592532009-03-18 17:39:46 -07003099 // Verify that this new package doesn't have any content providers
3100 // that conflict with existing packages. Only do this if the
3101 // package isn't already installed, since we don't want to break
3102 // things that are installed.
3103 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3104 int N = pkg.providers.size();
3105 int i;
3106 for (i=0; i<N; i++) {
3107 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003108 if (p.info.authority != null) {
3109 String names[] = p.info.authority.split(";");
3110 for (int j = 0; j < names.length; j++) {
3111 if (mProviders.containsKey(names[j])) {
3112 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003113 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003114 " (in package " + pkg.applicationInfo.packageName +
3115 ") is already used by "
3116 + ((other != null && other.getComponentName() != null)
3117 ? other.getComponentName().getPackageName() : "?"));
3118 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3119 return null;
3120 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003121 }
3122 }
3123 }
3124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 }
3126
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003127 final String pkgName = pkg.packageName;
3128
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003129 if (pkg.mAdoptPermissions != null) {
3130 // This package wants to adopt ownership of permissions from
3131 // another package.
3132 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3133 String origName = pkg.mAdoptPermissions.get(i);
3134 PackageSetting orig = mSettings.peekPackageLP(origName);
3135 if (orig != null) {
3136 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003137 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003138 + origName + " to " + pkg.packageName);
3139 mSettings.transferPermissions(origName, pkg.packageName);
3140 }
3141 }
3142 }
3143 }
3144
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003145 final long scanFileTime = scanFile.lastModified();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
Kenny Root7d794fb2010-09-13 16:29:49 -07003147 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.timeStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 pkg.applicationInfo.processName = fixProcessName(
3149 pkg.applicationInfo.packageName,
3150 pkg.applicationInfo.processName,
3151 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003152
3153 File dataPath;
3154 if (mPlatformPackage == pkg) {
3155 // The system package is special.
3156 dataPath = new File (Environment.getDataDirectory(), "system");
3157 pkg.applicationInfo.dataDir = dataPath.getPath();
3158 } else {
3159 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003160 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003161 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003162
3163 boolean uidError = false;
3164
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 if (dataPath.exists()) {
3166 mOutPermissions[1] = 0;
3167 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003168
3169 // If we have mismatched owners for the data path, we have a
3170 // problem (unless we're running in the simulator.)
3171 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 boolean recovered = false;
3173 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3174 // If this is a system app, we can at least delete its
3175 // current data so the application will still work.
3176 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003177 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003178 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 // Old data gone!
3180 String msg = "System package " + pkg.packageName
3181 + " has changed from uid: "
3182 + mOutPermissions[1] + " to "
3183 + pkg.applicationInfo.uid + "; old data erased";
3184 reportSettingsProblem(Log.WARN, msg);
3185 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003186
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003187 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003188 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 pkg.applicationInfo.uid);
3190 if (ret == -1) {
3191 // Ack should not happen!
3192 msg = "System package " + pkg.packageName
3193 + " could not have data directory re-created after delete.";
3194 reportSettingsProblem(Log.WARN, msg);
3195 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3196 return null;
3197 }
3198 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 if (!recovered) {
3201 mHasSystemUidErrors = true;
3202 }
3203 }
3204 if (!recovered) {
3205 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3206 + pkg.applicationInfo.uid + "/fs_"
3207 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003208 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 String msg = "Package " + pkg.packageName
3210 + " has mismatched uid: "
3211 + mOutPermissions[1] + " on disk, "
3212 + pkg.applicationInfo.uid + " in settings";
3213 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003214 mSettings.mReadMessages.append(msg);
3215 mSettings.mReadMessages.append('\n');
3216 uidError = true;
3217 if (!pkgSetting.uidError) {
3218 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 }
3221 }
3222 }
3223 pkg.applicationInfo.dataDir = dataPath.getPath();
3224 } else {
3225 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3226 Log.v(TAG, "Want this data dir: " + dataPath);
3227 //invoke installer to do the actual installation
3228 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003229 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 pkg.applicationInfo.uid);
3231 if(ret < 0) {
3232 // Error from installer
3233 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3234 return null;
3235 }
3236 } else {
3237 dataPath.mkdirs();
3238 if (dataPath.exists()) {
3239 FileUtils.setPermissions(
3240 dataPath.toString(),
3241 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3242 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3243 }
3244 }
3245 if (dataPath.exists()) {
3246 pkg.applicationInfo.dataDir = dataPath.getPath();
3247 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003248 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 pkg.applicationInfo.dataDir = null;
3250 }
3251 }
Kenny Root85387d72010-08-26 10:13:11 -07003252
3253 /*
3254 * Set the data dir to the default "/data/data/<package name>/lib"
3255 * if we got here without anyone telling us different (e.g., apps
3256 * stored on SD card have their native libraries stored in the ASEC
3257 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003258 *
3259 * This happens during an upgrade from a package settings file that
3260 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003261 */
Kenny Rootbd135c12010-10-05 12:26:27 -07003262 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3263 if (pkgSetting.nativeLibraryPathString == null) {
3264 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3265 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3266 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
3267 } else {
3268 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3269 }
Kenny Root85387d72010-08-26 10:13:11 -07003270 }
3271
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003272 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 }
3274
Kenny Root85387d72010-08-26 10:13:11 -07003275 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003276 if (mInstaller != null) {
3277 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003278 /* Note: We don't want to unpack the native binaries for
3279 * system applications, unless they have been updated
3280 * (the binaries are already under /system/lib).
3281 * Also, don't unpack libs for apps on the external card
3282 * since they should have their libraries in the ASEC
3283 * container already.
3284 *
3285 * In other words, we're going to unpack the binaries
3286 * only for non-system apps and system app upgrades.
3287 */
Kenny Root831baa22010-10-05 12:29:25 -07003288 if (pkg.applicationInfo.nativeLibraryDir != null) {
Kenny Roote68d58a2010-10-18 16:08:54 -07003289 final File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3290 final String dataPathString = dataPath.getPath();
3291
Kenny Root831baa22010-10-05 12:29:25 -07003292 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
3293 /*
3294 * Upgrading from a previous version of the OS sometimes
3295 * leaves native libraries in the /data/data/<app>/lib
3296 * directory for system apps even when they shouldn't be.
3297 * Recent changes in the JNI library search path
3298 * necessitates we remove those to match previous behavior.
3299 */
Kenny Roote68d58a2010-10-18 16:08:54 -07003300 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
Kenny Root831baa22010-10-05 12:29:25 -07003301 Log.i(TAG, "removed obsolete native libraries for system package " + path);
3302 }
Kenny Roote68d58a2010-10-18 16:08:54 -07003303 } else if (nativeLibraryDir.getParent().equals(dataPathString)) {
3304 /*
3305 * If this is an internal application or our
3306 * nativeLibraryPath points to our data directory, unpack
3307 * the libraries. The native library path pointing to the
3308 * data directory for an application in an ASEC container
3309 * can happen for older apps that existed before an OTA to
3310 * Gingerbread.
3311 */
3312 Slog.i(TAG, "Unpacking native libraries for " + path);
3313 mInstaller.unlinkNativeLibraryDirectory(dataPathString);
3314 NativeLibraryHelper.copyNativeBinariesLI(scanFile, nativeLibraryDir);
Kenny Root6a6b0072010-10-07 16:46:10 -07003315 } else {
Kenny Roote68d58a2010-10-18 16:08:54 -07003316 Slog.i(TAG, "Linking native library dir for " + path);
3317 mInstaller.linkNativeLibraryDirectory(dataPathString,
Kenny Root6a6b0072010-10-07 16:46:10 -07003318 pkg.applicationInfo.nativeLibraryDir);
Kenny Root831baa22010-10-05 12:29:25 -07003319 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003321 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003322
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003323 if ((scanMode&SCAN_NO_DEX) == 0) {
3324 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3326 return null;
3327 }
3328 }
3329 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003330
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 if (mFactoryTest && pkg.requestedPermissions.contains(
3332 android.Manifest.permission.FACTORY_TEST)) {
3333 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3334 }
3335
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003336 // Request the ActivityManager to kill the process(only for existing packages)
3337 // so that we do not end up in a confused state while the user is still using the older
3338 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003339 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003340 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003341 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003342 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003345 // We don't expect installation to fail beyond this point,
3346 if ((scanMode&SCAN_MONITOR) != 0) {
3347 mAppDirs.put(pkg.mPath, pkg);
3348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003350 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003352 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003353 // Make sure we don't accidentally delete its data.
3354 mSettings.mPackagesToBeCleaned.remove(pkgName);
3355
Dianne Hackborn78d6883692010-10-07 01:12:46 -07003356 // Take care of first install / last update times.
3357 if (currentTime != 0) {
3358 if (pkgSetting.firstInstallTime == 0) {
3359 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
3360 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
3361 pkgSetting.lastUpdateTime = currentTime;
3362 }
3363 } else if (pkgSetting.firstInstallTime == 0) {
3364 // We need *something*. Take time time stamp of the file.
3365 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
3366 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
3367 if (scanFileTime != pkgSetting.timeStamp) {
3368 // A package on the system image has changed; consider this
3369 // to be an update.
3370 pkgSetting.lastUpdateTime = scanFileTime;
3371 }
3372 }
3373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 int N = pkg.providers.size();
3375 StringBuilder r = null;
3376 int i;
3377 for (i=0; i<N; i++) {
3378 PackageParser.Provider p = pkg.providers.get(i);
3379 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3380 p.info.processName, pkg.applicationInfo.uid);
3381 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3382 p.info.name), p);
3383 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003384 if (p.info.authority != null) {
3385 String names[] = p.info.authority.split(";");
3386 p.info.authority = null;
3387 for (int j = 0; j < names.length; j++) {
3388 if (j == 1 && p.syncable) {
3389 // We only want the first authority for a provider to possibly be
3390 // syncable, so if we already added this provider using a different
3391 // authority clear the syncable flag. We copy the provider before
3392 // changing it because the mProviders object contains a reference
3393 // to a provider that we don't want to change.
3394 // Only do this for the second authority since the resulting provider
3395 // object can be the same for all future authorities for this provider.
3396 p = new PackageParser.Provider(p);
3397 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003398 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003399 if (!mProviders.containsKey(names[j])) {
3400 mProviders.put(names[j], p);
3401 if (p.info.authority == null) {
3402 p.info.authority = names[j];
3403 } else {
3404 p.info.authority = p.info.authority + ";" + names[j];
3405 }
3406 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3407 Log.d(TAG, "Registered content provider: " + names[j] +
3408 ", className = " + p.info.name +
3409 ", isSyncable = " + p.info.isSyncable);
3410 } else {
3411 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003412 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003413 " (in package " + pkg.applicationInfo.packageName +
3414 "): name already used by "
3415 + ((other != null && other.getComponentName() != null)
3416 ? other.getComponentName().getPackageName() : "?"));
3417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 }
3419 }
3420 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3421 if (r == null) {
3422 r = new StringBuilder(256);
3423 } else {
3424 r.append(' ');
3425 }
3426 r.append(p.info.name);
3427 }
3428 }
3429 if (r != null) {
3430 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 N = pkg.services.size();
3434 r = null;
3435 for (i=0; i<N; i++) {
3436 PackageParser.Service s = pkg.services.get(i);
3437 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3438 s.info.processName, pkg.applicationInfo.uid);
3439 mServices.addService(s);
3440 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3441 if (r == null) {
3442 r = new StringBuilder(256);
3443 } else {
3444 r.append(' ');
3445 }
3446 r.append(s.info.name);
3447 }
3448 }
3449 if (r != null) {
3450 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 N = pkg.receivers.size();
3454 r = null;
3455 for (i=0; i<N; i++) {
3456 PackageParser.Activity a = pkg.receivers.get(i);
3457 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3458 a.info.processName, pkg.applicationInfo.uid);
3459 mReceivers.addActivity(a, "receiver");
3460 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3461 if (r == null) {
3462 r = new StringBuilder(256);
3463 } else {
3464 r.append(' ');
3465 }
3466 r.append(a.info.name);
3467 }
3468 }
3469 if (r != null) {
3470 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3471 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 N = pkg.activities.size();
3474 r = null;
3475 for (i=0; i<N; i++) {
3476 PackageParser.Activity a = pkg.activities.get(i);
3477 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3478 a.info.processName, pkg.applicationInfo.uid);
3479 mActivities.addActivity(a, "activity");
3480 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3481 if (r == null) {
3482 r = new StringBuilder(256);
3483 } else {
3484 r.append(' ');
3485 }
3486 r.append(a.info.name);
3487 }
3488 }
3489 if (r != null) {
3490 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3491 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 N = pkg.permissionGroups.size();
3494 r = null;
3495 for (i=0; i<N; i++) {
3496 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3497 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3498 if (cur == null) {
3499 mPermissionGroups.put(pg.info.name, pg);
3500 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3501 if (r == null) {
3502 r = new StringBuilder(256);
3503 } else {
3504 r.append(' ');
3505 }
3506 r.append(pg.info.name);
3507 }
3508 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003509 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 + pg.info.packageName + " ignored: original from "
3511 + cur.info.packageName);
3512 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3513 if (r == null) {
3514 r = new StringBuilder(256);
3515 } else {
3516 r.append(' ');
3517 }
3518 r.append("DUP:");
3519 r.append(pg.info.name);
3520 }
3521 }
3522 }
3523 if (r != null) {
3524 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3525 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 N = pkg.permissions.size();
3528 r = null;
3529 for (i=0; i<N; i++) {
3530 PackageParser.Permission p = pkg.permissions.get(i);
3531 HashMap<String, BasePermission> permissionMap =
3532 p.tree ? mSettings.mPermissionTrees
3533 : mSettings.mPermissions;
3534 p.group = mPermissionGroups.get(p.info.group);
3535 if (p.info.group == null || p.group != null) {
3536 BasePermission bp = permissionMap.get(p.info.name);
3537 if (bp == null) {
3538 bp = new BasePermission(p.info.name, p.info.packageName,
3539 BasePermission.TYPE_NORMAL);
3540 permissionMap.put(p.info.name, bp);
3541 }
3542 if (bp.perm == null) {
3543 if (bp.sourcePackage == null
3544 || bp.sourcePackage.equals(p.info.packageName)) {
3545 BasePermission tree = findPermissionTreeLP(p.info.name);
3546 if (tree == null
3547 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003548 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 bp.perm = p;
3550 bp.uid = pkg.applicationInfo.uid;
3551 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3552 if (r == null) {
3553 r = new StringBuilder(256);
3554 } else {
3555 r.append(' ');
3556 }
3557 r.append(p.info.name);
3558 }
3559 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003560 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 + p.info.packageName + " ignored: base tree "
3562 + tree.name + " is from package "
3563 + tree.sourcePackage);
3564 }
3565 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003566 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 + p.info.packageName + " ignored: original from "
3568 + bp.sourcePackage);
3569 }
3570 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3571 if (r == null) {
3572 r = new StringBuilder(256);
3573 } else {
3574 r.append(' ');
3575 }
3576 r.append("DUP:");
3577 r.append(p.info.name);
3578 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003579 if (bp.perm == p) {
3580 bp.protectionLevel = p.info.protectionLevel;
3581 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003582 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003583 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 + p.info.packageName + " ignored: no group "
3585 + p.group);
3586 }
3587 }
3588 if (r != null) {
3589 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 N = pkg.instrumentation.size();
3593 r = null;
3594 for (i=0; i<N; i++) {
3595 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3596 a.info.packageName = pkg.applicationInfo.packageName;
3597 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3598 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3599 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003600 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003601 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3603 if (r == null) {
3604 r = new StringBuilder(256);
3605 } else {
3606 r.append(' ');
3607 }
3608 r.append(a.info.name);
3609 }
3610 }
3611 if (r != null) {
3612 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003614
Dianne Hackborn854060af2009-07-09 18:14:31 -07003615 if (pkg.protectedBroadcasts != null) {
3616 N = pkg.protectedBroadcasts.size();
3617 for (i=0; i<N; i++) {
3618 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3619 }
3620 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 pkgSetting.setTimeStamp(scanFileTime);
3623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003625 return pkg;
3626 }
3627
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003628 private void killApplication(String pkgName, int uid) {
3629 // Request the ActivityManager to kill the process(only for existing packages)
3630 // so that we do not end up in a confused state while the user is still using the older
3631 // version of the application while the new one gets installed.
3632 IActivityManager am = ActivityManagerNative.getDefault();
3633 if (am != null) {
3634 try {
3635 am.killApplicationWithUid(pkgName, uid);
3636 } catch (RemoteException e) {
3637 }
3638 }
3639 }
3640
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003641 // Return the path of the directory that will contain the native binaries
3642 // of a given installed package. This is relative to the data path.
3643 //
Kenny Root85387d72010-08-26 10:13:11 -07003644 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3645 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3646 if (nativeLibraryDir != null) {
3647 return new File(nativeLibraryDir);
3648 } else {
3649 // Fall back for old packages
3650 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3651 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003652 }
3653
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003654 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3655 if (chatty && Config.LOGD) Log.d(
3656 TAG, "Removing package " + pkg.applicationInfo.packageName );
3657
3658 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003659 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003660
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 mPackages.remove(pkg.applicationInfo.packageName);
3662 if (pkg.mPath != null) {
3663 mAppDirs.remove(pkg.mPath);
3664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 int N = pkg.providers.size();
3667 StringBuilder r = null;
3668 int i;
3669 for (i=0; i<N; i++) {
3670 PackageParser.Provider p = pkg.providers.get(i);
3671 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3672 p.info.name));
3673 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 /* The is another ContentProvider with this authority when
3676 * this app was installed so this authority is null,
3677 * Ignore it as we don't have to unregister the provider.
3678 */
3679 continue;
3680 }
3681 String names[] = p.info.authority.split(";");
3682 for (int j = 0; j < names.length; j++) {
3683 if (mProviders.get(names[j]) == p) {
3684 mProviders.remove(names[j]);
3685 if (chatty && Config.LOGD) Log.d(
3686 TAG, "Unregistered content provider: " + names[j] +
3687 ", className = " + p.info.name +
3688 ", isSyncable = " + p.info.isSyncable);
3689 }
3690 }
3691 if (chatty) {
3692 if (r == null) {
3693 r = new StringBuilder(256);
3694 } else {
3695 r.append(' ');
3696 }
3697 r.append(p.info.name);
3698 }
3699 }
3700 if (r != null) {
3701 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3702 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003703
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 N = pkg.services.size();
3705 r = null;
3706 for (i=0; i<N; i++) {
3707 PackageParser.Service s = pkg.services.get(i);
3708 mServices.removeService(s);
3709 if (chatty) {
3710 if (r == null) {
3711 r = new StringBuilder(256);
3712 } else {
3713 r.append(' ');
3714 }
3715 r.append(s.info.name);
3716 }
3717 }
3718 if (r != null) {
3719 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3720 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 N = pkg.receivers.size();
3723 r = null;
3724 for (i=0; i<N; i++) {
3725 PackageParser.Activity a = pkg.receivers.get(i);
3726 mReceivers.removeActivity(a, "receiver");
3727 if (chatty) {
3728 if (r == null) {
3729 r = new StringBuilder(256);
3730 } else {
3731 r.append(' ');
3732 }
3733 r.append(a.info.name);
3734 }
3735 }
3736 if (r != null) {
3737 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3738 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 N = pkg.activities.size();
3741 r = null;
3742 for (i=0; i<N; i++) {
3743 PackageParser.Activity a = pkg.activities.get(i);
3744 mActivities.removeActivity(a, "activity");
3745 if (chatty) {
3746 if (r == null) {
3747 r = new StringBuilder(256);
3748 } else {
3749 r.append(' ');
3750 }
3751 r.append(a.info.name);
3752 }
3753 }
3754 if (r != null) {
3755 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3756 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003757
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 N = pkg.permissions.size();
3759 r = null;
3760 for (i=0; i<N; i++) {
3761 PackageParser.Permission p = pkg.permissions.get(i);
3762 boolean tree = false;
3763 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3764 if (bp == null) {
3765 tree = true;
3766 bp = mSettings.mPermissionTrees.get(p.info.name);
3767 }
3768 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003769 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 if (chatty) {
3771 if (r == null) {
3772 r = new StringBuilder(256);
3773 } else {
3774 r.append(' ');
3775 }
3776 r.append(p.info.name);
3777 }
3778 }
3779 }
3780 if (r != null) {
3781 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3782 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003783
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 N = pkg.instrumentation.size();
3785 r = null;
3786 for (i=0; i<N; i++) {
3787 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003788 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 if (chatty) {
3790 if (r == null) {
3791 r = new StringBuilder(256);
3792 } else {
3793 r.append(' ');
3794 }
3795 r.append(a.info.name);
3796 }
3797 }
3798 if (r != null) {
3799 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3800 }
3801 }
3802 }
3803
3804 private static final boolean isPackageFilename(String name) {
3805 return name != null && name.endsWith(".apk");
3806 }
3807
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003808 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3809 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3810 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3811 return true;
3812 }
3813 }
3814 return false;
3815 }
3816
3817 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003818 PackageParser.Package pkgInfo, boolean grantPermissions,
3819 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003820 // Make sure there are no dangling permission trees.
3821 Iterator<BasePermission> it = mSettings.mPermissionTrees
3822 .values().iterator();
3823 while (it.hasNext()) {
3824 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003825 if (bp.packageSetting == null) {
3826 // We may not yet have parsed the package, so just see if
3827 // we still know about its settings.
3828 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3829 }
3830 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003831 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 + " from package " + bp.sourcePackage);
3833 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003834 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3835 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3836 Slog.i(TAG, "Removing old permission tree: " + bp.name
3837 + " from package " + bp.sourcePackage);
3838 grantPermissions = true;
3839 it.remove();
3840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003841 }
3842 }
3843
3844 // Make sure all dynamic permissions have been assigned to a package,
3845 // and make sure there are no dangling permissions.
3846 it = mSettings.mPermissions.values().iterator();
3847 while (it.hasNext()) {
3848 BasePermission bp = it.next();
3849 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3850 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3851 + bp.name + " pkg=" + bp.sourcePackage
3852 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003853 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 BasePermission tree = findPermissionTreeLP(bp.name);
3855 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003856 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 bp.perm = new PackageParser.Permission(tree.perm.owner,
3858 new PermissionInfo(bp.pendingInfo));
3859 bp.perm.info.packageName = tree.perm.info.packageName;
3860 bp.perm.info.name = bp.name;
3861 bp.uid = tree.uid;
3862 }
3863 }
3864 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003865 if (bp.packageSetting == null) {
3866 // We may not yet have parsed the package, so just see if
3867 // we still know about its settings.
3868 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3869 }
3870 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003871 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003872 + " from package " + bp.sourcePackage);
3873 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003874 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3875 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3876 Slog.i(TAG, "Removing old permission: " + bp.name
3877 + " from package " + bp.sourcePackage);
3878 grantPermissions = true;
3879 it.remove();
3880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 }
3882 }
3883
3884 // Now update the permissions for all packages, in particular
3885 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003886 if (grantPermissions) {
3887 for (PackageParser.Package pkg : mPackages.values()) {
3888 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003889 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003890 }
3891 }
3892 }
3893
3894 if (pkgInfo != null) {
3895 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 }
3897 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3900 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3901 if (ps == null) {
3902 return;
3903 }
3904 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003905 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003906
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003907 if (replace) {
3908 ps.permissionsFixed = false;
3909 if (gp == ps) {
3910 gp.grantedPermissions.clear();
3911 gp.gids = mGlobalGids;
3912 }
3913 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003914
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003915 if (gp.gids == null) {
3916 gp.gids = mGlobalGids;
3917 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003918
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 final int N = pkg.requestedPermissions.size();
3920 for (int i=0; i<N; i++) {
3921 String name = pkg.requestedPermissions.get(i);
3922 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923 if (false) {
3924 if (gp != ps) {
3925 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003926 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 }
3928 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003929 if (bp != null && bp.packageSetting != null) {
3930 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003932 boolean allowedSig = false;
3933 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3934 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003936 } else if (bp.packageSetting == null) {
3937 // This permission is invalid; skip it.
3938 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003939 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3940 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003941 allowed = (checkSignaturesLP(
3942 bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003944 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 == PackageManager.SIGNATURE_MATCH);
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003946 if (!allowed && bp.protectionLevel
3947 == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003948 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 // For updated system applications, the signatureOrSystem permission
3950 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003951 if (isUpdatedSystemApp(pkg)) {
Dianne Hackborn2fe979f2010-10-08 15:07:17 -07003952 PackageSetting sysPs = mSettings.getDisabledSystemPkg(
3953 pkg.packageName);
3954 final GrantedPermissions origGp = sysPs.sharedUser != null
3955 ? sysPs.sharedUser : sysPs;
3956 if (origGp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 allowed = true;
3958 } else {
3959 allowed = false;
3960 }
3961 } else {
3962 allowed = true;
3963 }
3964 }
3965 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003966 if (allowed) {
3967 allowedSig = true;
3968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003969 } else {
3970 allowed = false;
3971 }
3972 if (false) {
3973 if (gp != ps) {
3974 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3975 }
3976 }
3977 if (allowed) {
3978 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3979 && ps.permissionsFixed) {
3980 // If this is an existing, non-system package, then
3981 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003982 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003984 // Except... if this is a permission that was added
3985 // to the platform (note: need to only do this when
3986 // updating the platform).
3987 final int NP = PackageParser.NEW_PERMISSIONS.length;
3988 for (int ip=0; ip<NP; ip++) {
3989 final PackageParser.NewPermissionInfo npi
3990 = PackageParser.NEW_PERMISSIONS[ip];
3991 if (npi.name.equals(perm)
3992 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3993 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003994 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003995 + pkg.packageName);
3996 break;
3997 }
3998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 }
4000 }
4001 if (allowed) {
4002 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004003 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 gp.grantedPermissions.add(perm);
4005 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004006 } else if (!ps.haveGids) {
4007 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004008 }
4009 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004010 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 + " to package " + pkg.packageName
4012 + " because it was previously installed without");
4013 }
4014 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004015 if (gp.grantedPermissions.remove(perm)) {
4016 changedPermission = true;
4017 gp.gids = removeInts(gp.gids, bp.gids);
4018 Slog.i(TAG, "Un-granting permission " + perm
4019 + " from package " + pkg.packageName
4020 + " (protectionLevel=" + bp.protectionLevel
4021 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4022 + ")");
4023 } else {
4024 Slog.w(TAG, "Not granting permission " + perm
4025 + " to package " + pkg.packageName
4026 + " (protectionLevel=" + bp.protectionLevel
4027 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4028 + ")");
4029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 }
4031 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004032 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 + " in package " + pkg.packageName);
4034 }
4035 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004036
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004037 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004038 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4039 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004040 // This is the first that we have heard about this package, so the
4041 // permissions we have now selected are fixed until explicitly
4042 // changed.
4043 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004044 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004045 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004047
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 private final class ActivityIntentResolver
4049 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004050 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004052 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004053 }
4054
Mihai Preda074edef2009-05-18 17:13:31 +02004055 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004057 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4059 }
4060
Mihai Predaeae850c2009-05-13 10:13:48 +02004061 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4062 ArrayList<PackageParser.Activity> packageActivities) {
4063 if (packageActivities == null) {
4064 return null;
4065 }
4066 mFlags = flags;
4067 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4068 int N = packageActivities.size();
4069 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4070 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004071
4072 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004073 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004074 intentFilters = packageActivities.get(i).intents;
4075 if (intentFilters != null && intentFilters.size() > 0) {
4076 listCut.add(intentFilters);
4077 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004078 }
4079 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4080 }
4081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004083 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 if (SHOW_INFO || Config.LOGV) Log.v(
4085 TAG, " " + type + " " +
4086 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4087 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4088 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004089 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4091 if (SHOW_INFO || Config.LOGV) {
4092 Log.v(TAG, " IntentFilter:");
4093 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4094 }
4095 if (!intent.debugCheck()) {
4096 Log.w(TAG, "==> For Activity " + a.info.name);
4097 }
4098 addFilter(intent);
4099 }
4100 }
4101
4102 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004103 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004104 if (SHOW_INFO || Config.LOGV) Log.v(
4105 TAG, " " + type + " " +
4106 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4107 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4108 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004109 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004110 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4111 if (SHOW_INFO || Config.LOGV) {
4112 Log.v(TAG, " IntentFilter:");
4113 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4114 }
4115 removeFilter(intent);
4116 }
4117 }
4118
4119 @Override
4120 protected boolean allowFilterResult(
4121 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4122 ActivityInfo filterAi = filter.activity.info;
4123 for (int i=dest.size()-1; i>=0; i--) {
4124 ActivityInfo destAi = dest.get(i).activityInfo;
4125 if (destAi.name == filterAi.name
4126 && destAi.packageName == filterAi.packageName) {
4127 return false;
4128 }
4129 }
4130 return true;
4131 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004133 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004134 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4135 return info.activity.owner.packageName;
4136 }
4137
4138 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4140 int match) {
4141 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4142 return null;
4143 }
4144 final PackageParser.Activity activity = info.activity;
4145 if (mSafeMode && (activity.info.applicationInfo.flags
4146 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4147 return null;
4148 }
4149 final ResolveInfo res = new ResolveInfo();
4150 res.activityInfo = PackageParser.generateActivityInfo(activity,
4151 mFlags);
4152 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4153 res.filter = info;
4154 }
4155 res.priority = info.getPriority();
4156 res.preferredOrder = activity.owner.mPreferredOrder;
4157 //System.out.println("Result: " + res.activityInfo.className +
4158 // " = " + res.priority);
4159 res.match = match;
4160 res.isDefault = info.hasDefault;
4161 res.labelRes = info.labelRes;
4162 res.nonLocalizedLabel = info.nonLocalizedLabel;
4163 res.icon = info.icon;
4164 return res;
4165 }
4166
4167 @Override
4168 protected void sortResults(List<ResolveInfo> results) {
4169 Collections.sort(results, mResolvePrioritySorter);
4170 }
4171
4172 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004173 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004174 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004175 out.print(prefix); out.print(
4176 Integer.toHexString(System.identityHashCode(filter.activity)));
4177 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004178 out.print(filter.activity.getComponentShortName());
4179 out.print(" filter ");
4180 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 }
4182
4183// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4184// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4185// final List<ResolveInfo> retList = Lists.newArrayList();
4186// while (i.hasNext()) {
4187// final ResolveInfo resolveInfo = i.next();
4188// if (isEnabledLP(resolveInfo.activityInfo)) {
4189// retList.add(resolveInfo);
4190// }
4191// }
4192// return retList;
4193// }
4194
4195 // Keys are String (activity class name), values are Activity.
4196 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4197 = new HashMap<ComponentName, PackageParser.Activity>();
4198 private int mFlags;
4199 }
4200
4201 private final class ServiceIntentResolver
4202 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004203 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004204 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004205 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004206 }
4207
Mihai Preda074edef2009-05-18 17:13:31 +02004208 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004209 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004210 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4212 }
4213
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004214 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4215 ArrayList<PackageParser.Service> packageServices) {
4216 if (packageServices == null) {
4217 return null;
4218 }
4219 mFlags = flags;
4220 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4221 int N = packageServices.size();
4222 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4223 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4224
4225 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4226 for (int i = 0; i < N; ++i) {
4227 intentFilters = packageServices.get(i).intents;
4228 if (intentFilters != null && intentFilters.size() > 0) {
4229 listCut.add(intentFilters);
4230 }
4231 }
4232 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4233 }
4234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004236 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 if (SHOW_INFO || Config.LOGV) Log.v(
4238 TAG, " " + (s.info.nonLocalizedLabel != null
4239 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4240 if (SHOW_INFO || Config.LOGV) Log.v(
4241 TAG, " Class=" + s.info.name);
4242 int NI = s.intents.size();
4243 int j;
4244 for (j=0; j<NI; j++) {
4245 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4246 if (SHOW_INFO || Config.LOGV) {
4247 Log.v(TAG, " IntentFilter:");
4248 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4249 }
4250 if (!intent.debugCheck()) {
4251 Log.w(TAG, "==> For Service " + s.info.name);
4252 }
4253 addFilter(intent);
4254 }
4255 }
4256
4257 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004258 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 if (SHOW_INFO || Config.LOGV) Log.v(
4260 TAG, " " + (s.info.nonLocalizedLabel != null
4261 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4262 if (SHOW_INFO || Config.LOGV) Log.v(
4263 TAG, " Class=" + s.info.name);
4264 int NI = s.intents.size();
4265 int j;
4266 for (j=0; j<NI; j++) {
4267 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4268 if (SHOW_INFO || Config.LOGV) {
4269 Log.v(TAG, " IntentFilter:");
4270 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4271 }
4272 removeFilter(intent);
4273 }
4274 }
4275
4276 @Override
4277 protected boolean allowFilterResult(
4278 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4279 ServiceInfo filterSi = filter.service.info;
4280 for (int i=dest.size()-1; i>=0; i--) {
4281 ServiceInfo destAi = dest.get(i).serviceInfo;
4282 if (destAi.name == filterSi.name
4283 && destAi.packageName == filterSi.packageName) {
4284 return false;
4285 }
4286 }
4287 return true;
4288 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004290 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004291 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4292 return info.service.owner.packageName;
4293 }
4294
4295 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004296 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4297 int match) {
4298 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4299 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4300 return null;
4301 }
4302 final PackageParser.Service service = info.service;
4303 if (mSafeMode && (service.info.applicationInfo.flags
4304 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4305 return null;
4306 }
4307 final ResolveInfo res = new ResolveInfo();
4308 res.serviceInfo = PackageParser.generateServiceInfo(service,
4309 mFlags);
4310 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4311 res.filter = filter;
4312 }
4313 res.priority = info.getPriority();
4314 res.preferredOrder = service.owner.mPreferredOrder;
4315 //System.out.println("Result: " + res.activityInfo.className +
4316 // " = " + res.priority);
4317 res.match = match;
4318 res.isDefault = info.hasDefault;
4319 res.labelRes = info.labelRes;
4320 res.nonLocalizedLabel = info.nonLocalizedLabel;
4321 res.icon = info.icon;
4322 return res;
4323 }
4324
4325 @Override
4326 protected void sortResults(List<ResolveInfo> results) {
4327 Collections.sort(results, mResolvePrioritySorter);
4328 }
4329
4330 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004331 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004332 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004333 out.print(prefix); out.print(
4334 Integer.toHexString(System.identityHashCode(filter.service)));
4335 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004336 out.print(filter.service.getComponentShortName());
4337 out.print(" filter ");
4338 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004339 }
4340
4341// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4342// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4343// final List<ResolveInfo> retList = Lists.newArrayList();
4344// while (i.hasNext()) {
4345// final ResolveInfo resolveInfo = (ResolveInfo) i;
4346// if (isEnabledLP(resolveInfo.serviceInfo)) {
4347// retList.add(resolveInfo);
4348// }
4349// }
4350// return retList;
4351// }
4352
4353 // Keys are String (activity class name), values are Activity.
4354 private final HashMap<ComponentName, PackageParser.Service> mServices
4355 = new HashMap<ComponentName, PackageParser.Service>();
4356 private int mFlags;
4357 };
4358
4359 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4360 new Comparator<ResolveInfo>() {
4361 public int compare(ResolveInfo r1, ResolveInfo r2) {
4362 int v1 = r1.priority;
4363 int v2 = r2.priority;
4364 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4365 if (v1 != v2) {
4366 return (v1 > v2) ? -1 : 1;
4367 }
4368 v1 = r1.preferredOrder;
4369 v2 = r2.preferredOrder;
4370 if (v1 != v2) {
4371 return (v1 > v2) ? -1 : 1;
4372 }
4373 if (r1.isDefault != r2.isDefault) {
4374 return r1.isDefault ? -1 : 1;
4375 }
4376 v1 = r1.match;
4377 v2 = r2.match;
4378 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4379 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4380 }
4381 };
4382
4383 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4384 new Comparator<ProviderInfo>() {
4385 public int compare(ProviderInfo p1, ProviderInfo p2) {
4386 final int v1 = p1.initOrder;
4387 final int v2 = p2.initOrder;
4388 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4389 }
4390 };
4391
Kenny Root93565c4b2010-06-18 15:46:06 -07004392 private static final boolean DEBUG_OBB = false;
4393
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004394 private static final void sendPackageBroadcast(String action, String pkg,
4395 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004396 IActivityManager am = ActivityManagerNative.getDefault();
4397 if (am != null) {
4398 try {
4399 final Intent intent = new Intent(action,
4400 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4401 if (extras != null) {
4402 intent.putExtras(extras);
4403 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004404 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004405 am.broadcastIntent(null, intent, null, finishedReceiver,
4406 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004407 } catch (RemoteException ex) {
4408 }
4409 }
4410 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004411
4412 public String nextPackageToClean(String lastPackage) {
4413 synchronized (mPackages) {
4414 if (!mMediaMounted) {
4415 // If the external storage is no longer mounted at this point,
4416 // the caller may not have been able to delete all of this
4417 // packages files and can not delete any more. Bail.
4418 return null;
4419 }
4420 if (lastPackage != null) {
4421 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4422 }
4423 return mSettings.mPackagesToBeCleaned.size() > 0
4424 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4425 }
4426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004427
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004428 void schedulePackageCleaning(String packageName) {
4429 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4430 }
4431
4432 void startCleaningPackages() {
4433 synchronized (mPackages) {
4434 if (!mMediaMounted) {
4435 return;
4436 }
4437 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4438 return;
4439 }
4440 }
4441 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4442 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4443 IActivityManager am = ActivityManagerNative.getDefault();
4444 if (am != null) {
4445 try {
4446 am.startService(null, intent, null);
4447 } catch (RemoteException e) {
4448 }
4449 }
4450 }
4451
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004452 private final class AppDirObserver extends FileObserver {
4453 public AppDirObserver(String path, int mask, boolean isrom) {
4454 super(path, mask);
4455 mRootDir = path;
4456 mIsRom = isrom;
4457 }
4458
4459 public void onEvent(int event, String path) {
4460 String removedPackage = null;
4461 int removedUid = -1;
4462 String addedPackage = null;
4463 int addedUid = -1;
4464
4465 synchronized (mInstallLock) {
4466 String fullPathStr = null;
4467 File fullPath = null;
4468 if (path != null) {
4469 fullPath = new File(mRootDir, path);
4470 fullPathStr = fullPath.getPath();
4471 }
4472
4473 if (Config.LOGV) Log.v(
4474 TAG, "File " + fullPathStr + " changed: "
4475 + Integer.toHexString(event));
4476
4477 if (!isPackageFilename(path)) {
4478 if (Config.LOGV) Log.v(
4479 TAG, "Ignoring change of non-package file: " + fullPathStr);
4480 return;
4481 }
4482
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004483 // Ignore packages that are being installed or
4484 // have just been installed.
4485 if (ignoreCodePath(fullPathStr)) {
4486 return;
4487 }
4488 PackageParser.Package p = null;
4489 synchronized (mPackages) {
4490 p = mAppDirs.get(fullPathStr);
4491 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004493 if (p != null) {
4494 removePackageLI(p, true);
4495 removedPackage = p.applicationInfo.packageName;
4496 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004497 }
4498 }
4499
4500 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004501 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004502 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004503 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4504 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004505 PackageParser.PARSE_CHATTY |
4506 PackageParser.PARSE_MUST_BE_APK,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07004507 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
4508 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004509 if (p != null) {
4510 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004511 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004512 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004513 }
4514 addedPackage = p.applicationInfo.packageName;
4515 addedUid = p.applicationInfo.uid;
4516 }
4517 }
4518 }
4519
4520 synchronized (mPackages) {
4521 mSettings.writeLP();
4522 }
4523 }
4524
4525 if (removedPackage != null) {
4526 Bundle extras = new Bundle(1);
4527 extras.putInt(Intent.EXTRA_UID, removedUid);
4528 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004529 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4530 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004531 }
4532 if (addedPackage != null) {
4533 Bundle extras = new Bundle(1);
4534 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004535 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4536 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004537 }
4538 }
4539
4540 private final String mRootDir;
4541 private final boolean mIsRom;
4542 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004544 /* Called when a downloaded package installation has been confirmed by the user */
4545 public void installPackage(
4546 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004547 installPackage(packageURI, observer, flags, null);
4548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004549
Jacek Surazski65e13172009-04-28 15:26:38 +02004550 /* Called when a downloaded package installation has been confirmed by the user */
4551 public void installPackage(
4552 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4553 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004554 mContext.enforceCallingOrSelfPermission(
4555 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004556
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004557 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004558 msg.obj = new InstallParams(packageURI, observer, flags,
4559 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004560 mHandler.sendMessage(msg);
4561 }
4562
Christopher Tate1bb69062010-02-19 17:02:12 -08004563 public void finishPackageInstall(int token) {
4564 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4565 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4566 mHandler.sendMessage(msg);
4567 }
4568
Dianne Hackborn880119b2010-11-18 22:26:40 -08004569 public void setInstallerPackageName(String targetPackage,
4570 String installerPackageName) {
4571 PackageSetting pkgSetting;
4572 final int uid = Binder.getCallingUid();
4573 final int permission = mContext.checkCallingPermission(
4574 android.Manifest.permission.INSTALL_PACKAGES);
4575 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
4576 synchronized (mPackages) {
4577 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
4578 if (targetPackageSetting == null) {
4579 throw new IllegalArgumentException("Unknown target package: " + targetPackage);
4580 }
4581
4582 PackageSetting installerPackageSetting;
4583 if (installerPackageName != null) {
4584 installerPackageSetting = mSettings.mPackages.get(installerPackageName);
4585 if (installerPackageSetting == null) {
4586 throw new IllegalArgumentException("Unknown installer package: "
4587 + installerPackageName);
4588 }
4589 } else {
4590 installerPackageSetting = null;
4591 }
4592
4593 Signature[] callerSignature;
4594 Object obj = mSettings.getUserIdLP(uid);
4595 if (obj != null) {
4596 if (obj instanceof SharedUserSetting) {
4597 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
4598 } else if (obj instanceof PackageSetting) {
4599 callerSignature = ((PackageSetting)obj).signatures.mSignatures;
4600 } else {
4601 throw new SecurityException("Bad object " + obj + " for uid " + uid);
4602 }
4603 } else {
4604 throw new SecurityException("Unknown calling uid " + uid);
4605 }
4606
4607 // Verify: can't set installerPackageName to a package that is
4608 // not signed with the same cert as the caller.
4609 if (installerPackageSetting != null) {
4610 if (checkSignaturesLP(callerSignature,
4611 installerPackageSetting.signatures.mSignatures)
4612 != PackageManager.SIGNATURE_MATCH) {
4613 throw new SecurityException(
4614 "Caller does not have same cert as new installer package "
4615 + installerPackageName);
4616 }
4617 }
4618
4619 // Verify: if target already has an installer package, it must
4620 // be signed with the same cert as the caller.
4621 if (targetPackageSetting.installerPackageName != null) {
4622 PackageSetting setting = mSettings.mPackages.get(
4623 targetPackageSetting.installerPackageName);
4624 // If the currently set package isn't valid, then it's always
4625 // okay to change it.
4626 if (setting != null) {
4627 if (checkSignaturesLP(callerSignature,
4628 setting.signatures.mSignatures)
4629 != PackageManager.SIGNATURE_MATCH) {
4630 throw new SecurityException(
4631 "Caller does not have same cert as old installer package "
4632 + targetPackageSetting.installerPackageName);
4633 }
4634 }
4635 }
4636
4637 // Okay!
4638 targetPackageSetting.installerPackageName = installerPackageName;
4639 scheduleWriteSettingsLocked();
4640 }
4641 }
4642
Kenny Root93565c4b2010-06-18 15:46:06 -07004643 public void setPackageObbPath(String packageName, String path) {
4644 if (DEBUG_OBB)
4645 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4646 PackageSetting pkgSetting;
4647 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004648 final int permission = mContext.checkCallingPermission(
4649 android.Manifest.permission.INSTALL_PACKAGES);
4650 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004651 synchronized (mPackages) {
4652 pkgSetting = mSettings.mPackages.get(packageName);
4653 if (pkgSetting == null) {
4654 throw new IllegalArgumentException("Unknown package: " + packageName);
4655 }
4656 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4657 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4658 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4659 + pkgSetting.userId);
4660 }
4661 pkgSetting.obbPathString = path;
4662 mSettings.writeLP();
4663 }
4664 }
4665
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004666 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004667 // Queue up an async operation since the package installation may take a little while.
4668 mHandler.post(new Runnable() {
4669 public void run() {
4670 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004671 // Result object to be returned
4672 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004673 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004674 res.uid = -1;
4675 res.pkg = null;
4676 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004677 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004678 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004679 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004680 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004681 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004682 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004683 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004684
4685 // A restore should be performed at this point if (a) the install
4686 // succeeded, (b) the operation is not an update, and (c) the new
4687 // package has a backupAgent defined.
4688 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004689 boolean doRestore = (!update
4690 && res.pkg != null
4691 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004692
4693 // Set up the post-install work request bookkeeping. This will be used
4694 // and cleaned up by the post-install event handling regardless of whether
4695 // there's a restore pass performed. Token values are >= 1.
4696 int token;
4697 if (mNextInstallToken < 0) mNextInstallToken = 1;
4698 token = mNextInstallToken++;
4699
4700 PostInstallData data = new PostInstallData(args, res);
4701 mRunningInstalls.put(token, data);
4702 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4703
4704 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4705 // Pass responsibility to the Backup Manager. It will perform a
4706 // restore if appropriate, then pass responsibility back to the
4707 // Package Manager to run the post-install observer callbacks
4708 // and broadcasts.
4709 IBackupManager bm = IBackupManager.Stub.asInterface(
4710 ServiceManager.getService(Context.BACKUP_SERVICE));
4711 if (bm != null) {
4712 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4713 + " to BM for possible restore");
4714 try {
4715 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4716 } catch (RemoteException e) {
4717 // can't happen; the backup manager is local
4718 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004719 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004720 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004721 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004722 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004723 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004724 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004725 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004726 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004727
4728 if (!doRestore) {
4729 // No restore possible, or the Backup Manager was mysteriously not
4730 // available -- just fire the post-install work request directly.
4731 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4732 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4733 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 }
4736 });
4737 }
4738
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004739 abstract class HandlerParams {
4740 final static int MAX_RETRIES = 4;
4741 int retry = 0;
4742 final void startCopy() {
4743 try {
4744 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4745 retry++;
4746 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004747 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004748 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4749 handleServiceError();
4750 return;
4751 } else {
4752 handleStartCopy();
4753 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4754 mHandler.sendEmptyMessage(MCS_UNBIND);
4755 }
4756 } catch (RemoteException e) {
4757 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4758 mHandler.sendEmptyMessage(MCS_RECONNECT);
4759 }
4760 handleReturnCode();
4761 }
4762
4763 final void serviceError() {
4764 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4765 handleServiceError();
4766 handleReturnCode();
4767 }
4768 abstract void handleStartCopy() throws RemoteException;
4769 abstract void handleServiceError();
4770 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004771 }
4772
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004773 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004774 final IPackageInstallObserver observer;
4775 int flags;
4776 final Uri packageURI;
4777 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004778 private InstallArgs mArgs;
4779 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004780 InstallParams(Uri packageURI,
4781 IPackageInstallObserver observer, int flags,
4782 String installerPackageName) {
4783 this.packageURI = packageURI;
4784 this.flags = flags;
4785 this.observer = observer;
4786 this.installerPackageName = installerPackageName;
4787 }
4788
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004789 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4790 String packageName = pkgLite.packageName;
4791 int installLocation = pkgLite.installLocation;
4792 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4793 synchronized (mPackages) {
4794 PackageParser.Package pkg = mPackages.get(packageName);
4795 if (pkg != null) {
4796 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4797 // Check for updated system application.
4798 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4799 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004800 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004801 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4802 }
4803 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4804 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004805 if (onSd) {
4806 // Install flag overrides everything.
4807 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4808 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004809 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004810 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4811 // Application explicitly specified internal.
4812 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4813 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4814 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004815 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004816 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004817 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004818 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4819 }
4820 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004821 }
4822 }
4823 } else {
4824 // Invalid install. Return error code
4825 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4826 }
4827 }
4828 }
4829 // All the special cases have been taken care of.
4830 // Return result based on recommended install location.
4831 if (onSd) {
4832 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4833 }
4834 return pkgLite.recommendedInstallLocation;
4835 }
4836
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004837 /*
4838 * Invoke remote method to get package information and install
4839 * location values. Override install location based on default
4840 * policy if needed and then create install arguments based
4841 * on the install location.
4842 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004843 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004844 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004845 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4846 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004847 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4848 if (onInt && onSd) {
4849 // Check if both bits are set.
4850 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4851 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4852 } else if (fwdLocked && onSd) {
4853 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004854 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004855 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004856 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004857 // Remote call to find out default install location
Kenny Root11128572010-10-11 10:51:32 -07004858 final PackageInfoLite pkgLite;
4859 try {
4860 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
4861 Intent.FLAG_GRANT_READ_URI_PERMISSION);
4862 pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
4863 } finally {
4864 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
4865 }
4866
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004867 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004868 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4869 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4870 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4871 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4872 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004873 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4874 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4875 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004876 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4877 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004878 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004879 // Override with defaults if needed.
4880 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004881 if (!onSd && !onInt) {
4882 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004883 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4884 // Set the flag to install on external media.
4885 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004886 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004887 } else {
4888 // Make sure the flag for installing on external
4889 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004890 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004891 flags &= ~PackageManager.INSTALL_EXTERNAL;
4892 }
4893 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004894 }
4895 }
4896 // Create the file args now.
4897 mArgs = createInstallArgs(this);
4898 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4899 // Create copy only if we are not in an erroneous state.
4900 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004901 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004902 }
4903 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004904 }
4905
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004906 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004907 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004908 // If mArgs is null, then MCS couldn't be reached. When it
4909 // reconnects, it will try again to install. At that point, this
4910 // will succeed.
4911 if (mArgs != null) {
4912 processPendingInstall(mArgs, mRet);
4913 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004914 }
4915
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004916 @Override
4917 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004918 mArgs = createInstallArgs(this);
4919 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004920 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004921 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004922
4923 /*
4924 * Utility class used in movePackage api.
4925 * srcArgs and targetArgs are not set for invalid flags and make
4926 * sure to do null checks when invoking methods on them.
4927 * We probably want to return ErrorPrams for both failed installs
4928 * and moves.
4929 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004930 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004931 final IPackageMoveObserver observer;
4932 final int flags;
4933 final String packageName;
4934 final InstallArgs srcArgs;
4935 final InstallArgs targetArgs;
4936 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004937
4938 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4939 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004940 this.srcArgs = srcArgs;
4941 this.observer = observer;
4942 this.flags = flags;
4943 this.packageName = packageName;
4944 if (srcArgs != null) {
4945 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004946 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004947 } else {
4948 targetArgs = null;
4949 }
4950 }
4951
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004952 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004953 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4954 // Check for storage space on target medium
4955 if (!targetArgs.checkFreeStorage(mContainerService)) {
4956 Log.w(TAG, "Insufficient storage to install");
4957 return;
4958 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004959 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004960 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004961 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004962 if (DEBUG_SD_INSTALL) {
4963 StringBuilder builder = new StringBuilder();
4964 if (srcArgs != null) {
4965 builder.append("src: ");
4966 builder.append(srcArgs.getCodePath());
4967 }
4968 if (targetArgs != null) {
4969 builder.append(" target : ");
4970 builder.append(targetArgs.getCodePath());
4971 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004972 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004973 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004974 }
4975
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004976 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004977 void handleReturnCode() {
4978 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004979 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4980 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4981 currentStatus = PackageManager.MOVE_SUCCEEDED;
4982 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4983 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4984 }
4985 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004986 }
4987
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004988 @Override
4989 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004991 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004992 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004993
4994 private InstallArgs createInstallArgs(InstallParams params) {
4995 if (installOnSd(params.flags)) {
4996 return new SdInstallArgs(params);
4997 } else {
4998 return new FileInstallArgs(params);
4999 }
5000 }
5001
Kenny Root85387d72010-08-26 10:13:11 -07005002 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
5003 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005004 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07005005 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005006 } else {
Kenny Root85387d72010-08-26 10:13:11 -07005007 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005008 }
5009 }
5010
Kenny Root85387d72010-08-26 10:13:11 -07005011 // Used by package mover
5012 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005013 if (installOnSd(flags)) {
5014 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5015 return new SdInstallArgs(packageURI, cid);
5016 } else {
Kenny Root85387d72010-08-26 10:13:11 -07005017 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005018 }
5019 }
5020
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005021 static abstract class InstallArgs {
5022 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005023 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005024 final int flags;
5025 final Uri packageURI;
5026 final String installerPackageName;
5027
5028 InstallArgs(Uri packageURI,
5029 IPackageInstallObserver observer, int flags,
5030 String installerPackageName) {
5031 this.packageURI = packageURI;
5032 this.flags = flags;
5033 this.observer = observer;
5034 this.installerPackageName = installerPackageName;
5035 }
5036
5037 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005038 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005039 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005040 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005041 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005042 abstract String getCodePath();
5043 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07005044 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005045 // Need installer lock especially for dex file removal.
5046 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005047 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005048 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005049 }
5050
5051 class FileInstallArgs extends InstallArgs {
5052 File installDir;
5053 String codeFileName;
5054 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07005055 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005056 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005057
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005058 FileInstallArgs(InstallParams params) {
5059 super(params.packageURI, params.observer,
5060 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005061 }
5062
Kenny Root85387d72010-08-26 10:13:11 -07005063 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005064 super(null, null, 0, null);
5065 File codeFile = new File(fullCodePath);
5066 installDir = codeFile.getParentFile();
5067 codeFileName = fullCodePath;
5068 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07005069 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005070 }
5071
Kenny Root85387d72010-08-26 10:13:11 -07005072 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005073 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07005074 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005075 String apkName = getNextCodePath(null, pkgName, ".apk");
5076 codeFileName = new File(installDir, apkName + ".apk").getPath();
5077 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07005078 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005079 }
5080
Kenny Root11128572010-10-11 10:51:32 -07005081 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5082 try {
5083 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5084 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5085 return imcs.checkFreeStorage(false, packageURI);
5086 } finally {
5087 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5088 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005089 }
5090
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005091 String getCodePath() {
5092 return codeFileName;
5093 }
5094
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005095 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07005096 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005097 codeFileName = createTempPackageFile(installDir).getPath();
5098 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005099 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005100 }
5101
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005102 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005103 if (temp) {
5104 // Generate temp file name
5105 createCopyFile();
5106 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 // Get a ParcelFileDescriptor to write to the output file
5108 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005109 if (!created) {
5110 try {
5111 codeFile.createNewFile();
5112 // Set permissions
5113 if (!setPermissions()) {
5114 // Failed setting permissions.
5115 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5116 }
5117 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005118 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005119 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5120 }
5121 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005122 ParcelFileDescriptor out = null;
5123 try {
Kenny Root85387d72010-08-26 10:13:11 -07005124 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005125 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005126 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005127 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5128 }
5129 // Copy the resource now
5130 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5131 try {
Kenny Root11128572010-10-11 10:51:32 -07005132 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5133 Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005134 if (imcs.copyResource(packageURI, out)) {
5135 ret = PackageManager.INSTALL_SUCCEEDED;
5136 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005137 } finally {
5138 try { if (out != null) out.close(); } catch (IOException e) {}
Kenny Root11128572010-10-11 10:51:32 -07005139 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005140 }
Kenny Root85387d72010-08-26 10:13:11 -07005141
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005142 return ret;
5143 }
5144
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005145 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005146 if (status != PackageManager.INSTALL_SUCCEEDED) {
5147 cleanUp();
5148 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005149 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005150 }
5151
5152 boolean doRename(int status, final String pkgName, String oldCodePath) {
5153 if (status != PackageManager.INSTALL_SUCCEEDED) {
5154 cleanUp();
5155 return false;
5156 } else {
5157 // Rename based on packageName
5158 File codeFile = new File(getCodePath());
5159 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5160 File desFile = new File(installDir, apkName + ".apk");
5161 if (!codeFile.renameTo(desFile)) {
5162 return false;
5163 }
5164 // Reset paths since the file has been renamed.
5165 codeFileName = desFile.getPath();
5166 resourceFileName = getResourcePathFromCodePath();
5167 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005168 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005169 // Failed setting permissions.
5170 return false;
5171 }
5172 return true;
5173 }
5174 }
5175
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005176 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005177 if (status != PackageManager.INSTALL_SUCCEEDED) {
5178 cleanUp();
5179 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005180 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005181 }
5182
5183 String getResourcePath() {
5184 return resourceFileName;
5185 }
5186
5187 String getResourcePathFromCodePath() {
5188 String codePath = getCodePath();
5189 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5190 String apkNameOnly = getApkName(codePath);
5191 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5192 } else {
5193 return codePath;
5194 }
5195 }
5196
Kenny Root85387d72010-08-26 10:13:11 -07005197 @Override
5198 String getNativeLibraryPath() {
5199 return libraryPath;
5200 }
5201
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005202 private boolean cleanUp() {
5203 boolean ret = true;
5204 String sourceDir = getCodePath();
5205 String publicSourceDir = getResourcePath();
5206 if (sourceDir != null) {
5207 File sourceFile = new File(sourceDir);
5208 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005209 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005210 ret = false;
5211 }
5212 // Delete application's code and resources
5213 sourceFile.delete();
5214 }
5215 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5216 final File publicSourceFile = new File(publicSourceDir);
5217 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005218 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005219 }
5220 if (publicSourceFile.exists()) {
5221 publicSourceFile.delete();
5222 }
5223 }
5224 return ret;
5225 }
5226
5227 void cleanUpResourcesLI() {
5228 String sourceDir = getCodePath();
5229 if (cleanUp() && mInstaller != null) {
5230 int retCode = mInstaller.rmdex(sourceDir);
5231 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005232 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005233 + " at location "
5234 + sourceDir + ", retcode=" + retCode);
5235 // we don't consider this to be a failure of the core package deletion
5236 }
5237 }
5238 }
5239
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005240 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005241 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005242 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005243 final int filePermissions =
5244 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5245 |FileUtils.S_IROTH;
5246 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5247 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005248 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005249 getCodePath()
5250 + ". The return code was: " + retCode);
5251 // TODO Define new internal error
5252 return false;
5253 }
5254 return true;
5255 }
5256 return true;
5257 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005258
5259 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005260 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005261 cleanUpResourcesLI();
5262 return true;
5263 }
Kenny Root85387d72010-08-26 10:13:11 -07005264
5265 private boolean isFwdLocked() {
5266 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5267 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005268 }
5269
5270 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005271 static final String RES_FILE_NAME = "pkg.apk";
5272
Kenny Root85387d72010-08-26 10:13:11 -07005273 String cid;
5274 String packagePath;
5275 String libraryPath;
5276
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005277 SdInstallArgs(InstallParams params) {
5278 super(params.packageURI, params.observer,
5279 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005280 }
5281
Kenny Root85387d72010-08-26 10:13:11 -07005282 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005283 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005284 // Extract cid from fullCodePath
5285 int eidx = fullCodePath.lastIndexOf("/");
5286 String subStr1 = fullCodePath.substring(0, eidx);
5287 int sidx = subStr1.lastIndexOf("/");
5288 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005289 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005290 }
5291
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005292 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005293 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5294 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005295 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005296 }
5297
5298 SdInstallArgs(Uri packageURI, String cid) {
5299 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005300 this.cid = cid;
5301 }
5302
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005303 void createCopyFile() {
5304 cid = getTempContainerId();
5305 }
5306
Kenny Root11128572010-10-11 10:51:32 -07005307 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5308 try {
5309 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5310 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5311 return imcs.checkFreeStorage(true, packageURI);
5312 } finally {
5313 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5314 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005315 }
5316
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005317 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005318 if (temp) {
5319 createCopyFile();
5320 }
Kenny Root11128572010-10-11 10:51:32 -07005321
5322 final String newCachePath;
5323 try {
5324 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
5325 Intent.FLAG_GRANT_READ_URI_PERMISSION);
5326 newCachePath = imcs.copyResourceToContainer(packageURI, cid,
5327 getEncryptKey(), RES_FILE_NAME);
5328 } finally {
5329 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
5330 }
5331
Kenny Root85387d72010-08-26 10:13:11 -07005332 if (newCachePath != null) {
5333 setCachePath(newCachePath);
5334 return PackageManager.INSTALL_SUCCEEDED;
5335 } else {
5336 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5337 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005338 }
5339
5340 @Override
5341 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005342 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005343 }
5344
5345 @Override
5346 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005347 return packagePath;
5348 }
5349
5350 @Override
5351 String getNativeLibraryPath() {
5352 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005353 }
5354
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005355 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005356 if (status != PackageManager.INSTALL_SUCCEEDED) {
5357 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005358 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005359 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005360 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005361 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005362 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5363 Process.SYSTEM_UID);
5364 if (newCachePath != null) {
5365 setCachePath(newCachePath);
5366 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005367 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5368 }
5369 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005370 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005371 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005372 }
5373
5374 boolean doRename(int status, final String pkgName,
5375 String oldCodePath) {
5376 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005377 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005378 if (PackageHelper.isContainerMounted(cid)) {
5379 // Unmount the container
5380 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005381 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005382 return false;
5383 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005384 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005385 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005386 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5387 " which might be stale. Will try to clean up.");
5388 // Clean up the stale container and proceed to recreate.
5389 if (!PackageHelper.destroySdDir(newCacheId)) {
5390 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5391 return false;
5392 }
5393 // Successfully cleaned up stale container. Try to rename again.
5394 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5395 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5396 + " inspite of cleaning it up.");
5397 return false;
5398 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005399 }
5400 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005401 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005402 newCachePath = PackageHelper.mountSdDir(newCacheId,
5403 getEncryptKey(), Process.SYSTEM_UID);
5404 } else {
5405 newCachePath = PackageHelper.getSdDir(newCacheId);
5406 }
5407 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005408 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005409 return false;
5410 }
5411 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005412 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005413 " at new path: " + newCachePath);
5414 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005415 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005416 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005417 }
5418
Kenny Root85387d72010-08-26 10:13:11 -07005419 private void setCachePath(String newCachePath) {
5420 File cachePath = new File(newCachePath);
5421 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5422 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5423 }
5424
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005425 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005426 if (status != PackageManager.INSTALL_SUCCEEDED) {
5427 cleanUp();
5428 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005429 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005430 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005431 PackageHelper.mountSdDir(cid,
5432 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005433 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005434 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005435 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005436 }
5437
5438 private void cleanUp() {
5439 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005440 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005441 }
5442
5443 void cleanUpResourcesLI() {
5444 String sourceFile = getCodePath();
5445 // Remove dex file
5446 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005447 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005448 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005449 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005450 + " at location "
5451 + sourceFile.toString() + ", retcode=" + retCode);
5452 // we don't consider this to be a failure of the core package deletion
5453 }
5454 }
5455 cleanUp();
5456 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005457
5458 boolean matchContainer(String app) {
5459 if (cid.startsWith(app)) {
5460 return true;
5461 }
5462 return false;
5463 }
5464
5465 String getPackageName() {
5466 int idx = cid.lastIndexOf("-");
5467 if (idx == -1) {
5468 return cid;
5469 }
5470 return cid.substring(0, idx);
5471 }
5472
5473 boolean doPostDeleteLI(boolean delete) {
5474 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005475 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005476 if (mounted) {
5477 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005478 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005479 }
5480 if (ret && delete) {
5481 cleanUpResourcesLI();
5482 }
5483 return ret;
5484 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005485 };
5486
5487 // Utility method used to create code paths based on package name and available index.
5488 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5489 String idxStr = "";
5490 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005491 // Fall back to default value of idx=1 if prefix is not
5492 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005493 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005494 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005495 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005496 if (subStr.endsWith(suffix)) {
5497 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005498 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005499 // If oldCodePath already contains prefix find out the
5500 // ending index to either increment or decrement.
5501 int sidx = subStr.lastIndexOf(prefix);
5502 if (sidx != -1) {
5503 subStr = subStr.substring(sidx + prefix.length());
5504 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005505 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5506 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005507 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005508 try {
5509 idx = Integer.parseInt(subStr);
5510 if (idx <= 1) {
5511 idx++;
5512 } else {
5513 idx--;
5514 }
5515 } catch(NumberFormatException e) {
5516 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005517 }
5518 }
5519 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005520 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005521 return prefix + idxStr;
5522 }
5523
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005524 // Utility method used to ignore ADD/REMOVE events
5525 // by directory observer.
5526 private static boolean ignoreCodePath(String fullPathStr) {
5527 String apkName = getApkName(fullPathStr);
5528 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5529 if (idx != -1 && ((idx+1) < apkName.length())) {
5530 // Make sure the package ends with a numeral
5531 String version = apkName.substring(idx+1);
5532 try {
5533 Integer.parseInt(version);
5534 return true;
5535 } catch (NumberFormatException e) {}
5536 }
5537 return false;
5538 }
5539
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005540 // Utility method that returns the relative package path with respect
5541 // to the installation directory. Like say for /data/data/com.test-1.apk
5542 // string com.test-1 is returned.
5543 static String getApkName(String codePath) {
5544 if (codePath == null) {
5545 return null;
5546 }
5547 int sidx = codePath.lastIndexOf("/");
5548 int eidx = codePath.lastIndexOf(".");
5549 if (eidx == -1) {
5550 eidx = codePath.length();
5551 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005552 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005553 return null;
5554 }
5555 return codePath.substring(sidx+1, eidx);
5556 }
5557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005558 class PackageInstalledInfo {
5559 String name;
5560 int uid;
5561 PackageParser.Package pkg;
5562 int returnCode;
5563 PackageRemovedInfo removedInfo;
5564 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005566 /*
5567 * Install a non-existing package.
5568 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005569 private void installNewPackageLI(PackageParser.Package pkg,
5570 int parseFlags,
5571 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005572 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005573 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005574 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005575
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005576 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005577 res.name = pkgName;
5578 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005579 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5580 // A package with the same name is already installed, though
5581 // it has been renamed to an older name. The package we
5582 // are trying to install should be installed as an update to
5583 // the existing one, but that has not been requested, so bail.
5584 Slog.w(TAG, "Attempt to re-install " + pkgName
5585 + " without first uninstalling package running as "
5586 + mSettings.mRenamedPackages.get(pkgName));
5587 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5588 return;
5589 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005590 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005592 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005593 + " without first uninstalling.");
5594 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5595 return;
5596 }
5597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005599 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
5600 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005602 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005603 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5604 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5605 }
5606 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005607 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005608 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 res);
5610 // delete the partially installed application. the data directory will have to be
5611 // restored if it was already existing
5612 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5613 // remove package from internal structures. Note that we want deletePackageX to
5614 // delete the package data and cache directories that it created in
5615 // scanPackageLocked, unless those directories existed before we even tried to
5616 // install.
5617 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005618 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005620 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 }
5622 }
5623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005624
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005625 private void replacePackageLI(PackageParser.Package pkg,
5626 int parseFlags,
5627 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005628 String installerPackageName, PackageInstalledInfo res) {
5629
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005630 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005631 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 // First find the old package info and check signatures
5633 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005634 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005635 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005636 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005637 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5638 return;
5639 }
5640 }
Kenny Root85387d72010-08-26 10:13:11 -07005641 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005642 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005643 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005645 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 }
5647 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005649 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005650 PackageParser.Package pkg,
5651 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005652 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 PackageParser.Package newPackage = null;
5654 String pkgName = deletedPackage.packageName;
5655 boolean deletedPkg = true;
5656 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005657
Jacek Surazski65e13172009-04-28 15:26:38 +02005658 String oldInstallerPackageName = null;
5659 synchronized (mPackages) {
5660 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005662
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005663 long origUpdateTime;
5664 if (pkg.mExtras != null) {
5665 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
5666 } else {
5667 origUpdateTime = 0;
5668 }
5669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005670 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005671 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005672 res.removedInfo, true)) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005673 // If the existing package wasn't successfully deleted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005674 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5675 deletedPkg = false;
5676 } else {
5677 // Successfully deleted the old package. Now proceed with re-installation
5678 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005679 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
5680 System.currentTimeMillis());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005681 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005682 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005683 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5684 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005685 }
5686 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005687 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005688 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 res);
5690 updatedSettings = true;
5691 }
5692 }
5693
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005694 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005695 // remove package from internal structures. Note that we want deletePackageX to
5696 // delete the package data and cache directories that it created in
5697 // scanPackageLocked, unless those directories existed before we even tried to
5698 // install.
5699 if(updatedSettings) {
5700 deletePackageLI(
5701 pkgName, true,
5702 PackageManager.DONT_DELETE_DATA,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07005703 res.removedInfo, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 }
5705 // Since we failed to install the new package we need to restore the old
5706 // package that we deleted.
5707 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005708 File restoreFile = new File(deletedPackage.mPath);
5709 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005710 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005711 return;
5712 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005713 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005714 boolean oldOnSd = isExternal(deletedPackage);
5715 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5716 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5717 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005718 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
5719 | SCAN_UPDATE_TIME;
5720 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
5721 origUpdateTime) == null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005722 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5723 return;
5724 }
5725 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005726 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005727 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005728 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005729 mSettings.writeLP();
5730 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005731 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005732 }
5733 }
5734 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005735
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005736 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005737 PackageParser.Package pkg,
5738 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005739 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005740 PackageParser.Package newPackage = null;
5741 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005742 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005743 PackageParser.PARSE_IS_SYSTEM;
5744 String packageName = deletedPackage.packageName;
5745 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5746 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005747 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005748 return;
5749 }
5750 PackageParser.Package oldPkg;
5751 PackageSetting oldPkgSetting;
5752 synchronized (mPackages) {
5753 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005754 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005755 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5756 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005757 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005758 return;
5759 }
5760 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005761
5762 killApplication(packageName, oldPkg.applicationInfo.uid);
5763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005764 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5765 res.removedInfo.removedPackage = packageName;
5766 // Remove existing system package
5767 removePackageLI(oldPkg, true);
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005768 synchronized (mPackages) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08005769 if (!mSettings.disableSystemPackageLP(packageName) && deletedPackage != null) {
5770 // We didn't need to disable the .apk as a current system package,
5771 // which means we are replacing another update that is already
5772 // installed. We need to make sure to delete the older one's .apk.
5773 res.removedInfo.args = createInstallArgs(isExternal(pkg)
5774 ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL,
5775 deletedPackage.applicationInfo.sourceDir,
5776 deletedPackage.applicationInfo.publicSourceDir,
5777 deletedPackage.applicationInfo.nativeLibraryDir);
5778 } else {
5779 res.removedInfo.args = null;
5780 }
Dianne Hackborn3ec27e02010-12-16 12:41:56 -08005781 }
5782
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005783 // Successfully disabled the old package. Now proceed with re-installation
5784 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5785 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005786 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005787 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005788 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005789 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5790 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5791 }
5792 } else {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005793 if (newPackage.mExtras != null) {
5794 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
5795 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
5796 newPkgSetting.lastUpdateTime = System.currentTimeMillis();
5797 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005798 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005799 updatedSettings = true;
5800 }
5801
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005802 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005803 // Re installation failed. Restore old information
5804 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005805 if (newPackage != null) {
5806 removePackageLI(newPackage, true);
5807 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005808 // Add back the old system package
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005809 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005810 // Restore the old system information in Settings
5811 synchronized(mPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07005812 if (updatedSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005813 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005814 mSettings.setInstallerPackageName(packageName,
5815 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005816 }
5817 mSettings.writeLP();
5818 }
5819 }
5820 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005821
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005822 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005823 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005824 int retCode;
5825 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5826 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5827 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005828 if (mNoDexOpt) {
5829 /*
5830 * If we're in an engineering build, programs are lazily run
5831 * through dexopt. If the .dex file doesn't exist yet, it
5832 * will be created when the program is run next.
5833 */
5834 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5835 } else {
5836 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5837 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5838 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005839 }
5840 }
5841 return PackageManager.INSTALL_SUCCEEDED;
5842 }
5843
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005844 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005845 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005846 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005847 synchronized (mPackages) {
5848 //write settings. the installStatus will be incomplete at this stage.
5849 //note that the new package setting would have already been
5850 //added to mPackages. It hasn't been persisted yet.
5851 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5852 mSettings.writeLP();
5853 }
5854
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005855 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005856 != PackageManager.INSTALL_SUCCEEDED) {
5857 // Discontinue if moving dex files failed.
5858 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005859 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005860 if((res.returnCode = setPermissionsLI(newPackage))
5861 != PackageManager.INSTALL_SUCCEEDED) {
5862 if (mInstaller != null) {
5863 mInstaller.rmdex(newPackage.mScanPath);
5864 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005865 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005867 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005869 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005870 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005871 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 res.name = pkgName;
5873 res.uid = newPackage.applicationInfo.uid;
5874 res.pkg = newPackage;
5875 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005876 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005877 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5878 //to update install status
5879 mSettings.writeLP();
5880 }
5881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005882
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005883 private void installPackageLI(InstallArgs args,
5884 boolean newInstall, PackageInstalledInfo res) {
5885 int pFlags = args.flags;
5886 String installerPackageName = args.installerPackageName;
5887 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005888 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005889 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005890 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005891 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005892 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005893 // Result object to be returned
5894 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5895
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005896 // Retrieve PackageSettings and parse package
5897 int parseFlags = PackageParser.PARSE_CHATTY |
5898 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5899 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5900 parseFlags |= mDefParseFlags;
5901 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5902 pp.setSeparateProcesses(mSeparateProcesses);
5903 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5904 null, mMetrics, parseFlags);
5905 if (pkg == null) {
5906 res.returnCode = pp.getParseError();
5907 return;
5908 }
5909 String pkgName = res.name = pkg.packageName;
5910 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5911 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5912 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5913 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005914 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005915 }
5916 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5917 res.returnCode = pp.getParseError();
5918 return;
5919 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005920 // Get rid of all references to package scan path via parser.
5921 pp = null;
5922 String oldCodePath = null;
5923 boolean systemApp = false;
5924 synchronized (mPackages) {
5925 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005926 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5927 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005928 if (pkg.mOriginalPackages != null
5929 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005930 && mPackages.containsKey(oldName)) {
5931 // This package is derived from an original package,
5932 // and this device has been updating from that original
5933 // name. We must continue using the original name, so
5934 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005935 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005936 pkgName = pkg.packageName;
5937 replace = true;
5938 } else if (mPackages.containsKey(pkgName)) {
5939 // This package, under its official name, already exists
5940 // on the device; we should replace it.
5941 replace = true;
5942 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005943 }
5944 PackageSetting ps = mSettings.mPackages.get(pkgName);
5945 if (ps != null) {
5946 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5947 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5948 systemApp = (ps.pkg.applicationInfo.flags &
5949 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005950 }
5951 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005952 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005953
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005954 if (systemApp && onSd) {
5955 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005956 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005957 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5958 return;
5959 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005960
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005961 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5962 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5963 return;
5964 }
5965 // Set application objects path explicitly after the rename
5966 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005967 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005968 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005969 replacePackageLI(pkg, parseFlags, scanMode,
5970 installerPackageName, res);
5971 } else {
5972 installNewPackageLI(pkg, parseFlags, scanMode,
5973 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 }
5975 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005976
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005977 private int setPermissionsLI(PackageParser.Package newPackage) {
5978 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005979 int retCode = 0;
5980 // TODO Gross hack but fix later. Ideally move this to be a post installation
5981 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005982 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005983 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005984 try {
5985 extractPublicFiles(newPackage, destResourceFile);
5986 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005987 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 -08005988 " forward-locked app.");
5989 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5990 } finally {
5991 //TODO clean up the extracted public files
5992 }
5993 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005994 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005995 newPackage.applicationInfo.uid);
5996 } else {
5997 final int filePermissions =
5998 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005999 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006000 newPackage.applicationInfo.uid);
6001 }
6002 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006003 // The permissions on the resource file was set when it was copied for
6004 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006005 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006007 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006008 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006009 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006010 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006011 // TODO Define new internal error
6012 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006013 }
6014 return PackageManager.INSTALL_SUCCEEDED;
6015 }
6016
Kenny Root85387d72010-08-26 10:13:11 -07006017 private static boolean isForwardLocked(PackageParser.Package pkg) {
6018 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 }
6020
Kenny Root85387d72010-08-26 10:13:11 -07006021 private static boolean isExternal(PackageParser.Package pkg) {
6022 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
6023 }
6024
6025 private static boolean isSystemApp(PackageParser.Package pkg) {
6026 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
6027 }
6028
6029 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
6030 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006031 }
6032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 private void extractPublicFiles(PackageParser.Package newPackage,
6034 File publicZipFile) throws IOException {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006035 final FileOutputStream fstr = new FileOutputStream(publicZipFile);
6036 final ZipOutputStream publicZipOutStream = new ZipOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6038
6039 // Copy manifest, resources.arsc and res directory to public zip
6040
6041 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6042 while (privateZipEntries.hasMoreElements()) {
6043 final ZipEntry zipEntry = privateZipEntries.nextElement();
6044 final String zipEntryName = zipEntry.getName();
6045 if ("AndroidManifest.xml".equals(zipEntryName)
6046 || "resources.arsc".equals(zipEntryName)
6047 || zipEntryName.startsWith("res/")) {
6048 try {
6049 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6050 } catch (IOException e) {
6051 try {
6052 publicZipOutStream.close();
6053 throw e;
6054 } finally {
6055 publicZipFile.delete();
6056 }
6057 }
6058 }
6059 }
6060
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07006061 publicZipOutStream.finish();
6062 publicZipOutStream.flush();
6063 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006064 publicZipOutStream.close();
6065 FileUtils.setPermissions(
6066 publicZipFile.getAbsolutePath(),
6067 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6068 -1, -1);
6069 }
6070
6071 private static void copyZipEntry(ZipEntry zipEntry,
6072 ZipFile inZipFile,
6073 ZipOutputStream outZipStream) throws IOException {
6074 byte[] buffer = new byte[4096];
6075 int num;
6076
6077 ZipEntry newEntry;
6078 if (zipEntry.getMethod() == ZipEntry.STORED) {
6079 // Preserve the STORED method of the input entry.
6080 newEntry = new ZipEntry(zipEntry);
6081 } else {
6082 // Create a new entry so that the compressed len is recomputed.
6083 newEntry = new ZipEntry(zipEntry.getName());
6084 }
6085 outZipStream.putNextEntry(newEntry);
6086
6087 InputStream data = inZipFile.getInputStream(zipEntry);
6088 while ((num = data.read(buffer)) > 0) {
6089 outZipStream.write(buffer, 0, num);
6090 }
6091 outZipStream.flush();
6092 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006093
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 private void deleteTempPackageFiles() {
6095 FilenameFilter filter = new FilenameFilter() {
6096 public boolean accept(File dir, String name) {
6097 return name.startsWith("vmdl") && name.endsWith(".tmp");
6098 }
6099 };
6100 String tmpFilesList[] = mAppInstallDir.list(filter);
6101 if(tmpFilesList == null) {
6102 return;
6103 }
6104 for(int i = 0; i < tmpFilesList.length; i++) {
6105 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6106 tmpFile.delete();
6107 }
6108 }
6109
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006110 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 File tmpPackageFile;
6112 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006113 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006114 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006115 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006116 return null;
6117 }
6118 try {
6119 FileUtils.setPermissions(
6120 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6121 -1, -1);
6122 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006123 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006124 return null;
6125 }
6126 return tmpPackageFile;
6127 }
6128
6129 public void deletePackage(final String packageName,
6130 final IPackageDeleteObserver observer,
6131 final int flags) {
6132 mContext.enforceCallingOrSelfPermission(
6133 android.Manifest.permission.DELETE_PACKAGES, null);
6134 // Queue up an async operation since the package deletion may take a little while.
6135 mHandler.post(new Runnable() {
6136 public void run() {
6137 mHandler.removeCallbacks(this);
6138 final boolean succeded = deletePackageX(packageName, true, true, flags);
6139 if (observer != null) {
6140 try {
6141 observer.packageDeleted(succeded);
6142 } catch (RemoteException e) {
6143 Log.i(TAG, "Observer no longer exists.");
6144 } //end catch
6145 } //end if
6146 } //end run
6147 });
6148 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006150 /**
6151 * This method is an internal method that could be get invoked either
6152 * to delete an installed package or to clean up a failed installation.
6153 * After deleting an installed package, a broadcast is sent to notify any
6154 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006155 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006156 * installation wouldn't have sent the initial broadcast either
6157 * The key steps in deleting a package are
6158 * deleting the package information in internal structures like mPackages,
6159 * deleting the packages base directories through installd
6160 * updating mSettings to reflect current status
6161 * persisting settings for later use
6162 * sending a broadcast if necessary
6163 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006164 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6165 boolean deleteCodeAndResources, int flags) {
6166 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006167 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006168
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006169 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6170 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6171 try {
6172 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006173 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006174 return false;
6175 }
6176 } catch (RemoteException e) {
6177 }
6178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006179 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006180 res = deletePackageLI(packageName, deleteCodeAndResources,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006181 flags | REMOVE_CHATTY, info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006183
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006184 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006185 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006186 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006187
6188 // If the removed package was a system update, the old system packaged
6189 // was re-enabled; we need to broadcast this information
6190 if (systemUpdate) {
6191 Bundle extras = new Bundle(1);
6192 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6193 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6194
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006195 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6196 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006199 // Force a gc here.
6200 Runtime.getRuntime().gc();
6201 // Delete the resources here after sending the broadcast to let
6202 // other processes clean up before deleting resources.
6203 if (info.args != null) {
6204 synchronized (mInstallLock) {
6205 info.args.doPostDeleteLI(deleteCodeAndResources);
6206 }
6207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006208 return res;
6209 }
6210
6211 static class PackageRemovedInfo {
6212 String removedPackage;
6213 int uid = -1;
6214 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006215 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006216 // Clean up resources deleted packages.
6217 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006218
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006219 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 Bundle extras = new Bundle(1);
6221 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6222 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6223 if (replacing) {
6224 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6225 }
6226 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006227 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006228 }
6229 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006230 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006231 }
6232 }
6233 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006235 /*
6236 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6237 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006238 * 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 -08006239 * delete a partially installed application.
6240 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006241 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006242 int flags, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006243 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006244 if (outInfo != null) {
6245 outInfo.removedPackage = packageName;
6246 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006247 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 // Retrieve object to delete permissions for shared user later on
6249 PackageSetting deletedPs;
6250 synchronized (mPackages) {
6251 deletedPs = mSettings.mPackages.get(packageName);
6252 }
6253 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006254 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006256 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006257 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006258 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 + packageName + ", retcode=" + retCode);
6260 // we don't consider this to be a failure of the core package deletion
6261 }
6262 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006263 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 PackageParser.Package pkg = mPackages.get(packageName);
6265 File dataDir = new File(pkg.applicationInfo.dataDir);
6266 dataDir.delete();
6267 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006268 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006269 }
6270 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006271 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006272 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6273 if (outInfo != null) {
6274 outInfo.removedUid = mSettings.removePackageLP(packageName);
6275 }
6276 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006277 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006278 if (deletedPs.sharedUser != null) {
6279 // remove permissions associated with package
6280 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6281 }
6282 }
6283 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006284 // remove from preferred activities.
6285 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6286 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6287 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6288 removed.add(pa);
6289 }
6290 }
6291 for (PreferredActivity pa : removed) {
6292 mSettings.mPreferredActivities.removeFilter(pa);
6293 }
6294 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006295 if (writeSettings) {
6296 // Save settings now
6297 mSettings.writeLP();
6298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 }
6300 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 /*
6303 * Tries to delete system package.
6304 */
6305 private boolean deleteSystemPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006306 int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 ApplicationInfo applicationInfo = p.applicationInfo;
6308 //applicable for non-partially installed applications only
6309 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006310 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006311 return false;
6312 }
6313 PackageSetting ps = null;
6314 // Confirm if the system package has been updated
6315 // An updated system app can be deleted. This will also have to restore
6316 // the system pkg from system partition
6317 synchronized (mPackages) {
6318 ps = mSettings.getDisabledSystemPkg(p.packageName);
6319 }
6320 if (ps == null) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006321 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006322 return false;
6323 } else {
6324 Log.i(TAG, "Deleting system pkg from data partition");
6325 }
6326 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006327 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006328 if (ps.versionCode < p.mVersionCode) {
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006329 // Delete data for downgrades
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006330 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006331 } else {
6332 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006333 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006334 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08006335 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006336 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 if (!ret) {
6338 return false;
6339 }
6340 synchronized (mPackages) {
6341 // Reinstate the old system package
6342 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006343 // Remove any native libraries from the upgraded package.
6344 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 }
6346 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006347 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Dianne Hackborn78d6883692010-10-07 01:12:46 -07006349 SCAN_MONITOR | SCAN_NO_PATHS, 0);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006352 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006353 return false;
6354 }
6355 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006356 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006357 if (writeSettings) {
6358 mSettings.writeLP();
6359 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 }
6361 return true;
6362 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 private boolean deleteInstalledPackageLI(PackageParser.Package p,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006365 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6366 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 ApplicationInfo applicationInfo = p.applicationInfo;
6368 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006369 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 return false;
6371 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006372 if (outInfo != null) {
6373 outInfo.uid = applicationInfo.uid;
6374 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006375
6376 // Delete package data from internal structures and also remove data if flag is set
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006377 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378
6379 // Delete application code and resources
6380 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006381 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006382 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6383 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6384 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6385 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 }
6387 return true;
6388 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006390 /*
6391 * This method handles package deletion in general
6392 */
6393 private boolean deletePackageLI(String packageName,
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006394 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo,
6395 boolean writeSettings) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006397 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 return false;
6399 }
6400 PackageParser.Package p;
6401 boolean dataOnly = false;
6402 synchronized (mPackages) {
6403 p = mPackages.get(packageName);
6404 if (p == null) {
6405 //this retrieves partially installed apps
6406 dataOnly = true;
6407 PackageSetting ps = mSettings.mPackages.get(packageName);
6408 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006409 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 return false;
6411 }
6412 p = ps.pkg;
6413 }
6414 }
6415 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006416 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 return false;
6418 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 if (dataOnly) {
6421 // Delete application data first
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006422 removePackageDataLI(p, outInfo, flags, writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 return true;
6424 }
6425 // At this point the package should have ApplicationInfo associated with it
6426 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006427 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006428 return false;
6429 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006430 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006431 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006432 Log.i(TAG, "Removing system package:"+p.packageName);
6433 // When an updated system application is deleted we delete the existing resources as well and
6434 // fall back to existing code in system partition
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006435 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006436 } else {
6437 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006438 // Kill application pre-emptively especially for apps on sd.
6439 killApplication(packageName, p.applicationInfo.uid);
Dianne Hackborn3aeee332010-10-02 18:56:33 -07006440 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo,
6441 writeSettings);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006442 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006443 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006446 public void clearApplicationUserData(final String packageName,
6447 final IPackageDataObserver observer) {
6448 mContext.enforceCallingOrSelfPermission(
6449 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6450 // Queue up an async operation since the package deletion may take a little while.
6451 mHandler.post(new Runnable() {
6452 public void run() {
6453 mHandler.removeCallbacks(this);
6454 final boolean succeeded;
6455 synchronized (mInstallLock) {
6456 succeeded = clearApplicationUserDataLI(packageName);
6457 }
6458 if (succeeded) {
6459 // invoke DeviceStorageMonitor's update method to clear any notifications
6460 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6461 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6462 if (dsm != null) {
6463 dsm.updateMemory();
6464 }
6465 }
6466 if(observer != null) {
6467 try {
6468 observer.onRemoveCompleted(packageName, succeeded);
6469 } catch (RemoteException e) {
6470 Log.i(TAG, "Observer no longer exists.");
6471 }
6472 } //end if observer
6473 } //end run
6474 });
6475 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 private boolean clearApplicationUserDataLI(String packageName) {
6478 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006479 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 return false;
6481 }
6482 PackageParser.Package p;
6483 boolean dataOnly = false;
6484 synchronized (mPackages) {
6485 p = mPackages.get(packageName);
6486 if(p == null) {
6487 dataOnly = true;
6488 PackageSetting ps = mSettings.mPackages.get(packageName);
6489 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006490 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006491 return false;
6492 }
6493 p = ps.pkg;
6494 }
6495 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006496 boolean useEncryptedFSDir = false;
6497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 if(!dataOnly) {
6499 //need to check this only for fully installed applications
6500 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006501 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006502 return false;
6503 }
6504 final ApplicationInfo applicationInfo = p.applicationInfo;
6505 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006506 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 return false;
6508 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006509 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 }
6511 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006512 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006513 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006514 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006515 + packageName);
6516 return false;
6517 }
6518 }
6519 return true;
6520 }
6521
6522 public void deleteApplicationCacheFiles(final String packageName,
6523 final IPackageDataObserver observer) {
6524 mContext.enforceCallingOrSelfPermission(
6525 android.Manifest.permission.DELETE_CACHE_FILES, null);
6526 // Queue up an async operation since the package deletion may take a little while.
6527 mHandler.post(new Runnable() {
6528 public void run() {
6529 mHandler.removeCallbacks(this);
6530 final boolean succeded;
6531 synchronized (mInstallLock) {
6532 succeded = deleteApplicationCacheFilesLI(packageName);
6533 }
6534 if(observer != null) {
6535 try {
6536 observer.onRemoveCompleted(packageName, succeded);
6537 } catch (RemoteException e) {
6538 Log.i(TAG, "Observer no longer exists.");
6539 }
6540 } //end if observer
6541 } //end run
6542 });
6543 }
6544
6545 private boolean deleteApplicationCacheFilesLI(String packageName) {
6546 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006547 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 return false;
6549 }
6550 PackageParser.Package p;
6551 synchronized (mPackages) {
6552 p = mPackages.get(packageName);
6553 }
6554 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006555 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556 return false;
6557 }
6558 final ApplicationInfo applicationInfo = p.applicationInfo;
6559 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006560 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006561 return false;
6562 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006563 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006564 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006565 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006567 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006568 + packageName);
6569 return false;
6570 }
6571 }
6572 return true;
6573 }
6574
6575 public void getPackageSizeInfo(final String packageName,
6576 final IPackageStatsObserver observer) {
6577 mContext.enforceCallingOrSelfPermission(
6578 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6579 // Queue up an async operation since the package deletion may take a little while.
6580 mHandler.post(new Runnable() {
6581 public void run() {
6582 mHandler.removeCallbacks(this);
6583 PackageStats lStats = new PackageStats(packageName);
6584 final boolean succeded;
6585 synchronized (mInstallLock) {
6586 succeded = getPackageSizeInfoLI(packageName, lStats);
6587 }
6588 if(observer != null) {
6589 try {
6590 observer.onGetStatsCompleted(lStats, succeded);
6591 } catch (RemoteException e) {
6592 Log.i(TAG, "Observer no longer exists.");
6593 }
6594 } //end if observer
6595 } //end run
6596 });
6597 }
6598
6599 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6600 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006601 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 return false;
6603 }
6604 PackageParser.Package p;
6605 boolean dataOnly = false;
6606 synchronized (mPackages) {
6607 p = mPackages.get(packageName);
6608 if(p == null) {
6609 dataOnly = true;
6610 PackageSetting ps = mSettings.mPackages.get(packageName);
6611 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006612 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006613 return false;
6614 }
6615 p = ps.pkg;
6616 }
6617 }
6618 String publicSrcDir = null;
6619 if(!dataOnly) {
6620 final ApplicationInfo applicationInfo = p.applicationInfo;
6621 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006622 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 return false;
6624 }
6625 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6626 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006627 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006628 if (mInstaller != null) {
6629 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006630 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 if (res < 0) {
6632 return false;
6633 } else {
6634 return true;
6635 }
6636 }
6637 return true;
6638 }
6639
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006642 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006643 }
6644
6645 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006646 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006647 }
6648
6649 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006650 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006651 }
6652
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006653 int getUidTargetSdkVersionLockedLP(int uid) {
6654 Object obj = mSettings.getUserIdLP(uid);
6655 if (obj instanceof SharedUserSetting) {
6656 SharedUserSetting sus = (SharedUserSetting)obj;
6657 final int N = sus.packages.size();
6658 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6659 Iterator<PackageSetting> it = sus.packages.iterator();
6660 int i=0;
6661 while (it.hasNext()) {
6662 PackageSetting ps = it.next();
6663 if (ps.pkg != null) {
6664 int v = ps.pkg.applicationInfo.targetSdkVersion;
6665 if (v < vers) vers = v;
6666 }
6667 }
6668 return vers;
6669 } else if (obj instanceof PackageSetting) {
6670 PackageSetting ps = (PackageSetting)obj;
6671 if (ps.pkg != null) {
6672 return ps.pkg.applicationInfo.targetSdkVersion;
6673 }
6674 }
6675 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6676 }
6677
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006678 public void addPreferredActivity(IntentFilter filter, int match,
6679 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006680 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006681 if (mContext.checkCallingOrSelfPermission(
6682 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6683 != PackageManager.PERMISSION_GRANTED) {
6684 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6685 < Build.VERSION_CODES.FROYO) {
6686 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6687 + Binder.getCallingUid());
6688 return;
6689 }
6690 mContext.enforceCallingOrSelfPermission(
6691 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6692 }
6693
6694 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6696 mSettings.mPreferredActivities.addFilter(
6697 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006698 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 }
6700 }
6701
Satish Sampath8dbe6122009-06-02 23:35:54 +01006702 public void replacePreferredActivity(IntentFilter filter, int match,
6703 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006704 if (filter.countActions() != 1) {
6705 throw new IllegalArgumentException(
6706 "replacePreferredActivity expects filter to have only 1 action.");
6707 }
6708 if (filter.countCategories() != 1) {
6709 throw new IllegalArgumentException(
6710 "replacePreferredActivity expects filter to have only 1 category.");
6711 }
6712 if (filter.countDataAuthorities() != 0
6713 || filter.countDataPaths() != 0
6714 || filter.countDataSchemes() != 0
6715 || filter.countDataTypes() != 0) {
6716 throw new IllegalArgumentException(
6717 "replacePreferredActivity expects filter to have no data authorities, " +
6718 "paths, schemes or types.");
6719 }
6720 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006721 if (mContext.checkCallingOrSelfPermission(
6722 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6723 != PackageManager.PERMISSION_GRANTED) {
6724 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6725 < Build.VERSION_CODES.FROYO) {
6726 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6727 + Binder.getCallingUid());
6728 return;
6729 }
6730 mContext.enforceCallingOrSelfPermission(
6731 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6732 }
6733
Satish Sampath8dbe6122009-06-02 23:35:54 +01006734 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6735 String action = filter.getAction(0);
6736 String category = filter.getCategory(0);
6737 while (it.hasNext()) {
6738 PreferredActivity pa = it.next();
6739 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6740 it.remove();
6741 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6742 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6743 }
6744 }
6745 addPreferredActivity(filter, match, set, activity);
6746 }
6747 }
6748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006750 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006751 int uid = Binder.getCallingUid();
6752 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006753 if (pkg == null || pkg.applicationInfo.uid != uid) {
6754 if (mContext.checkCallingOrSelfPermission(
6755 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6756 != PackageManager.PERMISSION_GRANTED) {
6757 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6758 < Build.VERSION_CODES.FROYO) {
6759 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6760 + Binder.getCallingUid());
6761 return;
6762 }
6763 mContext.enforceCallingOrSelfPermission(
6764 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6765 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006766 }
6767
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006769 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 }
6771 }
6772 }
6773
6774 boolean clearPackagePreferredActivitiesLP(String packageName) {
6775 boolean changed = false;
6776 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6777 while (it.hasNext()) {
6778 PreferredActivity pa = it.next();
6779 if (pa.mActivity.getPackageName().equals(packageName)) {
6780 it.remove();
6781 changed = true;
6782 }
6783 }
6784 return changed;
6785 }
6786
6787 public int getPreferredActivities(List<IntentFilter> outFilters,
6788 List<ComponentName> outActivities, String packageName) {
6789
6790 int num = 0;
6791 synchronized (mPackages) {
6792 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6793 while (it.hasNext()) {
6794 PreferredActivity pa = it.next();
6795 if (packageName == null
6796 || pa.mActivity.getPackageName().equals(packageName)) {
6797 if (outFilters != null) {
6798 outFilters.add(new IntentFilter(pa));
6799 }
6800 if (outActivities != null) {
6801 outActivities.add(pa.mActivity);
6802 }
6803 }
6804 }
6805 }
6806
6807 return num;
6808 }
6809
6810 public void setApplicationEnabledSetting(String appPackageName,
6811 int newState, int flags) {
6812 setEnabledSetting(appPackageName, null, newState, flags);
6813 }
6814
6815 public void setComponentEnabledSetting(ComponentName componentName,
6816 int newState, int flags) {
6817 setEnabledSetting(componentName.getPackageName(),
6818 componentName.getClassName(), newState, flags);
6819 }
6820
6821 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006822 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006823 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6824 || newState == COMPONENT_ENABLED_STATE_ENABLED
6825 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6826 throw new IllegalArgumentException("Invalid new component state: "
6827 + newState);
6828 }
6829 PackageSetting pkgSetting;
6830 final int uid = Binder.getCallingUid();
6831 final int permission = mContext.checkCallingPermission(
6832 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6833 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006834 boolean sendNow = false;
6835 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006836 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006837 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006838 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006839 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006840 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006842 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006843 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006844 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006845 }
6846 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006847 "Unknown component: " + packageName
6848 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006849 }
6850 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6851 throw new SecurityException(
6852 "Permission Denial: attempt to change component state from pid="
6853 + Binder.getCallingPid()
6854 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6855 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006856 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006858 if (pkgSetting.enabled == newState) {
6859 // Nothing to do
6860 return;
6861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006862 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006863 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006864 } else {
6865 // We're dealing with a component level state change
6866 switch (newState) {
6867 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006868 if (!pkgSetting.enableComponentLP(className)) {
6869 return;
6870 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006871 break;
6872 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006873 if (!pkgSetting.disableComponentLP(className)) {
6874 return;
6875 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006876 break;
6877 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006878 if (!pkgSetting.restoreComponentLP(className)) {
6879 return;
6880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006881 break;
6882 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006883 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006884 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006885 }
6886 }
6887 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006888 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006889 components = mPendingBroadcasts.get(packageName);
6890 boolean newPackage = components == null;
6891 if (newPackage) {
6892 components = new ArrayList<String>();
6893 }
6894 if (!components.contains(componentName)) {
6895 components.add(componentName);
6896 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006897 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6898 sendNow = true;
6899 // Purge entry from pending broadcast list if another one exists already
6900 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006901 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006902 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006903 if (newPackage) {
6904 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006905 }
6906 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6907 // Schedule a message
6908 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6909 }
6910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006911 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006913 long callingId = Binder.clearCallingIdentity();
6914 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006915 if (sendNow) {
6916 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006917 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006918 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006919 } finally {
6920 Binder.restoreCallingIdentity(callingId);
6921 }
6922 }
6923
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006924 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006925 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6926 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6927 + " components=" + componentNames);
6928 Bundle extras = new Bundle(4);
6929 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6930 String nameList[] = new String[componentNames.size()];
6931 componentNames.toArray(nameList);
6932 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006933 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6934 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006935 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006936 }
6937
Jacek Surazski65e13172009-04-28 15:26:38 +02006938 public String getInstallerPackageName(String packageName) {
6939 synchronized (mPackages) {
6940 PackageSetting pkg = mSettings.mPackages.get(packageName);
6941 if (pkg == null) {
6942 throw new IllegalArgumentException("Unknown package: " + packageName);
6943 }
6944 return pkg.installerPackageName;
6945 }
6946 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006947
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006948 public int getApplicationEnabledSetting(String appPackageName) {
6949 synchronized (mPackages) {
6950 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6951 if (pkg == null) {
6952 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6953 }
6954 return pkg.enabled;
6955 }
6956 }
6957
6958 public int getComponentEnabledSetting(ComponentName componentName) {
6959 synchronized (mPackages) {
6960 final String packageNameStr = componentName.getPackageName();
6961 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6962 if (pkg == null) {
6963 throw new IllegalArgumentException("Unknown component: " + componentName);
6964 }
6965 final String classNameStr = componentName.getClassName();
6966 return pkg.currentEnabledStateLP(classNameStr);
6967 }
6968 }
6969
6970 public void enterSafeMode() {
6971 if (!mSystemReady) {
6972 mSafeMode = true;
6973 }
6974 }
6975
6976 public void systemReady() {
6977 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006978
6979 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006980 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006981 mContext.getContentResolver(),
6982 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006983 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006984 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006985 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006987 }
6988
6989 public boolean isSafeMode() {
6990 return mSafeMode;
6991 }
6992
6993 public boolean hasSystemUidErrors() {
6994 return mHasSystemUidErrors;
6995 }
6996
6997 static String arrayToString(int[] array) {
6998 StringBuffer buf = new StringBuffer(128);
6999 buf.append('[');
7000 if (array != null) {
7001 for (int i=0; i<array.length; i++) {
7002 if (i > 0) buf.append(", ");
7003 buf.append(array[i]);
7004 }
7005 }
7006 buf.append(']');
7007 return buf.toString();
7008 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007010 @Override
7011 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7012 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7013 != PackageManager.PERMISSION_GRANTED) {
7014 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7015 + Binder.getCallingPid()
7016 + ", uid=" + Binder.getCallingUid()
7017 + " without permission "
7018 + android.Manifest.permission.DUMP);
7019 return;
7020 }
7021
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007022 boolean dumpStar = true;
7023 boolean dumpLibs = false;
7024 boolean dumpFeatures = false;
7025 boolean dumpResolvers = false;
7026 boolean dumpPermissions = false;
7027 boolean dumpPackages = false;
7028 boolean dumpSharedUsers = false;
7029 boolean dumpMessages = false;
7030 boolean dumpProviders = false;
7031
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007032 String packageName = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007033 boolean showFilters = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007034
7035 int opti = 0;
7036 while (opti < args.length) {
7037 String opt = args[opti];
7038 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7039 break;
7040 }
7041 opti++;
7042 if ("-a".equals(opt)) {
7043 // Right now we only know how to print all.
7044 } else if ("-h".equals(opt)) {
7045 pw.println("Package manager dump options:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007046 pw.println(" [-h] [-f] [cmd] ...");
7047 pw.println(" -f: print details of intent filters");
7048 pw.println(" -h: print this help");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007049 pw.println(" cmd may be one of:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007050 pw.println(" l[ibraries]: list known shared libraries");
7051 pw.println(" f[ibraries]: list device features");
7052 pw.println(" r[esolvers]: dump intent resolvers");
7053 pw.println(" perm[issions]: dump permissions");
7054 pw.println(" prov[iders]: dump content providers");
7055 pw.println(" p[ackages]: dump installed packages");
7056 pw.println(" s[hared-users]: dump shared user IDs");
7057 pw.println(" m[essages]: print collected runtime messages");
7058 pw.println(" <package.name>: info about given package");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007059 return;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007060 } else if ("-f".equals(opt)) {
7061 showFilters = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007062 } else {
7063 pw.println("Unknown argument: " + opt + "; use -h for help");
7064 }
7065 }
7066
7067 // Is the caller requesting to dump a particular piece of data?
7068 if (opti < args.length) {
7069 String cmd = args[opti];
7070 opti++;
7071 // Is this a package name?
7072 if ("android".equals(cmd) || cmd.contains(".")) {
7073 packageName = cmd;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007074 } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
7075 dumpStar = false;
7076 dumpLibs = true;
7077 } else if ("f".equals(cmd) || "features".equals(cmd)) {
7078 dumpStar = false;
7079 dumpFeatures = true;
7080 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
7081 dumpStar = false;
7082 dumpResolvers = true;
7083 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
7084 dumpStar = false;
7085 dumpPermissions = true;
7086 } else if ("p".equals(cmd) || "packages".equals(cmd)) {
7087 dumpStar = false;
7088 dumpPackages = true;
7089 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
7090 dumpStar = false;
7091 dumpSharedUsers = true;
7092 } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
7093 dumpStar = false;
7094 dumpProviders = true;
7095 } else if ("m".equals(cmd) || "messages".equals(cmd)) {
7096 dumpStar = false;
7097 dumpMessages = true;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007098 }
7099 }
7100
7101 boolean printedTitle = false;
7102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 synchronized (mPackages) {
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007104 if ((dumpStar || dumpLibs) && packageName == null) {
7105 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007106 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007107 pw.println("Libraries:");
7108 Iterator<String> it = mSharedLibraries.keySet().iterator();
7109 while (it.hasNext()) {
7110 String name = it.next();
7111 pw.print(" ");
7112 pw.print(name);
7113 pw.print(" -> ");
7114 pw.println(mSharedLibraries.get(name));
7115 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007116 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007117
7118 if ((dumpStar || dumpFeatures) && packageName == null) {
7119 if (printedTitle) pw.println(" ");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007120 printedTitle = true;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007121 pw.println("Features:");
7122 Iterator<String> it = mAvailableFeatures.keySet().iterator();
7123 while (it.hasNext()) {
7124 String name = it.next();
7125 pw.print(" ");
7126 pw.println(name);
7127 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007128 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007129
7130 if (dumpStar || dumpResolvers) {
7131 if (mActivities.dump(pw, printedTitle
7132 ? "\nActivity Resolver Table:" : "Activity Resolver Table:",
7133 " ", packageName, showFilters)) {
7134 printedTitle = true;
7135 }
7136 if (mReceivers.dump(pw, printedTitle
7137 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7138 " ", packageName, showFilters)) {
7139 printedTitle = true;
7140 }
7141 if (mServices.dump(pw, printedTitle
7142 ? "\nService Resolver Table:" : "Service Resolver Table:",
7143 " ", packageName, showFilters)) {
7144 printedTitle = true;
7145 }
7146 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7147 ? "\nPreferred Activities:" : "Preferred Activities:",
7148 " ", packageName, showFilters)) {
7149 printedTitle = true;
7150 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007151 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007152
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007153 boolean printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007154 if (dumpStar || dumpPermissions) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007155 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007156 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7157 continue;
7158 }
7159 if (!printedSomething) {
7160 if (printedTitle) pw.println(" ");
7161 pw.println("Permissions:");
7162 printedSomething = true;
7163 printedTitle = true;
7164 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007165 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7166 pw.print(Integer.toHexString(System.identityHashCode(p)));
7167 pw.println("):");
7168 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7169 pw.print(" uid="); pw.print(p.uid);
7170 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007171 pw.print(" type="); pw.print(p.type);
7172 pw.print(" prot="); pw.println(p.protectionLevel);
7173 if (p.packageSetting != null) {
7174 pw.print(" packageSetting="); pw.println(p.packageSetting);
7175 }
7176 if (p.perm != null) {
7177 pw.print(" perm="); pw.println(p.perm);
7178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 }
7180 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007181
7182 if (dumpStar || dumpProviders) {
7183 printedSomething = false;
7184 for (PackageParser.Provider p : mProviders.values()) {
7185 if (packageName != null && !packageName.equals(p.info.packageName)) {
7186 continue;
7187 }
7188 if (!printedSomething) {
7189 if (printedTitle) pw.println(" ");
7190 pw.println("Registered ContentProviders:");
7191 printedSomething = true;
7192 printedTitle = true;
7193 }
7194 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
7195 pw.println(p.toString());
7196 }
7197 }
7198
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007199 printedSomething = false;
7200 SharedUserSetting packageSharedUser = null;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007201 if (dumpStar || dumpPackages) {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007202 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
7203 Date date = new Date();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007204 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007205 if (packageName != null && !packageName.equals(ps.realName)
7206 && !packageName.equals(ps.name)) {
7207 continue;
7208 }
7209 if (!printedSomething) {
7210 if (printedTitle) pw.println(" ");
7211 pw.println("Packages:");
7212 printedSomething = true;
7213 printedTitle = true;
7214 }
7215 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007216 pw.print(" Package [");
7217 pw.print(ps.realName != null ? ps.realName : ps.name);
7218 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007219 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7220 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007221 if (ps.realName != null) {
7222 pw.print(" compat name="); pw.println(ps.name);
7223 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007224 pw.print(" userId="); pw.print(ps.userId);
7225 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7226 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7227 pw.print(" pkg="); pw.println(ps.pkg);
7228 pw.print(" codePath="); pw.println(ps.codePathString);
7229 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07007230 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007231 pw.print(" obbPath="); pw.println(ps.obbPathString);
Kenny Root1174f712010-10-22 10:07:11 -07007232 pw.print(" versionCode="); pw.println(ps.versionCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007233 if (ps.pkg != null) {
Kenny Root1174f712010-10-22 10:07:11 -07007234 pw.print(" versionName="); pw.println(ps.pkg.mVersionName);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007235 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007236 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07007237 if (ps.pkg.mOperationPending) {
7238 pw.println(" mOperationPending=true");
7239 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007240 pw.print(" supportsScreens=[");
7241 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007242 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007243 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7244 if (!first) pw.print(", ");
7245 first = false;
7246 pw.print("small");
7247 }
7248 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007249 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007250 if (!first) pw.print(", ");
7251 first = false;
7252 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007253 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007254 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007255 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007256 if (!first) pw.print(", ");
7257 first = false;
7258 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007259 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007260 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007261 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007262 if (!first) pw.print(", ");
7263 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007264 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007266 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007267 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007268 if (!first) pw.print(", ");
7269 first = false;
7270 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007271 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007272 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007273 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7274 if (!first) pw.print(", ");
7275 first = false;
7276 pw.print("anyDensity");
7277 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007278 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007279 pw.println("]");
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007280 pw.print(" timeStamp=");
7281 date.setTime(ps.timeStamp); pw.println(sdf.format(date));
7282 pw.print(" firstInstallTime=");
7283 date.setTime(ps.firstInstallTime); pw.println(sdf.format(date));
7284 pw.print(" lastUpdateTime=");
7285 date.setTime(ps.lastUpdateTime); pw.println(sdf.format(date));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007286 pw.print(" signatures="); pw.println(ps.signatures);
7287 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007288 pw.print(" haveGids="); pw.println(ps.haveGids);
7289 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007290 pw.print(" installStatus="); pw.print(ps.installStatus);
7291 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007292 if (ps.disabledComponents.size() > 0) {
7293 pw.println(" disabledComponents:");
7294 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007295 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007296 }
7297 }
7298 if (ps.enabledComponents.size() > 0) {
7299 pw.println(" enabledComponents:");
7300 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007301 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007302 }
7303 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007304 if (ps.grantedPermissions.size() > 0) {
7305 pw.println(" grantedPermissions:");
7306 for (String s : ps.grantedPermissions) {
7307 pw.print(" "); pw.println(s);
7308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 }
7311 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007312 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007313 if (dumpStar || dumpPackages) {
7314 if (mSettings.mRenamedPackages.size() > 0) {
7315 for (HashMap.Entry<String, String> e
7316 : mSettings.mRenamedPackages.entrySet()) {
7317 if (packageName != null && !packageName.equals(e.getKey())
7318 && !packageName.equals(e.getValue())) {
7319 continue;
7320 }
7321 if (!printedSomething) {
7322 if (printedTitle) pw.println(" ");
7323 pw.println("Renamed packages:");
7324 printedSomething = true;
7325 printedTitle = true;
7326 }
7327 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7328 pw.println(e.getValue());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007329 }
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007330 }
7331 printedSomething = false;
7332 if (mSettings.mDisabledSysPackages.size() > 0) {
7333 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
7334 if (packageName != null && !packageName.equals(ps.realName)
7335 && !packageName.equals(ps.name)) {
7336 continue;
7337 }
7338 if (!printedSomething) {
7339 if (printedTitle) pw.println(" ");
7340 pw.println("Hidden system packages:");
7341 printedSomething = true;
7342 printedTitle = true;
7343 }
7344 pw.print(" Package [");
7345 pw.print(ps.realName != null ? ps.realName : ps.name);
7346 pw.print("] (");
7347 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7348 pw.println("):");
7349 if (ps.realName != null) {
7350 pw.print(" compat name="); pw.println(ps.name);
7351 }
7352 pw.print(" userId="); pw.println(ps.userId);
7353 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7354 pw.print(" codePath="); pw.println(ps.codePathString);
7355 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007356 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007357 }
7358 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007359 printedSomething = false;
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007360 if (dumpStar || dumpSharedUsers) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007361 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007362 if (packageName != null && su != packageSharedUser) {
7363 continue;
7364 }
7365 if (!printedSomething) {
7366 if (printedTitle) pw.println(" ");
7367 pw.println("Shared users:");
7368 printedSomething = true;
7369 printedTitle = true;
7370 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007371 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7372 pw.print(Integer.toHexString(System.identityHashCode(su)));
7373 pw.println("):");
7374 pw.print(" userId="); pw.print(su.userId);
7375 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007376 pw.println(" grantedPermissions:");
7377 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007378 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007380 }
7381 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007382
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007383 if ((dumpStar || dumpMessages) && packageName == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007384 if (printedTitle) pw.println(" ");
7385 printedTitle = true;
7386 pw.println("Settings parse messages:");
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007387 pw.print(mSettings.mReadMessages.toString());
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007388
7389 pw.println(" ");
7390 pw.println("Package warning messages:");
7391 File fname = getSettingsProblemFile();
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08007392 FileInputStream in = null;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007393 try {
7394 in = new FileInputStream(fname);
7395 int avail = in.available();
7396 byte[] data = new byte[avail];
7397 in.read(data);
Dianne Hackborncef65ee2010-09-30 18:27:22 -07007398 pw.print(new String(data));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007399 } catch (FileNotFoundException e) {
7400 } catch (IOException e) {
Brad Fitzpatrick6689ac82010-11-15 16:26:04 -08007401 } finally {
7402 if (in != null) {
7403 try {
7404 in.close();
7405 } catch (IOException e) {
7406 }
7407 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007408 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007409 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007410 }
7411 }
7412
7413 static final class BasePermission {
7414 final static int TYPE_NORMAL = 0;
7415 final static int TYPE_BUILTIN = 1;
7416 final static int TYPE_DYNAMIC = 2;
7417
7418 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007419 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007420 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007421 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007422 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007423 PackageParser.Permission perm;
7424 PermissionInfo pendingInfo;
7425 int uid;
7426 int[] gids;
7427
7428 BasePermission(String _name, String _sourcePackage, int _type) {
7429 name = _name;
7430 sourcePackage = _sourcePackage;
7431 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007432 // Default to most conservative protection level.
7433 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7434 }
7435
7436 public String toString() {
7437 return "BasePermission{"
7438 + Integer.toHexString(System.identityHashCode(this))
7439 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007440 }
7441 }
7442
7443 static class PackageSignatures {
7444 private Signature[] mSignatures;
7445
7446 PackageSignatures(Signature[] sigs) {
7447 assignSignatures(sigs);
7448 }
7449
7450 PackageSignatures() {
7451 }
7452
7453 void writeXml(XmlSerializer serializer, String tagName,
7454 ArrayList<Signature> pastSignatures) throws IOException {
7455 if (mSignatures == null) {
7456 return;
7457 }
7458 serializer.startTag(null, tagName);
7459 serializer.attribute(null, "count",
7460 Integer.toString(mSignatures.length));
7461 for (int i=0; i<mSignatures.length; i++) {
7462 serializer.startTag(null, "cert");
7463 final Signature sig = mSignatures[i];
7464 final int sigHash = sig.hashCode();
7465 final int numPast = pastSignatures.size();
7466 int j;
7467 for (j=0; j<numPast; j++) {
7468 Signature pastSig = pastSignatures.get(j);
7469 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7470 serializer.attribute(null, "index", Integer.toString(j));
7471 break;
7472 }
7473 }
7474 if (j >= numPast) {
7475 pastSignatures.add(sig);
7476 serializer.attribute(null, "index", Integer.toString(numPast));
7477 serializer.attribute(null, "key", sig.toCharsString());
7478 }
7479 serializer.endTag(null, "cert");
7480 }
7481 serializer.endTag(null, tagName);
7482 }
7483
7484 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7485 throws IOException, XmlPullParserException {
7486 String countStr = parser.getAttributeValue(null, "count");
7487 if (countStr == null) {
7488 reportSettingsProblem(Log.WARN,
7489 "Error in package manager settings: <signatures> has"
7490 + " no count at " + parser.getPositionDescription());
7491 XmlUtils.skipCurrentTag(parser);
7492 }
7493 final int count = Integer.parseInt(countStr);
7494 mSignatures = new Signature[count];
7495 int pos = 0;
7496
7497 int outerDepth = parser.getDepth();
7498 int type;
7499 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7500 && (type != XmlPullParser.END_TAG
7501 || parser.getDepth() > outerDepth)) {
7502 if (type == XmlPullParser.END_TAG
7503 || type == XmlPullParser.TEXT) {
7504 continue;
7505 }
7506
7507 String tagName = parser.getName();
7508 if (tagName.equals("cert")) {
7509 if (pos < count) {
7510 String index = parser.getAttributeValue(null, "index");
7511 if (index != null) {
7512 try {
7513 int idx = Integer.parseInt(index);
7514 String key = parser.getAttributeValue(null, "key");
7515 if (key == null) {
7516 if (idx >= 0 && idx < pastSignatures.size()) {
7517 Signature sig = pastSignatures.get(idx);
7518 if (sig != null) {
7519 mSignatures[pos] = pastSignatures.get(idx);
7520 pos++;
7521 } else {
7522 reportSettingsProblem(Log.WARN,
7523 "Error in package manager settings: <cert> "
7524 + "index " + index + " is not defined at "
7525 + parser.getPositionDescription());
7526 }
7527 } else {
7528 reportSettingsProblem(Log.WARN,
7529 "Error in package manager settings: <cert> "
7530 + "index " + index + " is out of bounds at "
7531 + parser.getPositionDescription());
7532 }
7533 } else {
7534 while (pastSignatures.size() <= idx) {
7535 pastSignatures.add(null);
7536 }
7537 Signature sig = new Signature(key);
7538 pastSignatures.set(idx, sig);
7539 mSignatures[pos] = sig;
7540 pos++;
7541 }
7542 } catch (NumberFormatException e) {
7543 reportSettingsProblem(Log.WARN,
7544 "Error in package manager settings: <cert> "
7545 + "index " + index + " is not a number at "
7546 + parser.getPositionDescription());
7547 }
7548 } else {
7549 reportSettingsProblem(Log.WARN,
7550 "Error in package manager settings: <cert> has"
7551 + " no index at " + parser.getPositionDescription());
7552 }
7553 } else {
7554 reportSettingsProblem(Log.WARN,
7555 "Error in package manager settings: too "
7556 + "many <cert> tags, expected " + count
7557 + " at " + parser.getPositionDescription());
7558 }
7559 } else {
7560 reportSettingsProblem(Log.WARN,
7561 "Unknown element under <cert>: "
7562 + parser.getName());
7563 }
7564 XmlUtils.skipCurrentTag(parser);
7565 }
7566
7567 if (pos < count) {
7568 // Should never happen -- there is an error in the written
7569 // settings -- but if it does we don't want to generate
7570 // a bad array.
7571 Signature[] newSigs = new Signature[pos];
7572 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7573 mSignatures = newSigs;
7574 }
7575 }
7576
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007577 private void assignSignatures(Signature[] sigs) {
7578 if (sigs == null) {
7579 mSignatures = null;
7580 return;
7581 }
7582 mSignatures = new Signature[sigs.length];
7583 for (int i=0; i<sigs.length; i++) {
7584 mSignatures[i] = sigs[i];
7585 }
7586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 @Override
7589 public String toString() {
7590 StringBuffer buf = new StringBuffer(128);
7591 buf.append("PackageSignatures{");
7592 buf.append(Integer.toHexString(System.identityHashCode(this)));
7593 buf.append(" [");
7594 if (mSignatures != null) {
7595 for (int i=0; i<mSignatures.length; i++) {
7596 if (i > 0) buf.append(", ");
7597 buf.append(Integer.toHexString(
7598 System.identityHashCode(mSignatures[i])));
7599 }
7600 }
7601 buf.append("]}");
7602 return buf.toString();
7603 }
7604 }
7605
7606 static class PreferredActivity extends IntentFilter {
7607 final int mMatch;
7608 final String[] mSetPackages;
7609 final String[] mSetClasses;
7610 final String[] mSetComponents;
7611 final ComponentName mActivity;
7612 final String mShortActivity;
7613 String mParseError;
7614
7615 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7616 ComponentName activity) {
7617 super(filter);
7618 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7619 mActivity = activity;
7620 mShortActivity = activity.flattenToShortString();
7621 mParseError = null;
7622 if (set != null) {
7623 final int N = set.length;
7624 String[] myPackages = new String[N];
7625 String[] myClasses = new String[N];
7626 String[] myComponents = new String[N];
7627 for (int i=0; i<N; i++) {
7628 ComponentName cn = set[i];
7629 if (cn == null) {
7630 mSetPackages = null;
7631 mSetClasses = null;
7632 mSetComponents = null;
7633 return;
7634 }
7635 myPackages[i] = cn.getPackageName().intern();
7636 myClasses[i] = cn.getClassName().intern();
7637 myComponents[i] = cn.flattenToShortString().intern();
7638 }
7639 mSetPackages = myPackages;
7640 mSetClasses = myClasses;
7641 mSetComponents = myComponents;
7642 } else {
7643 mSetPackages = null;
7644 mSetClasses = null;
7645 mSetComponents = null;
7646 }
7647 }
7648
7649 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7650 IOException {
7651 mShortActivity = parser.getAttributeValue(null, "name");
7652 mActivity = ComponentName.unflattenFromString(mShortActivity);
7653 if (mActivity == null) {
7654 mParseError = "Bad activity name " + mShortActivity;
7655 }
7656 String matchStr = parser.getAttributeValue(null, "match");
7657 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7658 String setCountStr = parser.getAttributeValue(null, "set");
7659 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7660
7661 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7662 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7663 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7664
7665 int setPos = 0;
7666
7667 int outerDepth = parser.getDepth();
7668 int type;
7669 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7670 && (type != XmlPullParser.END_TAG
7671 || parser.getDepth() > outerDepth)) {
7672 if (type == XmlPullParser.END_TAG
7673 || type == XmlPullParser.TEXT) {
7674 continue;
7675 }
7676
7677 String tagName = parser.getName();
7678 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7679 // + parser.getDepth() + " tag=" + tagName);
7680 if (tagName.equals("set")) {
7681 String name = parser.getAttributeValue(null, "name");
7682 if (name == null) {
7683 if (mParseError == null) {
7684 mParseError = "No name in set tag in preferred activity "
7685 + mShortActivity;
7686 }
7687 } else if (setPos >= setCount) {
7688 if (mParseError == null) {
7689 mParseError = "Too many set tags in preferred activity "
7690 + mShortActivity;
7691 }
7692 } else {
7693 ComponentName cn = ComponentName.unflattenFromString(name);
7694 if (cn == null) {
7695 if (mParseError == null) {
7696 mParseError = "Bad set name " + name + " in preferred activity "
7697 + mShortActivity;
7698 }
7699 } else {
7700 myPackages[setPos] = cn.getPackageName();
7701 myClasses[setPos] = cn.getClassName();
7702 myComponents[setPos] = name;
7703 setPos++;
7704 }
7705 }
7706 XmlUtils.skipCurrentTag(parser);
7707 } else if (tagName.equals("filter")) {
7708 //Log.i(TAG, "Starting to parse filter...");
7709 readFromXml(parser);
7710 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7711 // + parser.getDepth() + " tag=" + parser.getName());
7712 } else {
7713 reportSettingsProblem(Log.WARN,
7714 "Unknown element under <preferred-activities>: "
7715 + parser.getName());
7716 XmlUtils.skipCurrentTag(parser);
7717 }
7718 }
7719
7720 if (setPos != setCount) {
7721 if (mParseError == null) {
7722 mParseError = "Not enough set tags (expected " + setCount
7723 + " but found " + setPos + ") in " + mShortActivity;
7724 }
7725 }
7726
7727 mSetPackages = myPackages;
7728 mSetClasses = myClasses;
7729 mSetComponents = myComponents;
7730 }
7731
7732 public void writeToXml(XmlSerializer serializer) throws IOException {
7733 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7734 serializer.attribute(null, "name", mShortActivity);
7735 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7736 serializer.attribute(null, "set", Integer.toString(NS));
7737 for (int s=0; s<NS; s++) {
7738 serializer.startTag(null, "set");
7739 serializer.attribute(null, "name", mSetComponents[s]);
7740 serializer.endTag(null, "set");
7741 }
7742 serializer.startTag(null, "filter");
7743 super.writeToXml(serializer);
7744 serializer.endTag(null, "filter");
7745 }
7746
7747 boolean sameSet(List<ResolveInfo> query, int priority) {
7748 if (mSetPackages == null) return false;
7749 final int NQ = query.size();
7750 final int NS = mSetPackages.length;
7751 int numMatch = 0;
7752 for (int i=0; i<NQ; i++) {
7753 ResolveInfo ri = query.get(i);
7754 if (ri.priority != priority) continue;
7755 ActivityInfo ai = ri.activityInfo;
7756 boolean good = false;
7757 for (int j=0; j<NS; j++) {
7758 if (mSetPackages[j].equals(ai.packageName)
7759 && mSetClasses[j].equals(ai.name)) {
7760 numMatch++;
7761 good = true;
7762 break;
7763 }
7764 }
7765 if (!good) return false;
7766 }
7767 return numMatch == NS;
7768 }
7769 }
7770
7771 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007772 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007774 HashSet<String> grantedPermissions = new HashSet<String>();
7775 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007777 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007778 setFlags(pkgFlags);
7779 }
7780
7781 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007782 this.pkgFlags = pkgFlags & (
7783 ApplicationInfo.FLAG_SYSTEM |
7784 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007785 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007786 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007787 }
7788 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007790 /**
7791 * Settings base class for pending and resolved classes.
7792 */
7793 static class PackageSettingBase extends GrantedPermissions {
7794 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007795 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007796 File codePath;
7797 String codePathString;
7798 File resourcePath;
7799 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007800 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007801 String obbPathString;
Kenny Root7d794fb2010-09-13 16:29:49 -07007802 long timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007803 long firstInstallTime;
7804 long lastUpdateTime;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007805 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007807 boolean uidError;
7808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007809 PackageSignatures signatures = new PackageSignatures();
7810
7811 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007812 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007814 /* Explicitly disabled components */
7815 HashSet<String> disabledComponents = new HashSet<String>(0);
7816 /* Explicitly enabled components */
7817 HashSet<String> enabledComponents = new HashSet<String>(0);
7818 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7819 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007820
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007821 PackageSettingBase origPackage;
7822
Jacek Surazski65e13172009-04-28 15:26:38 +02007823 /* package name of the app that installed this package */
7824 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007826 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007827 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 super(pkgFlags);
7829 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007830 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007831 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007832 }
7833
Kenny Root806cc132010-09-12 08:34:19 -07007834 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7835 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 this.codePath = codePath;
7837 this.codePathString = codePath.toString();
7838 this.resourcePath = resourcePath;
7839 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007840 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007841 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 }
Kenny Root85387d72010-08-26 10:13:11 -07007843
Jacek Surazski65e13172009-04-28 15:26:38 +02007844 public void setInstallerPackageName(String packageName) {
7845 installerPackageName = packageName;
7846 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007847
Jacek Surazski65e13172009-04-28 15:26:38 +02007848 String getInstallerPackageName() {
7849 return installerPackageName;
7850 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007852 public void setInstallStatus(int newStatus) {
7853 installStatus = newStatus;
7854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007856 public int getInstallStatus() {
7857 return installStatus;
7858 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007859
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007860 public void setTimeStamp(long newStamp) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007861 timeStamp = newStamp;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007862 }
7863
7864 public void copyFrom(PackageSettingBase base) {
7865 grantedPermissions = base.grantedPermissions;
7866 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007868 timeStamp = base.timeStamp;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07007869 firstInstallTime = base.firstInstallTime;
7870 lastUpdateTime = base.lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007871 signatures = base.signatures;
7872 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007873 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 disabledComponents = base.disabledComponents;
7875 enabledComponents = base.enabledComponents;
7876 enabled = base.enabled;
7877 installStatus = base.installStatus;
7878 }
7879
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007880 boolean enableComponentLP(String componentClassName) {
7881 boolean changed = disabledComponents.remove(componentClassName);
7882 changed |= enabledComponents.add(componentClassName);
7883 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007884 }
7885
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007886 boolean disableComponentLP(String componentClassName) {
7887 boolean changed = enabledComponents.remove(componentClassName);
7888 changed |= disabledComponents.add(componentClassName);
7889 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007890 }
7891
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007892 boolean restoreComponentLP(String componentClassName) {
7893 boolean changed = enabledComponents.remove(componentClassName);
7894 changed |= disabledComponents.remove(componentClassName);
7895 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007896 }
7897
7898 int currentEnabledStateLP(String componentName) {
7899 if (enabledComponents.contains(componentName)) {
7900 return COMPONENT_ENABLED_STATE_ENABLED;
7901 } else if (disabledComponents.contains(componentName)) {
7902 return COMPONENT_ENABLED_STATE_DISABLED;
7903 } else {
7904 return COMPONENT_ENABLED_STATE_DEFAULT;
7905 }
7906 }
7907 }
7908
7909 /**
7910 * Settings data for a particular package we know about.
7911 */
7912 static final class PackageSetting extends PackageSettingBase {
7913 int userId;
7914 PackageParser.Package pkg;
7915 SharedUserSetting sharedUser;
7916
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007917 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007918 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7919 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7920 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007922
Dianne Hackborn690d20b2010-12-22 14:03:29 -08007923 PackageSetting(PackageSetting orig) {
7924 super(orig.name, orig.realName, orig.codePath, orig.resourcePath,
7925 orig.nativeLibraryPathString, orig.versionCode, orig.pkgFlags);
7926 copyFrom(orig);
7927 }
7928
Kenny Root97ef63b2011-01-11 11:15:35 -08007929 public void copyFrom(PackageSetting base) {
7930 super.copyFrom((PackageSettingBase) base);
7931
7932 userId = base.userId;
7933 sharedUser = base.sharedUser;
7934 pkg = base.pkg;
7935 }
7936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007937 @Override
7938 public String toString() {
7939 return "PackageSetting{"
7940 + Integer.toHexString(System.identityHashCode(this))
7941 + " " + name + "/" + userId + "}";
7942 }
7943 }
7944
7945 /**
7946 * Settings data for a particular shared user ID we know about.
7947 */
7948 static final class SharedUserSetting extends GrantedPermissions {
7949 final String name;
7950 int userId;
7951 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7952 final PackageSignatures signatures = new PackageSignatures();
7953
7954 SharedUserSetting(String _name, int _pkgFlags) {
7955 super(_pkgFlags);
7956 name = _name;
7957 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007959 @Override
7960 public String toString() {
7961 return "SharedUserSetting{"
7962 + Integer.toHexString(System.identityHashCode(this))
7963 + " " + name + "/" + userId + "}";
7964 }
7965 }
7966
7967 /**
7968 * Holds information about dynamic settings.
7969 */
7970 private static final class Settings {
7971 private final File mSettingsFilename;
7972 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007973 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 private final HashMap<String, PackageSetting> mPackages =
7975 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007976 // List of replaced system applications
7977 final HashMap<String, PackageSetting> mDisabledSysPackages =
7978 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007979
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007980 // These are the last platform API version we were using for
7981 // the apps installed on internal and external storage. It is
7982 // used to grant newer permissions one time during a system upgrade.
7983 int mInternalSdkPlatform;
7984 int mExternalSdkPlatform;
7985
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007986 // The user's preferred activities associated with particular intent
7987 // filters.
7988 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7989 new IntentResolver<PreferredActivity, PreferredActivity>() {
7990 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007991 protected String packageForFilter(PreferredActivity filter) {
7992 return filter.mActivity.getPackageName();
7993 }
7994 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007995 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007996 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007997 out.print(prefix); out.print(
7998 Integer.toHexString(System.identityHashCode(filter)));
7999 out.print(' ');
8000 out.print(filter.mActivity.flattenToShortString());
8001 out.print(" match=0x");
8002 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008003 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008004 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07008006 out.print(prefix); out.print(" ");
8007 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008008 }
8009 }
8010 }
8011 };
8012 private final HashMap<String, SharedUserSetting> mSharedUsers =
8013 new HashMap<String, SharedUserSetting>();
8014 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
8015 private final SparseArray<Object> mOtherUserIds =
8016 new SparseArray<Object>();
8017
8018 // For reading/writing settings file.
8019 private final ArrayList<Signature> mPastSignatures =
8020 new ArrayList<Signature>();
8021
8022 // Mapping from permission names to info about them.
8023 final HashMap<String, BasePermission> mPermissions =
8024 new HashMap<String, BasePermission>();
8025
8026 // Mapping from permission tree names to info about them.
8027 final HashMap<String, BasePermission> mPermissionTrees =
8028 new HashMap<String, BasePermission>();
8029
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008030 // Packages that have been uninstalled and still need their external
8031 // storage data deleted.
8032 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
8033
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008034 // Packages that have been renamed since they were first installed.
8035 // Keys are the new names of the packages, values are the original
8036 // names. The packages appear everwhere else under their original
8037 // names.
8038 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
8039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008040 private final StringBuilder mReadMessages = new StringBuilder();
8041
8042 private static final class PendingPackage extends PackageSettingBase {
8043 final int sharedId;
8044
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008045 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008046 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
8047 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
8048 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008049 this.sharedId = sharedId;
8050 }
8051 }
8052 private final ArrayList<PendingPackage> mPendingPackages
8053 = new ArrayList<PendingPackage>();
8054
8055 Settings() {
8056 File dataDir = Environment.getDataDirectory();
8057 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08008058 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
8059 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008060 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008061 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062 FileUtils.setPermissions(systemDir.toString(),
8063 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8064 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8065 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08008066 FileUtils.setPermissions(systemSecureDir.toString(),
8067 FileUtils.S_IRWXU|FileUtils.S_IRWXG
8068 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
8069 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008070 mSettingsFilename = new File(systemDir, "packages.xml");
8071 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008072 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008073 }
8074
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008075 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008076 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008077 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008079 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07008080 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008081 return p;
8082 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008083
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008084 PackageSetting peekPackageLP(String name) {
8085 return mPackages.get(name);
8086 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008087 PackageSetting p = mPackages.get(name);
8088 if (p != null && p.codePath.getPath().equals(codePath)) {
8089 return p;
8090 }
8091 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008092 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008093 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 void setInstallStatus(String pkgName, int status) {
8096 PackageSetting p = mPackages.get(pkgName);
8097 if(p != null) {
8098 if(p.getInstallStatus() != status) {
8099 p.setInstallStatus(status);
8100 }
8101 }
8102 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008103
Jacek Surazski65e13172009-04-28 15:26:38 +02008104 void setInstallerPackageName(String pkgName,
8105 String installerPkgName) {
8106 PackageSetting p = mPackages.get(pkgName);
8107 if(p != null) {
8108 p.setInstallerPackageName(installerPkgName);
8109 }
8110 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008111
Jacek Surazski65e13172009-04-28 15:26:38 +02008112 String getInstallerPackageName(String pkgName) {
8113 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008114 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008115 }
8116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008117 int getInstallStatus(String pkgName) {
8118 PackageSetting p = mPackages.get(pkgName);
8119 if(p != null) {
8120 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008121 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008122 return -1;
8123 }
8124
8125 SharedUserSetting getSharedUserLP(String name,
8126 int pkgFlags, boolean create) {
8127 SharedUserSetting s = mSharedUsers.get(name);
8128 if (s == null) {
8129 if (!create) {
8130 return null;
8131 }
8132 s = new SharedUserSetting(name, pkgFlags);
8133 if (MULTIPLE_APPLICATION_UIDS) {
8134 s.userId = newUserIdLP(s);
8135 } else {
8136 s.userId = FIRST_APPLICATION_UID;
8137 }
8138 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8139 // < 0 means we couldn't assign a userid; fall out and return
8140 // s, which is currently null
8141 if (s.userId >= 0) {
8142 mSharedUsers.put(name, s);
8143 }
8144 }
8145
8146 return s;
8147 }
8148
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008149 boolean disableSystemPackageLP(String name) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 PackageSetting p = mPackages.get(name);
8151 if(p == null) {
8152 Log.w(TAG, "Package:"+name+" is not an installed package");
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008153 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008154 }
8155 PackageSetting dp = mDisabledSysPackages.get(name);
8156 // always make sure the system package code and resource paths dont change
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008157 if (dp == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008158 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8159 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8160 }
8161 mDisabledSysPackages.put(name, p);
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008162
8163 // a little trick... when we install the new package, we don't
8164 // want to modify the existing PackageSetting for the built-in
8165 // version. so at this point we need a new PackageSetting that
8166 // is okay to much with.
8167 PackageSetting newp = new PackageSetting(p);
8168 replacePackageLP(name, newp);
8169 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008170 }
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008171 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008172 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008173
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008174 PackageSetting enableSystemPackageLP(String name) {
8175 PackageSetting p = mDisabledSysPackages.get(name);
8176 if(p == null) {
8177 Log.w(TAG, "Package:"+name+" is not disabled");
8178 return null;
8179 }
8180 // Reset flag in ApplicationInfo object
8181 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8182 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8183 }
Kenny Root806cc132010-09-12 08:34:19 -07008184 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
8185 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 mDisabledSysPackages.remove(name);
8187 return ret;
8188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008189
Kenny Root806cc132010-09-12 08:34:19 -07008190 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
8191 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008192 PackageSetting p = mPackages.get(name);
8193 if (p != null) {
8194 if (p.userId == uid) {
8195 return p;
8196 }
8197 reportSettingsProblem(Log.ERROR,
8198 "Adding duplicate package, keeping first: " + name);
8199 return null;
8200 }
Kenny Root806cc132010-09-12 08:34:19 -07008201 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
8202 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008203 p.userId = uid;
8204 if (addUserIdLP(uid, p, name)) {
8205 mPackages.put(name, p);
8206 return p;
8207 }
8208 return null;
8209 }
8210
8211 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8212 SharedUserSetting s = mSharedUsers.get(name);
8213 if (s != null) {
8214 if (s.userId == uid) {
8215 return s;
8216 }
8217 reportSettingsProblem(Log.ERROR,
8218 "Adding duplicate shared user, keeping first: " + name);
8219 return null;
8220 }
8221 s = new SharedUserSetting(name, pkgFlags);
8222 s.userId = uid;
8223 if (addUserIdLP(uid, s, name)) {
8224 mSharedUsers.put(name, s);
8225 return s;
8226 }
8227 return null;
8228 }
8229
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008230 // Transfer ownership of permissions from one package to another.
8231 private void transferPermissions(String origPkg, String newPkg) {
8232 // Transfer ownership of permissions to the new package.
8233 for (int i=0; i<2; i++) {
8234 HashMap<String, BasePermission> permissions =
8235 i == 0 ? mPermissionTrees : mPermissions;
8236 for (BasePermission bp : permissions.values()) {
8237 if (origPkg.equals(bp.sourcePackage)) {
8238 if (DEBUG_UPGRADE) Log.v(TAG,
8239 "Moving permission " + bp.name
8240 + " from pkg " + bp.sourcePackage
8241 + " to " + newPkg);
8242 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008243 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008244 bp.perm = null;
8245 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008246 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008247 }
8248 bp.uid = 0;
8249 bp.gids = null;
8250 }
8251 }
8252 }
8253 }
8254
8255 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008256 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07008257 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008258 PackageSetting p = mPackages.get(name);
8259 if (p != null) {
8260 if (!p.codePath.equals(codePath)) {
8261 // Check to see if its a disabled system app
Kenny Rootbd135c12010-10-05 12:26:27 -07008262 if ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008263 // This is an updated system app with versions in both system
8264 // and data partition. Just let the most recent version
8265 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008266 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008267 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008268 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008269 // Just a change in the code path is not an issue, but
8270 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008271 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008272 + " to " + codePath + "; Retaining data and using new");
Kenny Rootbd135c12010-10-05 12:26:27 -07008273 /*
8274 * Since we've changed paths, we need to prefer the new
8275 * native library path over the one stored in the
8276 * package settings since we might have moved from
8277 * internal to external storage or vice versa.
8278 */
8279 p.nativeLibraryPathString = nativeLibraryPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008280 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008281 }
8282 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008283 reportSettingsProblem(Log.WARN,
8284 "Package " + name + " shared user changed from "
8285 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8286 + " to "
8287 + (sharedUser != null ? sharedUser.name : "<nothing>")
8288 + "; replacing with new");
8289 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008290 } else {
8291 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8292 // If what we are scanning is a system package, then
8293 // make it so, regardless of whether it was previously
8294 // installed only in the data partition.
8295 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008297 }
8298 }
8299 if (p == null) {
8300 // Create a new PackageSettings entry. this can end up here because
8301 // of code path mismatch or user id mismatch of an updated system partition
8302 if (!create) {
8303 return null;
8304 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008305 if (origPackage != null) {
8306 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008307 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8308 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008309 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8310 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008311 // Note that we will retain the new package's signature so
8312 // that we can keep its data.
8313 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008314 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008315 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008316 p.sharedUser = origPackage.sharedUser;
8317 p.userId = origPackage.userId;
8318 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008319 mRenamedPackages.put(name, origPackage.name);
8320 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008321 // Update new package state.
8322 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008323 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008324 p = new PackageSetting(name, realName, codePath, resourcePath,
8325 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008326 p.setTimeStamp(codePath.lastModified());
8327 p.sharedUser = sharedUser;
8328 if (sharedUser != null) {
8329 p.userId = sharedUser.userId;
8330 } else if (MULTIPLE_APPLICATION_UIDS) {
8331 // Clone the setting here for disabled system packages
8332 PackageSetting dis = mDisabledSysPackages.get(name);
8333 if (dis != null) {
8334 // For disabled packages a new setting is created
8335 // from the existing user id. This still has to be
8336 // added to list of user id's
8337 // Copy signatures from previous setting
8338 if (dis.signatures.mSignatures != null) {
8339 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8340 }
8341 p.userId = dis.userId;
8342 // Clone permissions
8343 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008344 // Clone component info
8345 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8346 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8347 // Add new setting to list of user ids
8348 addUserIdLP(p.userId, p, name);
8349 } else {
8350 // Assign new user id
8351 p.userId = newUserIdLP(p);
8352 }
8353 } else {
8354 p.userId = FIRST_APPLICATION_UID;
8355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008356 }
8357 if (p.userId < 0) {
8358 reportSettingsProblem(Log.WARN,
8359 "Package " + name + " could not be assigned a valid uid");
8360 return null;
8361 }
8362 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008363 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008364 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008365 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008366 }
8367 }
8368 return p;
8369 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008370
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008371 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008372 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008373 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008374 final String codePath = pkg.applicationInfo.sourceDir;
8375 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008376 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008377 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008378 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008379 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008380 p.codePath = new File(codePath);
8381 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008382 }
8383 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008384 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008385 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008386 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008387 p.resourcePath = new File(resourcePath);
8388 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008389 }
Kenny Root85387d72010-08-26 10:13:11 -07008390 // Update the native library path if needed
8391 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8392 if (nativeLibraryPath != null
8393 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8394 p.nativeLibraryPathString = nativeLibraryPath;
8395 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008396 // Update version code if needed
8397 if (pkg.mVersionCode != p.versionCode) {
8398 p.versionCode = pkg.mVersionCode;
8399 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008400 // Update signatures if needed.
8401 if (p.signatures.mSignatures == null) {
8402 p.signatures.assignSignatures(pkg.mSignatures);
8403 }
8404 // If this app defines a shared user id initialize
8405 // the shared user signatures as well.
8406 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8407 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8408 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008409 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8410 }
8411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008412 // Utility method that adds a PackageSetting to mPackages and
8413 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008414 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008415 SharedUserSetting sharedUser) {
8416 mPackages.put(name, p);
8417 if (sharedUser != null) {
8418 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8419 reportSettingsProblem(Log.ERROR,
8420 "Package " + p.name + " was user "
8421 + p.sharedUser + " but is now " + sharedUser
8422 + "; I am not changing its files so it will probably fail!");
8423 p.sharedUser.packages.remove(p);
8424 } else if (p.userId != sharedUser.userId) {
8425 reportSettingsProblem(Log.ERROR,
8426 "Package " + p.name + " was user id " + p.userId
8427 + " but is now user " + sharedUser
8428 + " with id " + sharedUser.userId
8429 + "; I am not changing its files so it will probably fail!");
8430 }
8431
8432 sharedUser.packages.add(p);
8433 p.sharedUser = sharedUser;
8434 p.userId = sharedUser.userId;
8435 }
8436 }
8437
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008438 /*
8439 * Update the shared user setting when a package using
8440 * specifying the shared user id is removed. The gids
8441 * associated with each permission of the deleted package
8442 * are removed from the shared user's gid list only if its
8443 * not in use by other permissions of packages in the
8444 * shared user setting.
8445 */
8446 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008447 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008448 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008449 return;
8450 }
8451 // No sharedUserId
8452 if (deletedPs.sharedUser == null) {
8453 return;
8454 }
8455 SharedUserSetting sus = deletedPs.sharedUser;
8456 // Update permissions
8457 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8458 boolean used = false;
8459 if (!sus.grantedPermissions.contains (eachPerm)) {
8460 continue;
8461 }
8462 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008463 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008464 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008465 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008466 used = true;
8467 break;
8468 }
8469 }
8470 if (!used) {
8471 // can safely delete this permission from list
8472 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008473 }
8474 }
8475 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008476 int newGids[] = globalGids;
8477 for (String eachPerm : sus.grantedPermissions) {
8478 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008479 if (bp != null) {
8480 newGids = appendInts(newGids, bp.gids);
8481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008482 }
8483 sus.gids = newGids;
8484 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008486 private int removePackageLP(String name) {
8487 PackageSetting p = mPackages.get(name);
8488 if (p != null) {
8489 mPackages.remove(name);
8490 if (p.sharedUser != null) {
8491 p.sharedUser.packages.remove(p);
8492 if (p.sharedUser.packages.size() == 0) {
8493 mSharedUsers.remove(p.sharedUser.name);
8494 removeUserIdLP(p.sharedUser.userId);
8495 return p.sharedUser.userId;
8496 }
8497 } else {
8498 removeUserIdLP(p.userId);
8499 return p.userId;
8500 }
8501 }
8502 return -1;
8503 }
8504
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008505 private void replacePackageLP(String name, PackageSetting newp) {
8506 PackageSetting p = mPackages.get(name);
8507 if (p != null) {
8508 if (p.sharedUser != null) {
8509 p.sharedUser.packages.remove(p);
8510 p.sharedUser.packages.add(newp);
8511 } else {
8512 replaceUserIdLP(p.userId, newp);
8513 }
8514 }
8515 mPackages.put(name, newp);
8516 }
8517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008518 private boolean addUserIdLP(int uid, Object obj, Object name) {
8519 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8520 return false;
8521 }
8522
8523 if (uid >= FIRST_APPLICATION_UID) {
8524 int N = mUserIds.size();
8525 final int index = uid - FIRST_APPLICATION_UID;
8526 while (index >= N) {
8527 mUserIds.add(null);
8528 N++;
8529 }
8530 if (mUserIds.get(index) != null) {
8531 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008532 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 + " name=" + name);
8534 return false;
8535 }
8536 mUserIds.set(index, obj);
8537 } else {
8538 if (mOtherUserIds.get(uid) != null) {
8539 reportSettingsProblem(Log.ERROR,
8540 "Adding duplicate shared id: " + uid
8541 + " name=" + name);
8542 return false;
8543 }
8544 mOtherUserIds.put(uid, obj);
8545 }
8546 return true;
8547 }
8548
8549 public Object getUserIdLP(int uid) {
8550 if (uid >= FIRST_APPLICATION_UID) {
8551 int N = mUserIds.size();
8552 final int index = uid - FIRST_APPLICATION_UID;
8553 return index < N ? mUserIds.get(index) : null;
8554 } else {
8555 return mOtherUserIds.get(uid);
8556 }
8557 }
8558
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008559 private Set<String> findPackagesWithFlag(int flag) {
8560 Set<String> ret = new HashSet<String>();
8561 for (PackageSetting ps : mPackages.values()) {
8562 // Has to match atleast all the flag bits set on flag
8563 if ((ps.pkgFlags & flag) == flag) {
8564 ret.add(ps.name);
8565 }
8566 }
8567 return ret;
8568 }
8569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008570 private void removeUserIdLP(int uid) {
8571 if (uid >= FIRST_APPLICATION_UID) {
8572 int N = mUserIds.size();
8573 final int index = uid - FIRST_APPLICATION_UID;
8574 if (index < N) mUserIds.set(index, null);
8575 } else {
8576 mOtherUserIds.remove(uid);
8577 }
8578 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008579
Dianne Hackborn690d20b2010-12-22 14:03:29 -08008580 private void replaceUserIdLP(int uid, Object obj) {
8581 if (uid >= FIRST_APPLICATION_UID) {
8582 int N = mUserIds.size();
8583 final int index = uid - FIRST_APPLICATION_UID;
8584 if (index < N) mUserIds.set(index, obj);
8585 } else {
8586 mOtherUserIds.put(uid, obj);
8587 }
8588 }
8589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008590 void writeLP() {
8591 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8592
8593 // Keep the old settings around until we know the new ones have
8594 // been successfully written.
8595 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008596 // Presence of backup settings file indicates that we failed
8597 // to persist settings earlier. So preserve the older
8598 // backup for future reference since the current settings
8599 // might have been corrupted.
8600 if (!mBackupSettingsFilename.exists()) {
8601 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008602 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008603 return;
8604 }
8605 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008606 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008607 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008609 }
8610
8611 mPastSignatures.clear();
8612
8613 try {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008614 FileOutputStream fstr = new FileOutputStream(mSettingsFilename);
8615 BufferedOutputStream str = new BufferedOutputStream(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616
8617 //XmlSerializer serializer = XmlUtils.serializerInstance();
8618 XmlSerializer serializer = new FastXmlSerializer();
8619 serializer.setOutput(str, "utf-8");
8620 serializer.startDocument(null, true);
8621 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8622
8623 serializer.startTag(null, "packages");
8624
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008625 serializer.startTag(null, "last-platform-version");
8626 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8627 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8628 serializer.endTag(null, "last-platform-version");
8629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008630 serializer.startTag(null, "permission-trees");
8631 for (BasePermission bp : mPermissionTrees.values()) {
8632 writePermission(serializer, bp);
8633 }
8634 serializer.endTag(null, "permission-trees");
8635
8636 serializer.startTag(null, "permissions");
8637 for (BasePermission bp : mPermissions.values()) {
8638 writePermission(serializer, bp);
8639 }
8640 serializer.endTag(null, "permissions");
8641
8642 for (PackageSetting pkg : mPackages.values()) {
8643 writePackage(serializer, pkg);
8644 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8647 writeDisabledSysPackage(serializer, pkg);
8648 }
8649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 serializer.startTag(null, "preferred-activities");
8651 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8652 serializer.startTag(null, "item");
8653 pa.writeToXml(serializer);
8654 serializer.endTag(null, "item");
8655 }
8656 serializer.endTag(null, "preferred-activities");
8657
8658 for (SharedUserSetting usr : mSharedUsers.values()) {
8659 serializer.startTag(null, "shared-user");
8660 serializer.attribute(null, "name", usr.name);
8661 serializer.attribute(null, "userId",
8662 Integer.toString(usr.userId));
8663 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8664 serializer.startTag(null, "perms");
8665 for (String name : usr.grantedPermissions) {
8666 serializer.startTag(null, "item");
8667 serializer.attribute(null, "name", name);
8668 serializer.endTag(null, "item");
8669 }
8670 serializer.endTag(null, "perms");
8671 serializer.endTag(null, "shared-user");
8672 }
8673
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008674 if (mPackagesToBeCleaned.size() > 0) {
8675 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8676 serializer.startTag(null, "cleaning-package");
8677 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8678 serializer.endTag(null, "cleaning-package");
8679 }
8680 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008681
8682 if (mRenamedPackages.size() > 0) {
8683 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8684 serializer.startTag(null, "renamed-package");
8685 serializer.attribute(null, "new", e.getKey());
8686 serializer.attribute(null, "old", e.getValue());
8687 serializer.endTag(null, "renamed-package");
8688 }
8689 }
8690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008691 serializer.endTag(null, "packages");
8692
8693 serializer.endDocument();
8694
8695 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008696 FileUtils.sync(fstr);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008697 str.close();
8698
8699 // New settings successfully written, old ones are no longer
8700 // needed.
8701 mBackupSettingsFilename.delete();
8702 FileUtils.setPermissions(mSettingsFilename.toString(),
8703 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8704 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8705 |FileUtils.S_IROTH,
8706 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008707
8708 // Write package list file now, use a JournaledFile.
8709 //
8710 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8711 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8712
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008713 fstr = new FileOutputStream(journal.chooseForWrite());
8714 str = new BufferedOutputStream(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008715 try {
8716 StringBuilder sb = new StringBuilder();
8717 for (PackageSetting pkg : mPackages.values()) {
8718 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008719 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008720 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8721
8722 // Avoid any application that has a space in its path
8723 // or that is handled by the system.
8724 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8725 continue;
8726
8727 // we store on each line the following information for now:
8728 //
8729 // pkgName - package name
8730 // userId - application-specific user id
8731 // debugFlag - 0 or 1 if the package is debuggable.
8732 // dataPath - path to package's data path
8733 //
8734 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8735 //
8736 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8737 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8738 // system/core/run-as/run-as.c
8739 //
8740 sb.setLength(0);
8741 sb.append(ai.packageName);
8742 sb.append(" ");
8743 sb.append((int)ai.uid);
8744 sb.append(isDebug ? " 1 " : " 0 ");
8745 sb.append(dataPath);
8746 sb.append("\n");
8747 str.write(sb.toString().getBytes());
8748 }
8749 str.flush();
Dianne Hackborn8bdf5932010-10-15 12:54:40 -07008750 FileUtils.sync(fstr);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008751 str.close();
8752 journal.commit();
8753 }
8754 catch (Exception e) {
8755 journal.rollback();
8756 }
8757
8758 FileUtils.setPermissions(mPackageListFilename.toString(),
8759 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8760 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8761 |FileUtils.S_IROTH,
8762 -1, -1);
8763
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008764 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008765
8766 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008767 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 -08008768 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008769 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 -08008770 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008771 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008772 if (mSettingsFilename.exists()) {
8773 if (!mSettingsFilename.delete()) {
8774 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8775 }
8776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008777 //Debug.stopMethodTracing();
8778 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008779
8780 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008781 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008782 serializer.startTag(null, "updated-package");
8783 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008784 if (pkg.realName != null) {
8785 serializer.attribute(null, "realName", pkg.realName);
8786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 serializer.attribute(null, "codePath", pkg.codePathString);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008788 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8789 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8790 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008791 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008792 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8793 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8794 }
Kenny Root85387d72010-08-26 10:13:11 -07008795 if (pkg.nativeLibraryPathString != null) {
8796 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008798 if (pkg.sharedUser == null) {
8799 serializer.attribute(null, "userId",
8800 Integer.toString(pkg.userId));
8801 } else {
8802 serializer.attribute(null, "sharedUserId",
8803 Integer.toString(pkg.userId));
8804 }
8805 serializer.startTag(null, "perms");
8806 if (pkg.sharedUser == null) {
8807 // If this is a shared user, the permissions will
8808 // be written there. We still need to write an
8809 // empty permissions list so permissionsFixed will
8810 // be set.
8811 for (final String name : pkg.grantedPermissions) {
8812 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008813 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008814 // We only need to write signature or system permissions but this wont
8815 // match the semantics of grantedPermissions. So write all permissions.
8816 serializer.startTag(null, "item");
8817 serializer.attribute(null, "name", name);
8818 serializer.endTag(null, "item");
8819 }
8820 }
8821 }
8822 serializer.endTag(null, "perms");
8823 serializer.endTag(null, "updated-package");
8824 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008825
8826 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008827 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008828 serializer.startTag(null, "package");
8829 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008830 if (pkg.realName != null) {
8831 serializer.attribute(null, "realName", pkg.realName);
8832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008833 serializer.attribute(null, "codePath", pkg.codePathString);
8834 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8835 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8836 }
Kenny Root85387d72010-08-26 10:13:11 -07008837 if (pkg.nativeLibraryPathString != null) {
8838 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8839 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008840 serializer.attribute(null, "flags",
8841 Integer.toString(pkg.pkgFlags));
Dianne Hackborn78d6883692010-10-07 01:12:46 -07008842 serializer.attribute(null, "ft", Long.toHexString(pkg.timeStamp));
8843 serializer.attribute(null, "it", Long.toHexString(pkg.firstInstallTime));
8844 serializer.attribute(null, "ut", Long.toHexString(pkg.lastUpdateTime));
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008845 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008846 if (pkg.sharedUser == null) {
8847 serializer.attribute(null, "userId",
8848 Integer.toString(pkg.userId));
8849 } else {
8850 serializer.attribute(null, "sharedUserId",
8851 Integer.toString(pkg.userId));
8852 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008853 if (pkg.uidError) {
8854 serializer.attribute(null, "uidError", "true");
8855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008856 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8857 serializer.attribute(null, "enabled",
8858 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8859 ? "true" : "false");
8860 }
8861 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8862 serializer.attribute(null, "installStatus", "false");
8863 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008864 if (pkg.installerPackageName != null) {
8865 serializer.attribute(null, "installer", pkg.installerPackageName);
8866 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008867 if (pkg.obbPathString != null) {
8868 serializer.attribute(null, "obbPath", pkg.obbPathString);
8869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008870 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8871 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8872 serializer.startTag(null, "perms");
8873 if (pkg.sharedUser == null) {
8874 // If this is a shared user, the permissions will
8875 // be written there. We still need to write an
8876 // empty permissions list so permissionsFixed will
8877 // be set.
8878 for (final String name : pkg.grantedPermissions) {
8879 serializer.startTag(null, "item");
8880 serializer.attribute(null, "name", name);
8881 serializer.endTag(null, "item");
8882 }
8883 }
8884 serializer.endTag(null, "perms");
8885 }
8886 if (pkg.disabledComponents.size() > 0) {
8887 serializer.startTag(null, "disabled-components");
8888 for (final String name : pkg.disabledComponents) {
8889 serializer.startTag(null, "item");
8890 serializer.attribute(null, "name", name);
8891 serializer.endTag(null, "item");
8892 }
8893 serializer.endTag(null, "disabled-components");
8894 }
8895 if (pkg.enabledComponents.size() > 0) {
8896 serializer.startTag(null, "enabled-components");
8897 for (final String name : pkg.enabledComponents) {
8898 serializer.startTag(null, "item");
8899 serializer.attribute(null, "name", name);
8900 serializer.endTag(null, "item");
8901 }
8902 serializer.endTag(null, "enabled-components");
8903 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008905 serializer.endTag(null, "package");
8906 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 void writePermission(XmlSerializer serializer, BasePermission bp)
8909 throws XmlPullParserException, java.io.IOException {
8910 if (bp.type != BasePermission.TYPE_BUILTIN
8911 && bp.sourcePackage != null) {
8912 serializer.startTag(null, "item");
8913 serializer.attribute(null, "name", bp.name);
8914 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008915 if (bp.protectionLevel !=
8916 PermissionInfo.PROTECTION_NORMAL) {
8917 serializer.attribute(null, "protection",
8918 Integer.toString(bp.protectionLevel));
8919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920 if (DEBUG_SETTINGS) Log.v(TAG,
8921 "Writing perm: name=" + bp.name + " type=" + bp.type);
8922 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8923 PermissionInfo pi = bp.perm != null ? bp.perm.info
8924 : bp.pendingInfo;
8925 if (pi != null) {
8926 serializer.attribute(null, "type", "dynamic");
8927 if (pi.icon != 0) {
8928 serializer.attribute(null, "icon",
8929 Integer.toString(pi.icon));
8930 }
8931 if (pi.nonLocalizedLabel != null) {
8932 serializer.attribute(null, "label",
8933 pi.nonLocalizedLabel.toString());
8934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 }
8936 }
8937 serializer.endTag(null, "item");
8938 }
8939 }
8940
8941 String getReadMessagesLP() {
8942 return mReadMessages.toString();
8943 }
8944
Oscar Montemayora8529f62009-11-18 10:14:20 -08008945 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8947 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008948 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 while(its.hasNext()) {
8950 String key = its.next();
8951 PackageSetting ps = mPackages.get(key);
8952 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008953 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008954 }
8955 }
8956 return ret;
8957 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008959 boolean readLP() {
8960 FileInputStream str = null;
8961 if (mBackupSettingsFilename.exists()) {
8962 try {
8963 str = new FileInputStream(mBackupSettingsFilename);
8964 mReadMessages.append("Reading from backup settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008965 reportSettingsProblem(Log.INFO, "Need to read from backup settings file");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008966 if (mSettingsFilename.exists()) {
8967 // If both the backup and settings file exist, we
8968 // ignore the settings since it might have been
8969 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008970 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008971 mSettingsFilename.delete();
8972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008973 } catch (java.io.IOException e) {
8974 // We'll try for the normal settings file.
8975 }
8976 }
8977
8978 mPastSignatures.clear();
8979
8980 try {
8981 if (str == null) {
8982 if (!mSettingsFilename.exists()) {
8983 mReadMessages.append("No settings file found\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07008984 reportSettingsProblem(Log.INFO, "No settings file; creating initial state");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 return false;
8986 }
8987 str = new FileInputStream(mSettingsFilename);
8988 }
8989 XmlPullParser parser = Xml.newPullParser();
8990 parser.setInput(str, null);
8991
8992 int type;
8993 while ((type=parser.next()) != XmlPullParser.START_TAG
8994 && type != XmlPullParser.END_DOCUMENT) {
8995 ;
8996 }
8997
8998 if (type != XmlPullParser.START_TAG) {
8999 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackbornefb58102010-10-14 16:47:34 -07009000 reportSettingsProblem(Log.WARN, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009001 return false;
9002 }
9003
9004 int outerDepth = parser.getDepth();
9005 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9006 && (type != XmlPullParser.END_TAG
9007 || parser.getDepth() > outerDepth)) {
9008 if (type == XmlPullParser.END_TAG
9009 || type == XmlPullParser.TEXT) {
9010 continue;
9011 }
9012
9013 String tagName = parser.getName();
9014 if (tagName.equals("package")) {
9015 readPackageLP(parser);
9016 } else if (tagName.equals("permissions")) {
9017 readPermissionsLP(mPermissions, parser);
9018 } else if (tagName.equals("permission-trees")) {
9019 readPermissionsLP(mPermissionTrees, parser);
9020 } else if (tagName.equals("shared-user")) {
9021 readSharedUserLP(parser);
9022 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08009023 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009024 } else if (tagName.equals("preferred-activities")) {
9025 readPreferredActivitiesLP(parser);
9026 } else if(tagName.equals("updated-package")) {
9027 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009028 } else if (tagName.equals("cleaning-package")) {
9029 String name = parser.getAttributeValue(null, "name");
9030 if (name != null) {
9031 mPackagesToBeCleaned.add(name);
9032 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009033 } else if (tagName.equals("renamed-package")) {
9034 String nname = parser.getAttributeValue(null, "new");
9035 String oname = parser.getAttributeValue(null, "old");
9036 if (nname != null && oname != null) {
9037 mRenamedPackages.put(nname, oname);
9038 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009039 } else if (tagName.equals("last-platform-version")) {
9040 mInternalSdkPlatform = mExternalSdkPlatform = 0;
9041 try {
9042 String internal = parser.getAttributeValue(null, "internal");
9043 if (internal != null) {
9044 mInternalSdkPlatform = Integer.parseInt(internal);
9045 }
9046 String external = parser.getAttributeValue(null, "external");
9047 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01009048 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009049 }
9050 } catch (NumberFormatException e) {
9051 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009052 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009053 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009054 + parser.getName());
9055 XmlUtils.skipCurrentTag(parser);
9056 }
9057 }
9058
9059 str.close();
9060
9061 } catch(XmlPullParserException e) {
9062 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07009063 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009064 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009065
9066 } catch(java.io.IOException e) {
9067 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackbornefb58102010-10-14 16:47:34 -07009068 reportSettingsProblem(Log.ERROR, "Error reading settings: " + e);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009069 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009070
9071 }
9072
9073 int N = mPendingPackages.size();
9074 for (int i=0; i<N; i++) {
9075 final PendingPackage pp = mPendingPackages.get(i);
9076 Object idObj = getUserIdLP(pp.sharedId);
9077 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009078 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07009079 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
9080 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009081 if (p == null) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07009082 reportSettingsProblem(Log.WARN, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009083 + pp.name);
9084 continue;
9085 }
9086 p.copyFrom(pp);
9087 } else if (idObj != null) {
9088 String msg = "Bad package setting: package " + pp.name
9089 + " has shared uid " + pp.sharedId
9090 + " that is not a shared uid\n";
9091 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009092 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009093 } else {
9094 String msg = "Bad package setting: package " + pp.name
9095 + " has shared uid " + pp.sharedId
9096 + " that is not defined\n";
9097 mReadMessages.append(msg);
Dianne Hackbornefb58102010-10-14 16:47:34 -07009098 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009099 }
9100 }
9101 mPendingPackages.clear();
9102
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009103 mReadMessages.append("Read completed successfully: "
9104 + mPackages.size() + " packages, "
9105 + mSharedUsers.size() + " shared uids\n");
9106
9107 return true;
9108 }
9109
9110 private int readInt(XmlPullParser parser, String ns, String name,
9111 int defValue) {
9112 String v = parser.getAttributeValue(ns, name);
9113 try {
9114 if (v == null) {
9115 return defValue;
9116 }
9117 return Integer.parseInt(v);
9118 } catch (NumberFormatException e) {
9119 reportSettingsProblem(Log.WARN,
9120 "Error in package manager settings: attribute " +
9121 name + " has bad integer value " + v + " at "
9122 + parser.getPositionDescription());
9123 }
9124 return defValue;
9125 }
9126
9127 private void readPermissionsLP(HashMap<String, BasePermission> out,
9128 XmlPullParser parser)
9129 throws IOException, XmlPullParserException {
9130 int outerDepth = parser.getDepth();
9131 int type;
9132 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9133 && (type != XmlPullParser.END_TAG
9134 || parser.getDepth() > outerDepth)) {
9135 if (type == XmlPullParser.END_TAG
9136 || type == XmlPullParser.TEXT) {
9137 continue;
9138 }
9139
9140 String tagName = parser.getName();
9141 if (tagName.equals("item")) {
9142 String name = parser.getAttributeValue(null, "name");
9143 String sourcePackage = parser.getAttributeValue(null, "package");
9144 String ptype = parser.getAttributeValue(null, "type");
9145 if (name != null && sourcePackage != null) {
9146 boolean dynamic = "dynamic".equals(ptype);
9147 BasePermission bp = new BasePermission(name, sourcePackage,
9148 dynamic
9149 ? BasePermission.TYPE_DYNAMIC
9150 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009151 bp.protectionLevel = readInt(parser, null, "protection",
9152 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009153 if (dynamic) {
9154 PermissionInfo pi = new PermissionInfo();
9155 pi.packageName = sourcePackage.intern();
9156 pi.name = name.intern();
9157 pi.icon = readInt(parser, null, "icon", 0);
9158 pi.nonLocalizedLabel = parser.getAttributeValue(
9159 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009160 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009161 bp.pendingInfo = pi;
9162 }
9163 out.put(bp.name, bp);
9164 } else {
9165 reportSettingsProblem(Log.WARN,
9166 "Error in package manager settings: permissions has"
9167 + " no name at " + parser.getPositionDescription());
9168 }
9169 } else {
9170 reportSettingsProblem(Log.WARN,
9171 "Unknown element reading permissions: "
9172 + parser.getName() + " at "
9173 + parser.getPositionDescription());
9174 }
9175 XmlUtils.skipCurrentTag(parser);
9176 }
9177 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009178
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009179 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009180 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009181 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009182 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009183 String codePathStr = parser.getAttributeValue(null, "codePath");
9184 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07009185 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009186 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009187 resourcePathStr = codePathStr;
9188 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009189 String version = parser.getAttributeValue(null, "version");
9190 int versionCode = 0;
9191 if (version != null) {
9192 try {
9193 versionCode = Integer.parseInt(version);
9194 } catch (NumberFormatException e) {
9195 }
9196 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009197
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009198 int pkgFlags = 0;
9199 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07009200 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
9201 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009202 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009203 if (timeStampStr != null) {
9204 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009205 long timeStamp = Long.parseLong(timeStampStr, 16);
Kenny Root7d794fb2010-09-13 16:29:49 -07009206 ps.setTimeStamp(timeStamp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009207 } catch (NumberFormatException e) {
9208 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009209 } else {
9210 timeStampStr = parser.getAttributeValue(null, "ts");
9211 if (timeStampStr != null) {
9212 try {
9213 long timeStamp = Long.parseLong(timeStampStr);
9214 ps.setTimeStamp(timeStamp);
9215 } catch (NumberFormatException e) {
9216 }
9217 }
9218 }
9219 timeStampStr = parser.getAttributeValue(null, "it");
9220 if (timeStampStr != null) {
9221 try {
9222 ps.firstInstallTime = Long.parseLong(timeStampStr, 16);
9223 } catch (NumberFormatException e) {
9224 }
9225 }
9226 timeStampStr = parser.getAttributeValue(null, "ut");
9227 if (timeStampStr != null) {
9228 try {
9229 ps.lastUpdateTime = Long.parseLong(timeStampStr, 16);
9230 } catch (NumberFormatException e) {
9231 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009232 }
9233 String idStr = parser.getAttributeValue(null, "userId");
9234 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9235 if(ps.userId <= 0) {
9236 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9237 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9238 }
9239 int outerDepth = parser.getDepth();
9240 int type;
9241 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9242 && (type != XmlPullParser.END_TAG
9243 || parser.getDepth() > outerDepth)) {
9244 if (type == XmlPullParser.END_TAG
9245 || type == XmlPullParser.TEXT) {
9246 continue;
9247 }
9248
9249 String tagName = parser.getName();
9250 if (tagName.equals("perms")) {
9251 readGrantedPermissionsLP(parser,
9252 ps.grantedPermissions);
9253 } else {
9254 reportSettingsProblem(Log.WARN,
9255 "Unknown element under <updated-package>: "
9256 + parser.getName());
9257 XmlUtils.skipCurrentTag(parser);
9258 }
9259 }
9260 mDisabledSysPackages.put(name, ps);
9261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009263 private void readPackageLP(XmlPullParser parser)
9264 throws XmlPullParserException, IOException {
9265 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009266 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009267 String idStr = null;
9268 String sharedIdStr = null;
9269 String codePathStr = null;
9270 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07009271 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009272 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009273 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009274 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009275 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009276 int pkgFlags = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009277 long timeStamp = 0;
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009278 long firstInstallTime = 0;
9279 long lastUpdateTime = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009280 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009281 String version = null;
9282 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009283 try {
9284 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009285 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009286 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009287 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009288 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9289 codePathStr = parser.getAttributeValue(null, "codePath");
9290 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07009291 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009292 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009293 version = parser.getAttributeValue(null, "version");
9294 if (version != null) {
9295 try {
9296 versionCode = Integer.parseInt(version);
9297 } catch (NumberFormatException e) {
9298 }
9299 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009300 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009301
9302 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009303 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009304 try {
9305 pkgFlags = Integer.parseInt(systemStr);
9306 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009307 }
9308 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009309 // For backward compatibility
9310 systemStr = parser.getAttributeValue(null, "system");
9311 if (systemStr != null) {
9312 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9313 } else {
9314 // Old settings that don't specify system... just treat
9315 // them as system, good enough.
9316 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9317 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009318 }
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009319 String timeStampStr = parser.getAttributeValue(null, "ft");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009320 if (timeStampStr != null) {
9321 try {
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009322 timeStamp = Long.parseLong(timeStampStr, 16);
9323 } catch (NumberFormatException e) {
9324 }
9325 } else {
9326 timeStampStr = parser.getAttributeValue(null, "ts");
9327 if (timeStampStr != null) {
9328 try {
9329 timeStamp = Long.parseLong(timeStampStr);
9330 } catch (NumberFormatException e) {
9331 }
9332 }
9333 }
9334 timeStampStr = parser.getAttributeValue(null, "it");
9335 if (timeStampStr != null) {
9336 try {
9337 firstInstallTime = Long.parseLong(timeStampStr, 16);
9338 } catch (NumberFormatException e) {
9339 }
9340 }
9341 timeStampStr = parser.getAttributeValue(null, "ut");
9342 if (timeStampStr != null) {
9343 try {
9344 lastUpdateTime = Long.parseLong(timeStampStr, 16);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009345 } catch (NumberFormatException e) {
9346 }
9347 }
9348 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9349 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9350 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9351 if (resourcePathStr == null) {
9352 resourcePathStr = codePathStr;
9353 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009354 if (realName != null) {
9355 realName = realName.intern();
9356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009357 if (name == null) {
9358 reportSettingsProblem(Log.WARN,
9359 "Error in package manager settings: <package> has no name at "
9360 + parser.getPositionDescription());
9361 } else if (codePathStr == null) {
9362 reportSettingsProblem(Log.WARN,
9363 "Error in package manager settings: <package> has no codePath at "
9364 + parser.getPositionDescription());
9365 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009366 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9367 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9368 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009369 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9370 + ": userId=" + userId + " pkg=" + packageSetting);
9371 if (packageSetting == null) {
9372 reportSettingsProblem(Log.ERROR,
9373 "Failure adding uid " + userId
9374 + " while parsing settings at "
9375 + parser.getPositionDescription());
9376 } else {
Kenny Root7d794fb2010-09-13 16:29:49 -07009377 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009378 packageSetting.firstInstallTime = firstInstallTime;
9379 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009380 }
9381 } else if (sharedIdStr != null) {
9382 userId = sharedIdStr != null
9383 ? Integer.parseInt(sharedIdStr) : 0;
9384 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009385 packageSetting = new PendingPackage(name.intern(), realName,
9386 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009387 nativeLibraryPathStr, userId, versionCode, pkgFlags);
Kenny Root7d794fb2010-09-13 16:29:49 -07009388 packageSetting.setTimeStamp(timeStamp);
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009389 packageSetting.firstInstallTime = firstInstallTime;
9390 packageSetting.lastUpdateTime = lastUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009391 mPendingPackages.add((PendingPackage) packageSetting);
9392 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9393 + ": sharedUserId=" + userId + " pkg="
9394 + packageSetting);
9395 } else {
9396 reportSettingsProblem(Log.WARN,
9397 "Error in package manager settings: package "
9398 + name + " has bad sharedId " + sharedIdStr
9399 + " at " + parser.getPositionDescription());
9400 }
9401 } else {
9402 reportSettingsProblem(Log.WARN,
9403 "Error in package manager settings: package "
9404 + name + " has bad userId " + idStr + " at "
9405 + parser.getPositionDescription());
9406 }
9407 } catch (NumberFormatException e) {
9408 reportSettingsProblem(Log.WARN,
9409 "Error in package manager settings: package "
9410 + name + " has bad userId " + idStr + " at "
9411 + parser.getPositionDescription());
9412 }
9413 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009414 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009415 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009416 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009417 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009418 final String enabledStr = parser.getAttributeValue(null, "enabled");
9419 if (enabledStr != null) {
9420 if (enabledStr.equalsIgnoreCase("true")) {
9421 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9422 } else if (enabledStr.equalsIgnoreCase("false")) {
9423 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9424 } else if (enabledStr.equalsIgnoreCase("default")) {
9425 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9426 } else {
9427 reportSettingsProblem(Log.WARN,
9428 "Error in package manager settings: package "
9429 + name + " has bad enabled value: " + idStr
9430 + " at " + parser.getPositionDescription());
9431 }
9432 } else {
9433 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9434 }
9435 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9436 if (installStatusStr != null) {
9437 if (installStatusStr.equalsIgnoreCase("false")) {
9438 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9439 } else {
9440 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9441 }
9442 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009444 int outerDepth = parser.getDepth();
9445 int type;
9446 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9447 && (type != XmlPullParser.END_TAG
9448 || parser.getDepth() > outerDepth)) {
9449 if (type == XmlPullParser.END_TAG
9450 || type == XmlPullParser.TEXT) {
9451 continue;
9452 }
9453
9454 String tagName = parser.getName();
9455 if (tagName.equals("disabled-components")) {
9456 readDisabledComponentsLP(packageSetting, parser);
9457 } else if (tagName.equals("enabled-components")) {
9458 readEnabledComponentsLP(packageSetting, parser);
9459 } else if (tagName.equals("sigs")) {
9460 packageSetting.signatures.readXml(parser, mPastSignatures);
9461 } else if (tagName.equals("perms")) {
9462 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009463 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009464 packageSetting.permissionsFixed = true;
9465 } else {
9466 reportSettingsProblem(Log.WARN,
9467 "Unknown element under <package>: "
9468 + parser.getName());
9469 XmlUtils.skipCurrentTag(parser);
9470 }
9471 }
9472 } else {
9473 XmlUtils.skipCurrentTag(parser);
9474 }
9475 }
9476
9477 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9478 XmlPullParser parser)
9479 throws IOException, XmlPullParserException {
9480 int outerDepth = parser.getDepth();
9481 int type;
9482 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9483 && (type != XmlPullParser.END_TAG
9484 || parser.getDepth() > outerDepth)) {
9485 if (type == XmlPullParser.END_TAG
9486 || type == XmlPullParser.TEXT) {
9487 continue;
9488 }
9489
9490 String tagName = parser.getName();
9491 if (tagName.equals("item")) {
9492 String name = parser.getAttributeValue(null, "name");
9493 if (name != null) {
9494 packageSetting.disabledComponents.add(name.intern());
9495 } else {
9496 reportSettingsProblem(Log.WARN,
9497 "Error in package manager settings: <disabled-components> has"
9498 + " no name at " + parser.getPositionDescription());
9499 }
9500 } else {
9501 reportSettingsProblem(Log.WARN,
9502 "Unknown element under <disabled-components>: "
9503 + parser.getName());
9504 }
9505 XmlUtils.skipCurrentTag(parser);
9506 }
9507 }
9508
9509 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9510 XmlPullParser parser)
9511 throws IOException, XmlPullParserException {
9512 int outerDepth = parser.getDepth();
9513 int type;
9514 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9515 && (type != XmlPullParser.END_TAG
9516 || parser.getDepth() > outerDepth)) {
9517 if (type == XmlPullParser.END_TAG
9518 || type == XmlPullParser.TEXT) {
9519 continue;
9520 }
9521
9522 String tagName = parser.getName();
9523 if (tagName.equals("item")) {
9524 String name = parser.getAttributeValue(null, "name");
9525 if (name != null) {
9526 packageSetting.enabledComponents.add(name.intern());
9527 } else {
9528 reportSettingsProblem(Log.WARN,
9529 "Error in package manager settings: <enabled-components> has"
9530 + " no name at " + parser.getPositionDescription());
9531 }
9532 } else {
9533 reportSettingsProblem(Log.WARN,
9534 "Unknown element under <enabled-components>: "
9535 + parser.getName());
9536 }
9537 XmlUtils.skipCurrentTag(parser);
9538 }
9539 }
9540
9541 private void readSharedUserLP(XmlPullParser parser)
9542 throws XmlPullParserException, IOException {
9543 String name = null;
9544 String idStr = null;
9545 int pkgFlags = 0;
9546 SharedUserSetting su = null;
9547 try {
9548 name = parser.getAttributeValue(null, "name");
9549 idStr = parser.getAttributeValue(null, "userId");
9550 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9551 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9552 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9553 }
9554 if (name == null) {
9555 reportSettingsProblem(Log.WARN,
9556 "Error in package manager settings: <shared-user> has no name at "
9557 + parser.getPositionDescription());
9558 } else if (userId == 0) {
9559 reportSettingsProblem(Log.WARN,
9560 "Error in package manager settings: shared-user "
9561 + name + " has bad userId " + idStr + " at "
9562 + parser.getPositionDescription());
9563 } else {
9564 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9565 reportSettingsProblem(Log.ERROR,
9566 "Occurred while parsing settings at "
9567 + parser.getPositionDescription());
9568 }
9569 }
9570 } catch (NumberFormatException e) {
9571 reportSettingsProblem(Log.WARN,
9572 "Error in package manager settings: package "
9573 + name + " has bad userId " + idStr + " at "
9574 + parser.getPositionDescription());
9575 };
9576
9577 if (su != null) {
9578 int outerDepth = parser.getDepth();
9579 int type;
9580 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9581 && (type != XmlPullParser.END_TAG
9582 || parser.getDepth() > outerDepth)) {
9583 if (type == XmlPullParser.END_TAG
9584 || type == XmlPullParser.TEXT) {
9585 continue;
9586 }
9587
9588 String tagName = parser.getName();
9589 if (tagName.equals("sigs")) {
9590 su.signatures.readXml(parser, mPastSignatures);
9591 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009592 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009593 } else {
9594 reportSettingsProblem(Log.WARN,
9595 "Unknown element under <shared-user>: "
9596 + parser.getName());
9597 XmlUtils.skipCurrentTag(parser);
9598 }
9599 }
9600
9601 } else {
9602 XmlUtils.skipCurrentTag(parser);
9603 }
9604 }
9605
9606 private void readGrantedPermissionsLP(XmlPullParser parser,
9607 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9608 int outerDepth = parser.getDepth();
9609 int type;
9610 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9611 && (type != XmlPullParser.END_TAG
9612 || parser.getDepth() > outerDepth)) {
9613 if (type == XmlPullParser.END_TAG
9614 || type == XmlPullParser.TEXT) {
9615 continue;
9616 }
9617
9618 String tagName = parser.getName();
9619 if (tagName.equals("item")) {
9620 String name = parser.getAttributeValue(null, "name");
9621 if (name != null) {
9622 outPerms.add(name.intern());
9623 } else {
9624 reportSettingsProblem(Log.WARN,
9625 "Error in package manager settings: <perms> has"
9626 + " no name at " + parser.getPositionDescription());
9627 }
9628 } else {
9629 reportSettingsProblem(Log.WARN,
9630 "Unknown element under <perms>: "
9631 + parser.getName());
9632 }
9633 XmlUtils.skipCurrentTag(parser);
9634 }
9635 }
9636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009637 private void readPreferredActivitiesLP(XmlPullParser parser)
9638 throws XmlPullParserException, IOException {
9639 int outerDepth = parser.getDepth();
9640 int type;
9641 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9642 && (type != XmlPullParser.END_TAG
9643 || parser.getDepth() > outerDepth)) {
9644 if (type == XmlPullParser.END_TAG
9645 || type == XmlPullParser.TEXT) {
9646 continue;
9647 }
9648
9649 String tagName = parser.getName();
9650 if (tagName.equals("item")) {
9651 PreferredActivity pa = new PreferredActivity(parser);
9652 if (pa.mParseError == null) {
9653 mPreferredActivities.addFilter(pa);
9654 } else {
9655 reportSettingsProblem(Log.WARN,
9656 "Error in package manager settings: <preferred-activity> "
9657 + pa.mParseError + " at "
9658 + parser.getPositionDescription());
9659 }
9660 } else {
9661 reportSettingsProblem(Log.WARN,
9662 "Unknown element under <preferred-activities>: "
9663 + parser.getName());
9664 XmlUtils.skipCurrentTag(parser);
9665 }
9666 }
9667 }
9668
9669 // Returns -1 if we could not find an available UserId to assign
9670 private int newUserIdLP(Object obj) {
9671 // Let's be stupidly inefficient for now...
9672 final int N = mUserIds.size();
9673 for (int i=0; i<N; i++) {
9674 if (mUserIds.get(i) == null) {
9675 mUserIds.set(i, obj);
9676 return FIRST_APPLICATION_UID + i;
9677 }
9678 }
9679
9680 // None left?
9681 if (N >= MAX_APPLICATION_UIDS) {
9682 return -1;
9683 }
9684
9685 mUserIds.add(obj);
9686 return FIRST_APPLICATION_UID + N;
9687 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009689 public PackageSetting getDisabledSystemPkg(String name) {
9690 synchronized(mPackages) {
9691 PackageSetting ps = mDisabledSysPackages.get(name);
9692 return ps;
9693 }
9694 }
9695
9696 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009697 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9698 return true;
9699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009700 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9701 if (Config.LOGV) {
9702 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9703 + " componentName = " + componentInfo.name);
9704 Log.v(TAG, "enabledComponents: "
9705 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9706 Log.v(TAG, "disabledComponents: "
9707 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9708 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009709 if (packageSettings == null) {
9710 if (false) {
9711 Log.w(TAG, "WAITING FOR DEBUGGER");
9712 Debug.waitForDebugger();
9713 Log.i(TAG, "We will crash!");
9714 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009715 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009716 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009717 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9718 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9719 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9720 return false;
9721 }
9722 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9723 return true;
9724 }
9725 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9726 return false;
9727 }
9728 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009729 }
9730 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009731
9732 // ------- apps on sdcard specific code -------
9733 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009734 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9735 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9736 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009737 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009738
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009739 private String getEncryptKey() {
9740 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009741 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9742 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009743 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009744 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9745 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009746 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009747 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009748 return null;
9749 }
9750 }
9751 return sdEncKey;
9752 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009753 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009754 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009755 } catch (IOException ioe) {
9756 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9757 + ioe);
9758 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009759 }
Rich Cannings8d578832010-09-09 15:12:40 -07009760
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009761 }
9762
Kenny Rootc78a8072010-07-27 15:18:38 -07009763 /* package */ static String getTempContainerId() {
9764 int tmpIdx = 1;
9765 String list[] = PackageHelper.getSecureContainerList();
9766 if (list != null) {
9767 for (final String name : list) {
9768 // Ignore null and non-temporary container entries
9769 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9770 continue;
9771 }
9772
9773 String subStr = name.substring(mTempContainerPrefix.length());
9774 try {
9775 int cid = Integer.parseInt(subStr);
9776 if (cid >= tmpIdx) {
9777 tmpIdx = cid + 1;
9778 }
9779 } catch (NumberFormatException e) {
9780 }
9781 }
9782 }
9783 return mTempContainerPrefix + tmpIdx;
9784 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009785
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009786 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009787 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009788 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009789 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
Marco Nelissen584f1372010-05-24 16:34:30 -07009790 int callingUid = Binder.getCallingUid();
9791 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009792 throw new SecurityException("Media status can only be updated by the system");
9793 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009794 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009795 Log.i(TAG, "Updating external media status from " +
9796 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9797 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009798 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9799 mediaStatus+", mMediaMounted=" + mMediaMounted);
9800 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009801 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9802 reportStatus ? 1 : 0, -1);
9803 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009804 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009805 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009806 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009807 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009808 // Queue up an async operation since the package installation may take a little while.
9809 mHandler.post(new Runnable() {
9810 public void run() {
9811 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009812 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009813 }
9814 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009815 }
9816
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009817 /*
9818 * Collect information of applications on external media, map them
9819 * against existing containers and update information based on current
9820 * mount status. Please note that we always have to report status
9821 * if reportStatus has been set to true especially when unloading packages.
9822 */
9823 private void updateExternalMediaStatusInner(boolean mediaStatus,
9824 boolean reportStatus) {
9825 // Collection of uids
9826 int uidArr[] = null;
9827 // Collection of stale containers
9828 HashSet<String> removeCids = new HashSet<String>();
9829 // Collection of packages on external media with valid containers.
9830 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9831 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009832 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009833 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009834 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009835 } else {
9836 // Process list of secure containers and categorize them
9837 // as active or stale based on their package internal state.
9838 int uidList[] = new int[list.length];
9839 int num = 0;
9840 synchronized (mPackages) {
9841 for (String cid : list) {
9842 SdInstallArgs args = new SdInstallArgs(cid);
9843 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009844 String pkgName = args.getPackageName();
9845 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009846 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9847 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009848 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009849 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009850 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9851 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009852 // The package status is changed only if the code path
9853 // matches between settings and the container id.
9854 if (ps != null && ps.codePathString != null &&
9855 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009856 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9857 " corresponds to pkg : " + pkgName +
9858 " at code path: " + ps.codePathString);
9859 // We do have a valid package installed on sdcard
9860 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009861 int uid = ps.userId;
9862 if (uid != -1) {
9863 uidList[num++] = uid;
9864 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009865 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009866 // Stale container on sdcard. Just delete
9867 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9868 removeCids.add(cid);
9869 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009870 }
9871 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009872
9873 if (num > 0) {
9874 // Sort uid list
9875 Arrays.sort(uidList, 0, num);
9876 // Throw away duplicates
9877 uidArr = new int[num];
9878 uidArr[0] = uidList[0];
9879 int di = 0;
9880 for (int i = 1; i < num; i++) {
9881 if (uidList[i-1] != uidList[i]) {
9882 uidArr[di++] = uidList[i];
9883 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009884 }
9885 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009886 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009887 // Process packages with valid entries.
9888 if (mediaStatus) {
9889 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009890 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009891 startCleaningPackages();
9892 } else {
9893 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009894 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009895 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009896 }
9897
9898 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009899 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009900 int size = pkgList.size();
9901 if (size > 0) {
9902 // Send broadcasts here
9903 Bundle extras = new Bundle();
9904 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9905 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009906 if (uidArr != null) {
9907 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9908 }
9909 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9910 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009911 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009912 }
9913 }
9914
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009915 /*
9916 * Look at potentially valid container ids from processCids
9917 * If package information doesn't match the one on record
9918 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009919 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009920 */
9921 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009922 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009923 ArrayList<String> pkgList = new ArrayList<String>();
9924 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009925 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009926 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009927 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009928 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9929 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009930 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009931 try {
9932 // Make sure there are no container errors first.
9933 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9934 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009935 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009936 " when installing from sdcard");
9937 continue;
9938 }
9939 // Check code path here.
9940 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009941 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009942 " does not match one in settings " + codePath);
9943 continue;
9944 }
9945 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009946 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009947 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009948 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009949 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
Dianne Hackborn78d6883692010-10-07 01:12:46 -07009950 parseFlags, 0, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009951 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009952 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009953 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009954 retCode = PackageManager.INSTALL_SUCCEEDED;
9955 pkgList.add(pkg.packageName);
9956 // Post process args
9957 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9958 }
9959 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009960 Slog.i(TAG, "Failed to install pkg from " +
9961 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009962 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009963 }
9964
9965 } finally {
9966 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9967 // Don't destroy container here. Wait till gc clears things up.
9968 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009969 }
9970 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009971 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009972 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009973 // If the platform SDK has changed since the last time we booted,
9974 // we need to re-grant app permission to catch any new ones that
9975 // appear. This is really a hack, and means that apps can in some
9976 // cases get permissions that the user didn't initially explicitly
9977 // allow... it would be nice to have some better way to handle
9978 // this situation.
9979 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9980 != mSdkVersion;
9981 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9982 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9983 + "; regranting permissions for external storage");
9984 mSettings.mExternalSdkPlatform = mSdkVersion;
9985
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009986 // Make sure group IDs have been assigned, and any permission
9987 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009988 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009989 // Persist settings
9990 mSettings.writeLP();
9991 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009992 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009993 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009994 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009995 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009996 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009997 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009998 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009999 }
Kenny Rootf369a9b2010-07-28 14:47:01 -070010000 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010001 if (removeCids != null) {
10002 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -070010003 if (cid.startsWith(mTempContainerPrefix)) {
10004 Log.i(TAG, "Destroying stale temporary container " + cid);
10005 PackageHelper.destroySdDir(cid);
10006 } else {
10007 Log.w(TAG, "Container " + cid + " is stale");
10008 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010009 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010010 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010011 }
10012
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010013 /*
10014 * Utility method to unload a list of specified containers
10015 */
10016 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
10017 // Just unmount all valid containers.
10018 for (SdInstallArgs arg : cidArgs) {
10019 synchronized (mInstallLock) {
10020 arg.doPostDeleteLI(false);
10021 }
10022 }
10023 }
10024
10025 /*
10026 * Unload packages mounted on external media. This involves deleting
10027 * package data from internal structures, sending broadcasts about
10028 * diabled packages, gc'ing to free up references, unmounting all
10029 * secure containers corresponding to packages on external media, and
10030 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
10031 * Please note that we always have to post this message if status has
10032 * been requested no matter what.
10033 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010034 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010035 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010036 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010037 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010038 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010039 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010040 for (SdInstallArgs args : keys) {
10041 String cid = args.cid;
10042 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010043 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010044 // Delete package internally
10045 PackageRemovedInfo outInfo = new PackageRemovedInfo();
10046 synchronized (mInstallLock) {
10047 boolean res = deletePackageLI(pkgName, false,
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010048 PackageManager.DONT_DELETE_DATA, outInfo, false);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010049 if (res) {
10050 pkgList.add(pkgName);
10051 } else {
Jeff Brown07330792010-03-30 19:57:08 -070010052 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -080010053 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010054 }
10055 }
10056 }
Dianne Hackborn3aeee332010-10-02 18:56:33 -070010057
10058 synchronized (mPackages) {
10059 // We didn't update the settings after removing each package;
10060 // write them now for all packages.
10061 mSettings.writeLP();
10062 }
10063
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010064 // We have to absolutely send UPDATED_MEDIA_STATUS only
10065 // after confirming that all the receivers processed the ordered
10066 // broadcast when packages get disabled, force a gc to clean things up.
10067 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -070010068 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010069 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
10070 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
10071 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010072 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10073 reportStatus ? 1 : 0, 1, keys);
10074 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010075 }
10076 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -070010077 } else {
10078 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
10079 reportStatus ? 1 : 0, -1, keys);
10080 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080010081 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -080010082 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010083
10084 public void movePackage(final String packageName,
10085 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010086 mContext.enforceCallingOrSelfPermission(
10087 android.Manifest.permission.MOVE_PACKAGE, null);
10088 int returnCode = PackageManager.MOVE_SUCCEEDED;
10089 int currFlags = 0;
10090 int newFlags = 0;
10091 synchronized (mPackages) {
10092 PackageParser.Package pkg = mPackages.get(packageName);
10093 if (pkg == null) {
10094 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010095 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010096 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -070010097 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010098 Slog.w(TAG, "Cannot move system application");
10099 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -070010100 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010101 Slog.w(TAG, "Cannot move forward locked app.");
10102 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -070010103 } else if (pkg.mOperationPending) {
10104 Slog.w(TAG, "Attempt to move package which has pending operations");
10105 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010106 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010107 // Find install location first
10108 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
10109 (flags & PackageManager.MOVE_INTERNAL) != 0) {
10110 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010111 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010112 } else {
10113 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
10114 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -070010115 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
10116 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010117 if (newFlags == currFlags) {
10118 Slog.w(TAG, "No move required. Trying to move to same location");
10119 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
10120 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010121 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010122 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10123 pkg.mOperationPending = true;
10124 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010125 }
10126 }
10127 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -070010128 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010129 } else {
10130 Message msg = mHandler.obtainMessage(INIT_COPY);
10131 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -070010132 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
10133 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
10134 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010135 msg.obj = mp;
10136 mHandler.sendMessage(msg);
10137 }
10138 }
10139 }
10140
10141 private void processPendingMove(final MoveParams mp, final int currentStatus) {
10142 // Queue up an async operation since the package deletion may take a little while.
10143 mHandler.post(new Runnable() {
10144 public void run() {
10145 mHandler.removeCallbacks(this);
10146 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010147 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
10148 int uidArr[] = null;
10149 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010150 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010151 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -070010152 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010153 Slog.w(TAG, " Package " + mp.packageName +
10154 " doesn't exist. Aborting move");
10155 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
10156 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10157 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10158 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10159 " Aborting move and returning error");
10160 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10161 } else {
10162 uidArr = new int[] { pkg.applicationInfo.uid };
10163 pkgList = new ArrayList<String>();
10164 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010165 }
10166 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010167 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10168 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -070010169 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010170 // Update package code and resource paths
10171 synchronized (mInstallLock) {
10172 synchronized (mPackages) {
10173 PackageParser.Package pkg = mPackages.get(mp.packageName);
10174 // Recheck for package again.
Kenny Root6a6b0072010-10-07 16:46:10 -070010175 if (pkg == null) {
10176 Slog.w(TAG, " Package " + mp.packageName
10177 + " doesn't exist. Aborting move");
10178 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010179 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
10180 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
10181 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
10182 " Aborting move and returning error");
10183 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
10184 } else {
Kenny Root85387d72010-08-26 10:13:11 -070010185 final String oldCodePath = pkg.mPath;
10186 final String newCodePath = mp.targetArgs.getCodePath();
10187 final String newResPath = mp.targetArgs.getResourcePath();
10188 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Kenny Root6a6b0072010-10-07 16:46:10 -070010189
10190 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) == 0) {
10191 if (mInstaller
10192 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) {
10193 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10194 } else {
10195 NativeLibraryHelper.copyNativeBinariesLI(
10196 new File(newCodePath), new File(newNativePath));
10197 }
10198 } else {
10199 if (mInstaller.linkNativeLibraryDirectory(
10200 pkg.applicationInfo.dataDir, newNativePath) < 0) {
10201 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10202 }
10203 }
10204
10205 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
10206 pkg.mPath = newCodePath;
10207 // Move dex files around
10208 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
10209 // Moving of dex files failed. Set
10210 // error code and abort move.
10211 pkg.mPath = pkg.mScanPath;
10212 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
10213 }
10214 }
10215
10216 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010217 pkg.mScanPath = newCodePath;
10218 pkg.applicationInfo.sourceDir = newCodePath;
10219 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -070010220 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010221 PackageSetting ps = (PackageSetting) pkg.mExtras;
10222 ps.codePath = new File(pkg.applicationInfo.sourceDir);
10223 ps.codePathString = ps.codePath.getPath();
10224 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
10225 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -070010226 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010227 // Set the application info flag correctly.
10228 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
10229 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10230 } else {
10231 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
10232 }
10233 ps.setFlags(pkg.applicationInfo.flags);
10234 mAppDirs.remove(oldCodePath);
10235 mAppDirs.put(newCodePath, pkg);
10236 // Persist settings
10237 mSettings.writeLP();
10238 }
10239 }
10240 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010241 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -070010242 // Send resources available broadcast
10243 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010244 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010245 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010246 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010247 // Clean up failed installation
10248 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010249 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010250 }
10251 } else {
10252 // Force a gc to clear things up.
10253 Runtime.getRuntime().gc();
10254 // Delete older code
10255 synchronized (mInstallLock) {
10256 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010257 }
10258 }
Kenny Rootdeb11262010-08-02 11:36:21 -070010259
10260 // Allow more operations on this file if we didn't fail because
10261 // an operation was already pending for this package.
10262 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
10263 synchronized (mPackages) {
10264 PackageParser.Package pkg = mPackages.get(mp.packageName);
10265 if (pkg != null) {
10266 pkg.mOperationPending = false;
10267 }
10268 }
10269 }
10270
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010271 IPackageMoveObserver observer = mp.observer;
10272 if (observer != null) {
10273 try {
10274 observer.packageMoved(mp.packageName, returnCode);
10275 } catch (RemoteException e) {
10276 Log.i(TAG, "Observer no longer exists.");
10277 }
10278 }
10279 }
10280 });
10281 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010282
10283 public boolean setInstallLocation(int loc) {
10284 mContext.enforceCallingOrSelfPermission(
10285 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10286 if (getInstallLocation() == loc) {
10287 return true;
10288 }
10289 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10290 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10291 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10292 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10293 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10294 return true;
10295 }
10296 return false;
10297 }
10298
10299 public int getInstallLocation() {
10300 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10301 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010303}