blob: 17ad9e38acaf88dd22224cfab032c3ffcd42fe14 [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;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080021import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080022import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070023import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080024import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080025
26import org.xmlpull.v1.XmlPullParser;
27import org.xmlpull.v1.XmlPullParserException;
28import org.xmlpull.v1.XmlSerializer;
29
30import android.app.ActivityManagerNative;
31import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080032import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080033import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070035import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070036import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080037import android.content.Intent;
38import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070039import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080040import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070041import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.ActivityInfo;
43import android.content.pm.ApplicationInfo;
44import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070045import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.IPackageDataObserver;
47import android.content.pm.IPackageDeleteObserver;
48import android.content.pm.IPackageInstallObserver;
49import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080050import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.IPackageStatsObserver;
52import android.content.pm.InstrumentationInfo;
53import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080054import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.content.pm.PackageManager;
56import android.content.pm.PackageStats;
57import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.content.pm.PackageParser;
61import android.content.pm.PermissionInfo;
62import android.content.pm.PermissionGroupInfo;
63import android.content.pm.ProviderInfo;
64import android.content.pm.ResolveInfo;
65import android.content.pm.ServiceInfo;
66import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.net.Uri;
68import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070069import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080071import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080073import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070074import android.os.Looper;
75import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Parcel;
77import android.os.RemoteException;
78import android.os.Environment;
79import android.os.FileObserver;
80import android.os.FileUtils;
81import android.os.Handler;
82import android.os.ParcelFileDescriptor;
83import android.os.Process;
84import android.os.ServiceManager;
85import android.os.SystemClock;
86import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070087import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080088import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.util.*;
90import android.view.Display;
91import android.view.WindowManager;
92
93import java.io.File;
94import java.io.FileDescriptor;
95import java.io.FileInputStream;
96import java.io.FileNotFoundException;
97import java.io.FileOutputStream;
98import java.io.FileReader;
99import java.io.FilenameFilter;
100import java.io.IOException;
101import java.io.InputStream;
102import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800103import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800104import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.ArrayList;
106import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700107import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.Collections;
109import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800110import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111import java.util.Enumeration;
112import java.util.HashMap;
113import java.util.HashSet;
114import java.util.Iterator;
115import java.util.List;
116import java.util.Map;
117import java.util.Set;
118import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800119import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120import java.util.zip.ZipFile;
121import java.util.zip.ZipOutputStream;
122
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700123/**
124 * Keep track of all those .apks everywhere.
125 *
126 * This is very central to the platform's security; please run the unit
127 * tests whenever making modifications here:
128 *
129mmm frameworks/base/tests/AndroidTests
130adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
131adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
132 *
133 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134class PackageManagerService extends IPackageManager.Stub {
135 private static final String TAG = "PackageManager";
136 private static final boolean DEBUG_SETTINGS = false;
137 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800138 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800139 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700140 private static final boolean DEBUG_NATIVE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141
142 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
143 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400144 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 private static final int FIRST_APPLICATION_UID =
146 Process.FIRST_APPLICATION_UID;
147 private static final int MAX_APPLICATION_UIDS = 1000;
148
149 private static final boolean SHOW_INFO = false;
150
151 private static final boolean GET_CERTIFICATES = true;
152
Oscar Montemayora8529f62009-11-18 10:14:20 -0800153 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155 private static final int REMOVE_EVENTS =
156 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
157 private static final int ADD_EVENTS =
158 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
159
160 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800161 // Suffix used during package installation when copying/moving
162 // package apks to install directory.
163 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800165 /**
166 * Indicates the state of installation. Used by PackageManager to
167 * figure out incomplete installations. Say a package is being installed
168 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
169 * the package installation is successful or unsuccesful lin which case
170 * the PackageManager will no longer maintain state information associated
171 * with the package. If some exception(like device freeze or battery being
172 * pulled out) occurs during installation of a package, the PackageManager
173 * needs this information to clean up the previously failed installation.
174 */
175 private static final int PKG_INSTALL_INCOMPLETE = 0;
176 private static final int PKG_INSTALL_COMPLETE = 1;
177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178 static final int SCAN_MONITOR = 1<<0;
179 static final int SCAN_NO_DEX = 1<<1;
180 static final int SCAN_FORCE_DEX = 1<<2;
181 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800182 static final int SCAN_NEW_INSTALL = 1<<4;
183 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700185 static final int REMOVE_CHATTY = 1<<16;
186
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800187 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
188 "com.android.defcontainer",
189 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700190
191 static final String mTempContainerPrefix = "smdl2tmp";
192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
194 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700195 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
Dianne Hackborn851a5412009-05-08 12:06:44 -0700197 final int mSdkVersion = Build.VERSION.SDK_INT;
198 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
199 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201 final Context mContext;
202 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700203 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 final DisplayMetrics mMetrics;
205 final int mDefParseFlags;
206 final String[] mSeparateProcesses;
207
208 // This is where all application persistent data goes.
209 final File mAppDataDir;
210
Oscar Montemayora8529f62009-11-18 10:14:20 -0800211 // If Encrypted File System feature is enabled, all application persistent data
212 // should go here instead.
213 final File mSecureAppDataDir;
214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800215 // This is the object monitoring the framework dir.
216 final FileObserver mFrameworkInstallObserver;
217
218 // This is the object monitoring the system app dir.
219 final FileObserver mSystemInstallObserver;
220
221 // This is the object monitoring mAppInstallDir.
222 final FileObserver mAppInstallObserver;
223
224 // This is the object monitoring mDrmAppPrivateInstallDir.
225 final FileObserver mDrmAppInstallObserver;
226
227 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
228 // LOCK HELD. Can be called with mInstallLock held.
229 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800230
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231 final File mFrameworkDir;
232 final File mSystemAppDir;
233 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700234 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
236 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
237 // apps.
238 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800239
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 // Lock for state used when installing and doing other long running
243 // operations. Methods that must be called with this lock held have
244 // the prefix "LI".
245 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 // These are the directories in the 3rd party applications installed dir
248 // that we have currently loaded packages from. Keys are the application's
249 // installed zip file (absolute codePath), and values are Package.
250 final HashMap<String, PackageParser.Package> mAppDirs =
251 new HashMap<String, PackageParser.Package>();
252
253 // Information for the parser to write more useful error messages.
254 File mScanningPath;
255 int mLastScanError;
256
257 final int[] mOutPermissions = new int[3];
258
259 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800260
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 // Keys are String (package name), values are Package. This also serves
262 // as the lock for the global state. Methods that must be called with
263 // this lock held have the prefix "LP".
264 final HashMap<String, PackageParser.Package> mPackages =
265 new HashMap<String, PackageParser.Package>();
266
267 final Settings mSettings;
268 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800269
270 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
271 int[] mGlobalGids;
272
273 // These are the built-in uid -> permission mappings that were read from the
274 // etc/permissions.xml file.
275 final SparseArray<HashSet<String>> mSystemPermissions =
276 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800278 // These are the built-in shared libraries that were read from the
279 // etc/permissions.xml file.
280 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800281
Dianne Hackborn49237342009-08-27 20:08:01 -0700282 // Temporary for building the final shared libraries for an .apk.
283 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800284
Dianne Hackborn49237342009-08-27 20:08:01 -0700285 // These are the features this devices supports that were read from the
286 // etc/permissions.xml file.
287 final HashMap<String, FeatureInfo> mAvailableFeatures =
288 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800290 // All available activities, for your resolving pleasure.
291 final ActivityIntentResolver mActivities =
292 new ActivityIntentResolver();
293
294 // All available receivers, for your resolving pleasure.
295 final ActivityIntentResolver mReceivers =
296 new ActivityIntentResolver();
297
298 // All available services, for your resolving pleasure.
299 final ServiceIntentResolver mServices = new ServiceIntentResolver();
300
301 // Keys are String (provider class name), values are Provider.
302 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
303 new HashMap<ComponentName, PackageParser.Provider>();
304
305 // Mapping from provider base names (first directory in content URI codePath)
306 // to the provider information.
307 final HashMap<String, PackageParser.Provider> mProviders =
308 new HashMap<String, PackageParser.Provider>();
309
310 // Mapping from instrumentation class names to info about them.
311 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
312 new HashMap<ComponentName, PackageParser.Instrumentation>();
313
314 // Mapping from permission names to info about them.
315 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
316 new HashMap<String, PackageParser.PermissionGroup>();
317
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800318 // Packages whose data we have transfered into another package, thus
319 // should no longer exist.
320 final HashSet<String> mTransferedPackages = new HashSet<String>();
321
Dianne Hackborn854060af2009-07-09 18:14:31 -0700322 // Broadcast actions that are only available to the system.
323 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 boolean mSystemReady;
326 boolean mSafeMode;
327 boolean mHasSystemUidErrors;
328
329 ApplicationInfo mAndroidApplication;
330 final ActivityInfo mResolveActivity = new ActivityInfo();
331 final ResolveInfo mResolveInfo = new ResolveInfo();
332 ComponentName mResolveComponentName;
333 PackageParser.Package mPlatformPackage;
334
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700335 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800336 final HashMap<String, ArrayList<String>> mPendingBroadcasts
337 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800338 // Service Connection to remote media container service to copy
339 // package uri's from external media onto secure containers
340 // or internal storage.
341 private IMediaContainerService mContainerService = null;
342
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700343 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800344 static final int MCS_BOUND = 3;
345 static final int END_COPY = 4;
346 static final int INIT_COPY = 5;
347 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800348 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800349 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800350 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800351 static final int MCS_RECONNECT = 10;
352 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700353 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700354 static final int WRITE_SETTINGS = 13;
355
356 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800357
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700358 // Delay time in millisecs
359 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800360 final private DefaultContainerConnection mDefContainerConn =
361 new DefaultContainerConnection();
362 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800363 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800364 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800365 IMediaContainerService imcs =
366 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800367 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800368 }
369
370 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800371 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800372 }
373 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700374
Christopher Tate1bb69062010-02-19 17:02:12 -0800375 // Recordkeeping of restore-after-install operations that are currently in flight
376 // between the Package Manager and the Backup Manager
377 class PostInstallData {
378 public InstallArgs args;
379 public PackageInstalledInfo res;
380
381 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
382 args = _a;
383 res = _r;
384 }
385 };
386 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
387 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
388
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700389 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800390 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800391 final ArrayList<HandlerParams> mPendingInstalls =
392 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800393
394 private boolean connectToService() {
395 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
396 " DefaultContainerService");
397 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700398 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800399 if (mContext.bindService(service, mDefContainerConn,
400 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700401 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800402 mBound = true;
403 return true;
404 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406 return false;
407 }
408
409 private void disconnectService() {
410 mContainerService = null;
411 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700412 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800413 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700414 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800415 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800416
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700417 PackageHandler(Looper looper) {
418 super(looper);
419 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700420
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700422 try {
423 doHandleMessage(msg);
424 } finally {
425 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
426 }
427 }
428
429 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700430 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800431 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800432 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800433 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800434 int idx = mPendingInstalls.size();
435 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
436 // If a bind was already initiated we dont really
437 // need to do anything. The pending install
438 // will be processed later on.
439 if (!mBound) {
440 // If this is the only one pending we might
441 // have to bind to the service again.
442 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800443 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800444 params.serviceError();
445 return;
446 } else {
447 // Once we bind to the service, the first
448 // pending request will be processed.
449 mPendingInstalls.add(idx, params);
450 }
451 } else {
452 mPendingInstalls.add(idx, params);
453 // Already bound to the service. Just make
454 // sure we trigger off processing the first request.
455 if (idx == 0) {
456 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800457 }
458 }
459 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800460 }
461 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800462 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800463 if (msg.obj != null) {
464 mContainerService = (IMediaContainerService) msg.obj;
465 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800466 if (mContainerService == null) {
467 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800468 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800469 for (HandlerParams params : mPendingInstalls) {
470 mPendingInstalls.remove(0);
471 // Indicate service bind error
472 params.serviceError();
473 }
474 mPendingInstalls.clear();
475 } else if (mPendingInstalls.size() > 0) {
476 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800477 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800478 params.startCopy();
479 }
480 } else {
481 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800482 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800483 }
484 break;
485 }
486 case MCS_RECONNECT : {
487 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
488 if (mPendingInstalls.size() > 0) {
489 if (mBound) {
490 disconnectService();
491 }
492 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800493 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800494 for (HandlerParams params : mPendingInstalls) {
495 mPendingInstalls.remove(0);
496 // Indicate service bind error
497 params.serviceError();
498 }
499 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800500 }
501 }
502 break;
503 }
504 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800505 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
506 // Delete pending install
507 if (mPendingInstalls.size() > 0) {
508 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800509 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800510 if (mPendingInstalls.size() == 0) {
511 if (mBound) {
512 disconnectService();
513 }
514 } else {
515 // There are more pending requests in queue.
516 // Just post MCS_BOUND message to trigger processing
517 // of next pending install.
518 mHandler.sendEmptyMessage(MCS_BOUND);
519 }
520 break;
521 }
522 case MCS_GIVE_UP: {
523 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
524 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800525 break;
526 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700527 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800528 String packages[];
529 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700530 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700532 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700533 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800534 if (mPendingBroadcasts == null) {
535 return;
536 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 size = mPendingBroadcasts.size();
538 if (size <= 0) {
539 // Nothing to be done. Just return
540 return;
541 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800542 packages = new String[size];
543 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700544 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800545 Iterator<HashMap.Entry<String, ArrayList<String>>>
546 it = mPendingBroadcasts.entrySet().iterator();
547 int i = 0;
548 while (it.hasNext() && i < size) {
549 HashMap.Entry<String, ArrayList<String>> ent = it.next();
550 packages[i] = ent.getKey();
551 components[i] = ent.getValue();
552 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700553 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800554 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700555 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800556 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700557 mPendingBroadcasts.clear();
558 }
559 // Send broadcasts
560 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800561 sendPackageChangedBroadcast(packages[i], true,
562 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700563 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700564 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700565 break;
566 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800567 case START_CLEANING_PACKAGE: {
568 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700569 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800570 synchronized (mPackages) {
571 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
572 mSettings.mPackagesToBeCleaned.add(packageName);
573 }
574 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700575 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800576 startCleaningPackages();
577 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800578 case POST_INSTALL: {
579 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
580 PostInstallData data = mRunningInstalls.get(msg.arg1);
581 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700582 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800583
584 if (data != null) {
585 InstallArgs args = data.args;
586 PackageInstalledInfo res = data.res;
587
588 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700589 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800590 Bundle extras = new Bundle(1);
591 extras.putInt(Intent.EXTRA_UID, res.uid);
592 final boolean update = res.removedInfo.removedPackage != null;
593 if (update) {
594 extras.putBoolean(Intent.EXTRA_REPLACING, true);
595 }
596 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
597 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700598 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800599 if (update) {
600 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
601 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700602 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800603 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700604 if (res.removedInfo.args != null) {
605 // Remove the replaced package's older resources safely now
606 deleteOld = true;
607 }
608 }
609 // Force a gc to clear up things
610 Runtime.getRuntime().gc();
611 // We delete after a gc for applications on sdcard.
612 if (deleteOld) {
613 synchronized (mInstallLock) {
614 res.removedInfo.args.doPostDeleteLI(true);
615 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800616 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800617 if (args.observer != null) {
618 try {
619 args.observer.packageInstalled(res.name, res.returnCode);
620 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800621 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800622 }
623 }
624 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800625 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800626 }
627 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700628 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700629 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
630 boolean reportStatus = msg.arg1 == 1;
631 boolean doGc = msg.arg2 == 1;
632 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
633 if (doGc) {
634 // Force a gc to clear up stale containers.
635 Runtime.getRuntime().gc();
636 }
637 if (msg.obj != null) {
638 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
639 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
640 // Unload containers
641 unloadAllContainers(args);
642 }
643 if (reportStatus) {
644 try {
645 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
646 PackageHelper.getMountService().finishMediaUpdate();
647 } catch (RemoteException e) {
648 Log.e(TAG, "MountService not running?");
649 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700650 }
651 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700652 case WRITE_SETTINGS: {
653 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
654 synchronized (mPackages) {
655 removeMessages(WRITE_SETTINGS);
656 mSettings.writeLP();
657 }
658 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
659 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700660 }
661 }
662 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800663
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700664 void scheduleWriteSettingsLocked() {
665 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
666 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
667 }
668 }
669
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800670 static boolean installOnSd(int flags) {
671 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700672 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800673 return false;
674 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700675 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
676 return true;
677 }
678 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800679 }
680
681 static boolean isFwdLocked(int flags) {
682 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
683 return true;
684 }
685 return false;
686 }
687
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 public static final IPackageManager main(Context context, boolean factoryTest) {
689 PackageManagerService m = new PackageManagerService(context, factoryTest);
690 ServiceManager.addService("package", m);
691 return m;
692 }
693
694 static String[] splitString(String str, char sep) {
695 int count = 1;
696 int i = 0;
697 while ((i=str.indexOf(sep, i)) >= 0) {
698 count++;
699 i++;
700 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800702 String[] res = new String[count];
703 i=0;
704 count = 0;
705 int lastI=0;
706 while ((i=str.indexOf(sep, i)) >= 0) {
707 res[count] = str.substring(lastI, i);
708 count++;
709 i++;
710 lastI = i;
711 }
712 res[count] = str.substring(lastI, str.length());
713 return res;
714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800716 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800717 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800718 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800719
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800721 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 mContext = context;
725 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700726 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 mMetrics = new DisplayMetrics();
728 mSettings = new Settings();
729 mSettings.addSharedUserLP("android.uid.system",
730 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
731 mSettings.addSharedUserLP("android.uid.phone",
732 MULTIPLE_APPLICATION_UIDS
733 ? RADIO_UID : FIRST_APPLICATION_UID,
734 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400735 mSettings.addSharedUserLP("android.uid.log",
736 MULTIPLE_APPLICATION_UIDS
737 ? LOG_UID : FIRST_APPLICATION_UID,
738 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739
740 String separateProcesses = SystemProperties.get("debug.separate_processes");
741 if (separateProcesses != null && separateProcesses.length() > 0) {
742 if ("*".equals(separateProcesses)) {
743 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
744 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800745 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800746 } else {
747 mDefParseFlags = 0;
748 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800749 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 + separateProcesses);
751 }
752 } else {
753 mDefParseFlags = 0;
754 mSeparateProcesses = null;
755 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 Installer installer = new Installer();
758 // Little hacky thing to check if installd is here, to determine
759 // whether we are running on the simulator and thus need to take
760 // care of building the /data file structure ourself.
761 // (apparently the sim now has a working installer)
762 if (installer.ping() && Process.supportsProcesses()) {
763 mInstaller = installer;
764 } else {
765 mInstaller = null;
766 }
767
768 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
769 Display d = wm.getDefaultDisplay();
770 d.getMetrics(mMetrics);
771
772 synchronized (mInstallLock) {
773 synchronized (mPackages) {
774 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700775 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800776
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 File dataDir = Environment.getDataDirectory();
778 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800779 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
781
782 if (mInstaller == null) {
783 // Make sure these dirs exist, when we are running in
784 // the simulator.
785 // Make a wide-open directory for random misc stuff.
786 File miscDir = new File(dataDir, "misc");
787 miscDir.mkdirs();
788 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800789 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 mDrmAppPrivateInstallDir.mkdirs();
791 }
792
793 readPermissions();
794
795 mRestoredSettings = mSettings.readLP();
796 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
798 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800800
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800801 // Set flag to monitor and not change apk file paths when
802 // scanning install directories.
803 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700804 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800805 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800806 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700807 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700812 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700815 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800816
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800817 /**
818 * Out of paranoia, ensure that everything in the boot class
819 * path has been dexed.
820 */
821 String bootClassPath = System.getProperty("java.boot.class.path");
822 if (bootClassPath != null) {
823 String[] paths = splitString(bootClassPath, ':');
824 for (int i=0; i<paths.length; i++) {
825 try {
826 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
827 libFiles.add(paths[i]);
828 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700829 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 }
831 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800832 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800834 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 }
836 }
837 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800838 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800841 /**
842 * Also ensure all external libraries have had dexopt run on them.
843 */
844 if (mSharedLibraries.size() > 0) {
845 Iterator<String> libs = mSharedLibraries.values().iterator();
846 while (libs.hasNext()) {
847 String lib = libs.next();
848 try {
849 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
850 libFiles.add(lib);
851 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700852 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 }
854 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800855 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800857 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 }
859 }
860 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 // Gross hack for now: we know this file doesn't contain any
863 // code, so don't dexopt it to avoid the resulting log spew.
864 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 /**
867 * And there are a number of commands implemented in Java, which
868 * we currently need to do the dexopt on so that they can be
869 * run from a non-root shell.
870 */
871 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700872 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 for (int i=0; i<frameworkFiles.length; i++) {
874 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
875 String path = libPath.getPath();
876 // Skip the file if we alrady did it.
877 if (libFiles.contains(path)) {
878 continue;
879 }
880 // Skip the file if it is not a type we want to dexopt.
881 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
882 continue;
883 }
884 try {
885 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
886 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700887 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 }
889 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800890 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800891 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800892 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800893 }
894 }
895 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800896
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700897 if (didDexOpt) {
898 // If we had to do a dexopt of one of the previous
899 // things, then something on the system has changed.
900 // Consider this significant, and wipe away all other
901 // existing dexopt files to ensure we don't leave any
902 // dangling around.
903 String[] files = mDalvikCacheDir.list();
904 if (files != null) {
905 for (int i=0; i<files.length; i++) {
906 String fn = files[i];
907 if (fn.startsWith("data@app@")
908 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800909 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700910 (new File(mDalvikCacheDir, fn)).delete();
911 }
912 }
913 }
914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800916
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800917 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 mFrameworkInstallObserver = new AppDirObserver(
919 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
920 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700921 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
922 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800923 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800924
925 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800926 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
927 mSystemInstallObserver = new AppDirObserver(
928 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
929 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700930 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
931 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800932
933 if (mInstaller != null) {
934 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
935 mInstaller.moveFiles();
936 }
937
938 // Prune any system packages that no longer exist.
939 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
940 while (psit.hasNext()) {
941 PackageSetting ps = psit.next();
942 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800943 && !mPackages.containsKey(ps.name)
944 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800945 psit.remove();
946 String msg = "System package " + ps.name
947 + " no longer exists; wiping its data";
948 reportSettingsProblem(Log.WARN, msg);
949 if (mInstaller != null) {
950 // XXX how to set useEncryptedFSDir for packages that
951 // are not encrypted?
952 mInstaller.remove(ps.name, true);
953 }
954 }
955 }
956
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 mAppInstallDir = new File(dataDir, "app");
958 if (mInstaller == null) {
959 // Make sure these dirs exist, when we are running in
960 // the simulator.
961 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
962 }
963 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800964 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 //clean up list
966 for(int i = 0; i < deletePkgsList.size(); i++) {
967 //clean up here
968 cleanupInstallFailedPackage(deletePkgsList.get(i));
969 }
970 //delete tmp files
971 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800972
973 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800974 SystemClock.uptimeMillis());
975 mAppInstallObserver = new AppDirObserver(
976 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
977 mAppInstallObserver.startWatching();
978 scanDirLI(mAppInstallDir, 0, scanMode);
979
980 mDrmAppInstallObserver = new AppDirObserver(
981 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
982 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800983 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800985 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800987 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 + ((SystemClock.uptimeMillis()-startTime)/1000f)
989 + " seconds");
990
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700991 // If the platform SDK has changed since the last time we booted,
992 // we need to re-grant app permission to catch any new ones that
993 // appear. This is really a hack, and means that apps can in some
994 // cases get permissions that the user didn't initially explicitly
995 // allow... it would be nice to have some better way to handle
996 // this situation.
997 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
998 != mSdkVersion;
999 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1000 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1001 + "; regranting permissions for internal storage");
1002 mSettings.mInternalSdkPlatform = mSdkVersion;
1003
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001004 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001005
1006 mSettings.writeLP();
1007
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001008 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 // Now after opening every single application zip, make sure they
1012 // are all flushed. Not really needed, but keeps things nice and
1013 // tidy.
1014 Runtime.getRuntime().gc();
1015 } // synchronized (mPackages)
1016 } // synchronized (mInstallLock)
1017 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 @Override
1020 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1021 throws RemoteException {
1022 try {
1023 return super.onTransact(code, data, reply, flags);
1024 } catch (RuntimeException e) {
1025 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001026 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
1028 throw e;
1029 }
1030 }
1031
Dianne Hackborne6620b22010-01-22 14:46:21 -08001032 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001033 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001035 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1036 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001038 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001039 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 }
1041 } else {
1042 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001043 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 File dataDir = new File(pkg.applicationInfo.dataDir);
1045 dataDir.delete();
1046 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001047 if (ps.codePath != null) {
1048 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001049 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001050 }
1051 }
1052 if (ps.resourcePath != null) {
1053 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001054 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001055 }
1056 }
1057 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
1059
1060 void readPermissions() {
1061 // Read permissions from .../etc/permission directory.
1062 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1063 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001064 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 return;
1066 }
1067 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001068 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 return;
1070 }
1071
1072 // Iterate over the files in the directory and scan .xml files
1073 for (File f : libraryDir.listFiles()) {
1074 // We'll read platform.xml last
1075 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1076 continue;
1077 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001079 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001080 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 continue;
1082 }
1083 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001084 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 continue;
1086 }
1087
1088 readPermissionsFromXml(f);
1089 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1092 final File permFile = new File(Environment.getRootDirectory(),
1093 "etc/permissions/platform.xml");
1094 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001095
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001096 StringBuilder sb = new StringBuilder(128);
1097 sb.append("Libs:");
1098 Iterator<String> it = mSharedLibraries.keySet().iterator();
1099 while (it.hasNext()) {
1100 sb.append(' ');
1101 String name = it.next();
1102 sb.append(name);
1103 sb.append(':');
1104 sb.append(mSharedLibraries.get(name));
1105 }
1106 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001107
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001108 sb.setLength(0);
1109 sb.append("Features:");
1110 it = mAvailableFeatures.keySet().iterator();
1111 while (it.hasNext()) {
1112 sb.append(' ');
1113 sb.append(it.next());
1114 }
1115 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001117
1118 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 FileReader permReader = null;
1120 try {
1121 permReader = new FileReader(permFile);
1122 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001123 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 return;
1125 }
1126
1127 try {
1128 XmlPullParser parser = Xml.newPullParser();
1129 parser.setInput(permReader);
1130
1131 XmlUtils.beginDocument(parser, "permissions");
1132
1133 while (true) {
1134 XmlUtils.nextElement(parser);
1135 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1136 break;
1137 }
1138
1139 String name = parser.getName();
1140 if ("group".equals(name)) {
1141 String gidStr = parser.getAttributeValue(null, "gid");
1142 if (gidStr != null) {
1143 int gid = Integer.parseInt(gidStr);
1144 mGlobalGids = appendInt(mGlobalGids, gid);
1145 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001146 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 + parser.getPositionDescription());
1148 }
1149
1150 XmlUtils.skipCurrentTag(parser);
1151 continue;
1152 } else if ("permission".equals(name)) {
1153 String perm = parser.getAttributeValue(null, "name");
1154 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001155 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 + parser.getPositionDescription());
1157 XmlUtils.skipCurrentTag(parser);
1158 continue;
1159 }
1160 perm = perm.intern();
1161 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 } else if ("assign-permission".equals(name)) {
1164 String perm = parser.getAttributeValue(null, "name");
1165 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001166 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 + parser.getPositionDescription());
1168 XmlUtils.skipCurrentTag(parser);
1169 continue;
1170 }
1171 String uidStr = parser.getAttributeValue(null, "uid");
1172 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001173 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 + parser.getPositionDescription());
1175 XmlUtils.skipCurrentTag(parser);
1176 continue;
1177 }
1178 int uid = Process.getUidForName(uidStr);
1179 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001180 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 + uidStr + "\" at "
1182 + parser.getPositionDescription());
1183 XmlUtils.skipCurrentTag(parser);
1184 continue;
1185 }
1186 perm = perm.intern();
1187 HashSet<String> perms = mSystemPermissions.get(uid);
1188 if (perms == null) {
1189 perms = new HashSet<String>();
1190 mSystemPermissions.put(uid, perms);
1191 }
1192 perms.add(perm);
1193 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 } else if ("library".equals(name)) {
1196 String lname = parser.getAttributeValue(null, "name");
1197 String lfile = parser.getAttributeValue(null, "file");
1198 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 + parser.getPositionDescription());
1201 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001202 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 + parser.getPositionDescription());
1204 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001205 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001206 mSharedLibraries.put(lname, lfile);
1207 }
1208 XmlUtils.skipCurrentTag(parser);
1209 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001210
Dianne Hackborn49237342009-08-27 20:08:01 -07001211 } else if ("feature".equals(name)) {
1212 String fname = parser.getAttributeValue(null, "name");
1213 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001214 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 + parser.getPositionDescription());
1216 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001217 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001218 FeatureInfo fi = new FeatureInfo();
1219 fi.name = fname;
1220 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 }
1222 XmlUtils.skipCurrentTag(parser);
1223 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 } else {
1226 XmlUtils.skipCurrentTag(parser);
1227 continue;
1228 }
1229
1230 }
1231 } catch (XmlPullParserException 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 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001234 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001235 }
1236 }
1237
1238 void readPermission(XmlPullParser parser, String name)
1239 throws IOException, XmlPullParserException {
1240
1241 name = name.intern();
1242
1243 BasePermission bp = mSettings.mPermissions.get(name);
1244 if (bp == null) {
1245 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1246 mSettings.mPermissions.put(name, bp);
1247 }
1248 int outerDepth = parser.getDepth();
1249 int type;
1250 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1251 && (type != XmlPullParser.END_TAG
1252 || parser.getDepth() > outerDepth)) {
1253 if (type == XmlPullParser.END_TAG
1254 || type == XmlPullParser.TEXT) {
1255 continue;
1256 }
1257
1258 String tagName = parser.getName();
1259 if ("group".equals(tagName)) {
1260 String gidStr = parser.getAttributeValue(null, "gid");
1261 if (gidStr != null) {
1262 int gid = Process.getGidForName(gidStr);
1263 bp.gids = appendInt(bp.gids, gid);
1264 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001265 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 + parser.getPositionDescription());
1267 }
1268 }
1269 XmlUtils.skipCurrentTag(parser);
1270 }
1271 }
1272
1273 static int[] appendInt(int[] cur, int val) {
1274 if (cur == null) {
1275 return new int[] { val };
1276 }
1277 final int N = cur.length;
1278 for (int i=0; i<N; i++) {
1279 if (cur[i] == val) {
1280 return cur;
1281 }
1282 }
1283 int[] ret = new int[N+1];
1284 System.arraycopy(cur, 0, ret, 0, N);
1285 ret[N] = val;
1286 return ret;
1287 }
1288
1289 static int[] appendInts(int[] cur, int[] add) {
1290 if (add == null) return cur;
1291 if (cur == null) return add;
1292 final int N = add.length;
1293 for (int i=0; i<N; i++) {
1294 cur = appendInt(cur, add[i]);
1295 }
1296 return cur;
1297 }
1298
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001299 static int[] removeInt(int[] cur, int val) {
1300 if (cur == null) {
1301 return null;
1302 }
1303 final int N = cur.length;
1304 for (int i=0; i<N; i++) {
1305 if (cur[i] == val) {
1306 int[] ret = new int[N-1];
1307 if (i > 0) {
1308 System.arraycopy(cur, 0, ret, 0, i);
1309 }
1310 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001311 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001312 }
1313 return ret;
1314 }
1315 }
1316 return cur;
1317 }
1318
1319 static int[] removeInts(int[] cur, int[] rem) {
1320 if (rem == null) return cur;
1321 if (cur == null) return cur;
1322 final int N = rem.length;
1323 for (int i=0; i<N; i++) {
1324 cur = removeInt(cur, rem[i]);
1325 }
1326 return cur;
1327 }
1328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001330 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1331 // The package has been uninstalled but has retained data and resources.
1332 return PackageParser.generatePackageInfo(p, null, flags);
1333 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 final PackageSetting ps = (PackageSetting)p.mExtras;
1335 if (ps == null) {
1336 return null;
1337 }
1338 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1339 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1340 }
1341
1342 public PackageInfo getPackageInfo(String packageName, int flags) {
1343 synchronized (mPackages) {
1344 PackageParser.Package p = mPackages.get(packageName);
1345 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001346 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 + ": " + p);
1348 if (p != null) {
1349 return generatePackageInfo(p, flags);
1350 }
1351 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1352 return generatePackageInfoFromSettingsLP(packageName, flags);
1353 }
1354 }
1355 return null;
1356 }
1357
Dianne Hackborn47096932010-02-11 15:57:09 -08001358 public String[] currentToCanonicalPackageNames(String[] names) {
1359 String[] out = new String[names.length];
1360 synchronized (mPackages) {
1361 for (int i=names.length-1; i>=0; i--) {
1362 PackageSetting ps = mSettings.mPackages.get(names[i]);
1363 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1364 }
1365 }
1366 return out;
1367 }
1368
1369 public String[] canonicalToCurrentPackageNames(String[] names) {
1370 String[] out = new String[names.length];
1371 synchronized (mPackages) {
1372 for (int i=names.length-1; i>=0; i--) {
1373 String cur = mSettings.mRenamedPackages.get(names[i]);
1374 out[i] = cur != null ? cur : names[i];
1375 }
1376 }
1377 return out;
1378 }
1379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 public int getPackageUid(String packageName) {
1381 synchronized (mPackages) {
1382 PackageParser.Package p = mPackages.get(packageName);
1383 if(p != null) {
1384 return p.applicationInfo.uid;
1385 }
1386 PackageSetting ps = mSettings.mPackages.get(packageName);
1387 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1388 return -1;
1389 }
1390 p = ps.pkg;
1391 return p != null ? p.applicationInfo.uid : -1;
1392 }
1393 }
1394
1395 public int[] getPackageGids(String packageName) {
1396 synchronized (mPackages) {
1397 PackageParser.Package p = mPackages.get(packageName);
1398 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001399 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 + ": " + p);
1401 if (p != null) {
1402 final PackageSetting ps = (PackageSetting)p.mExtras;
1403 final SharedUserSetting suid = ps.sharedUser;
1404 return suid != null ? suid.gids : ps.gids;
1405 }
1406 }
1407 // stupid thing to indicate an error.
1408 return new int[0];
1409 }
1410
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001411 static final PermissionInfo generatePermissionInfo(
1412 BasePermission bp, int flags) {
1413 if (bp.perm != null) {
1414 return PackageParser.generatePermissionInfo(bp.perm, flags);
1415 }
1416 PermissionInfo pi = new PermissionInfo();
1417 pi.name = bp.name;
1418 pi.packageName = bp.sourcePackage;
1419 pi.nonLocalizedLabel = bp.name;
1420 pi.protectionLevel = bp.protectionLevel;
1421 return pi;
1422 }
1423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 public PermissionInfo getPermissionInfo(String name, int flags) {
1425 synchronized (mPackages) {
1426 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001427 if (p != null) {
1428 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430 return null;
1431 }
1432 }
1433
1434 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1435 synchronized (mPackages) {
1436 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1437 for (BasePermission p : mSettings.mPermissions.values()) {
1438 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001439 if (p.perm == null || p.perm.info.group == null) {
1440 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
1442 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001443 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1445 }
1446 }
1447 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 if (out.size() > 0) {
1450 return out;
1451 }
1452 return mPermissionGroups.containsKey(group) ? out : null;
1453 }
1454 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1457 synchronized (mPackages) {
1458 return PackageParser.generatePermissionGroupInfo(
1459 mPermissionGroups.get(name), flags);
1460 }
1461 }
1462
1463 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1464 synchronized (mPackages) {
1465 final int N = mPermissionGroups.size();
1466 ArrayList<PermissionGroupInfo> out
1467 = new ArrayList<PermissionGroupInfo>(N);
1468 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1469 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1470 }
1471 return out;
1472 }
1473 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1476 PackageSetting ps = mSettings.mPackages.get(packageName);
1477 if(ps != null) {
1478 if(ps.pkg == null) {
1479 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1480 if(pInfo != null) {
1481 return pInfo.applicationInfo;
1482 }
1483 return null;
1484 }
1485 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1486 }
1487 return null;
1488 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001490 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1491 PackageSetting ps = mSettings.mPackages.get(packageName);
1492 if(ps != null) {
1493 if(ps.pkg == null) {
1494 ps.pkg = new PackageParser.Package(packageName);
1495 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001496 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1497 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1498 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1499 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
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
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001620 public String[] getSystemSharedLibraryNames() {
1621 Set<String> libSet;
1622 synchronized (mPackages) {
1623 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001624 int size = libSet.size();
1625 if (size > 0) {
1626 String[] libs = new String[size];
1627 libSet.toArray(libs);
1628 return libs;
1629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001631 return null;
1632 }
1633
1634 public FeatureInfo[] getSystemAvailableFeatures() {
1635 Collection<FeatureInfo> featSet;
1636 synchronized (mPackages) {
1637 featSet = mAvailableFeatures.values();
1638 int size = featSet.size();
1639 if (size > 0) {
1640 FeatureInfo[] features = new FeatureInfo[size+1];
1641 featSet.toArray(features);
1642 FeatureInfo fi = new FeatureInfo();
1643 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1644 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1645 features[size] = fi;
1646 return features;
1647 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 return null;
1650 }
1651
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001652 public boolean hasSystemFeature(String name) {
1653 synchronized (mPackages) {
1654 return mAvailableFeatures.containsKey(name);
1655 }
1656 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 public int checkPermission(String permName, String pkgName) {
1659 synchronized (mPackages) {
1660 PackageParser.Package p = mPackages.get(pkgName);
1661 if (p != null && p.mExtras != null) {
1662 PackageSetting ps = (PackageSetting)p.mExtras;
1663 if (ps.sharedUser != null) {
1664 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1665 return PackageManager.PERMISSION_GRANTED;
1666 }
1667 } else if (ps.grantedPermissions.contains(permName)) {
1668 return PackageManager.PERMISSION_GRANTED;
1669 }
1670 }
1671 }
1672 return PackageManager.PERMISSION_DENIED;
1673 }
1674
1675 public int checkUidPermission(String permName, int uid) {
1676 synchronized (mPackages) {
1677 Object obj = mSettings.getUserIdLP(uid);
1678 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001679 GrantedPermissions gp = (GrantedPermissions)obj;
1680 if (gp.grantedPermissions.contains(permName)) {
1681 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 }
1683 } else {
1684 HashSet<String> perms = mSystemPermissions.get(uid);
1685 if (perms != null && perms.contains(permName)) {
1686 return PackageManager.PERMISSION_GRANTED;
1687 }
1688 }
1689 }
1690 return PackageManager.PERMISSION_DENIED;
1691 }
1692
1693 private BasePermission findPermissionTreeLP(String permName) {
1694 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1695 if (permName.startsWith(bp.name) &&
1696 permName.length() > bp.name.length() &&
1697 permName.charAt(bp.name.length()) == '.') {
1698 return bp;
1699 }
1700 }
1701 return null;
1702 }
1703
1704 private BasePermission checkPermissionTreeLP(String permName) {
1705 if (permName != null) {
1706 BasePermission bp = findPermissionTreeLP(permName);
1707 if (bp != null) {
1708 if (bp.uid == Binder.getCallingUid()) {
1709 return bp;
1710 }
1711 throw new SecurityException("Calling uid "
1712 + Binder.getCallingUid()
1713 + " is not allowed to add to permission tree "
1714 + bp.name + " owned by uid " + bp.uid);
1715 }
1716 }
1717 throw new SecurityException("No permission tree found for " + permName);
1718 }
1719
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001720 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1721 if (s1 == null) {
1722 return s2 == null;
1723 }
1724 if (s2 == null) {
1725 return false;
1726 }
1727 if (s1.getClass() != s2.getClass()) {
1728 return false;
1729 }
1730 return s1.equals(s2);
1731 }
1732
1733 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1734 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001735 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001736 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1737 if (!compareStrings(pi1.name, pi2.name)) return false;
1738 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1739 // We'll take care of setting this one.
1740 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1741 // These are not currently stored in settings.
1742 //if (!compareStrings(pi1.group, pi2.group)) return false;
1743 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1744 //if (pi1.labelRes != pi2.labelRes) return false;
1745 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1746 return true;
1747 }
1748
1749 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1750 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1751 throw new SecurityException("Label must be specified in permission");
1752 }
1753 BasePermission tree = checkPermissionTreeLP(info.name);
1754 BasePermission bp = mSettings.mPermissions.get(info.name);
1755 boolean added = bp == null;
1756 boolean changed = true;
1757 if (added) {
1758 bp = new BasePermission(info.name, tree.sourcePackage,
1759 BasePermission.TYPE_DYNAMIC);
1760 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1761 throw new SecurityException(
1762 "Not allowed to modify non-dynamic permission "
1763 + info.name);
1764 } else {
1765 if (bp.protectionLevel == info.protectionLevel
1766 && bp.perm.owner.equals(tree.perm.owner)
1767 && bp.uid == tree.uid
1768 && comparePermissionInfos(bp.perm.info, info)) {
1769 changed = false;
1770 }
1771 }
1772 bp.protectionLevel = info.protectionLevel;
1773 bp.perm = new PackageParser.Permission(tree.perm.owner,
1774 new PermissionInfo(info));
1775 bp.perm.info.packageName = tree.perm.info.packageName;
1776 bp.uid = tree.uid;
1777 if (added) {
1778 mSettings.mPermissions.put(info.name, bp);
1779 }
1780 if (changed) {
1781 if (!async) {
1782 mSettings.writeLP();
1783 } else {
1784 scheduleWriteSettingsLocked();
1785 }
1786 }
1787 return added;
1788 }
1789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 public boolean addPermission(PermissionInfo info) {
1791 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001792 return addPermissionLocked(info, false);
1793 }
1794 }
1795
1796 public boolean addPermissionAsync(PermissionInfo info) {
1797 synchronized (mPackages) {
1798 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 }
1800 }
1801
1802 public void removePermission(String name) {
1803 synchronized (mPackages) {
1804 checkPermissionTreeLP(name);
1805 BasePermission bp = mSettings.mPermissions.get(name);
1806 if (bp != null) {
1807 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1808 throw new SecurityException(
1809 "Not allowed to modify non-dynamic permission "
1810 + name);
1811 }
1812 mSettings.mPermissions.remove(name);
1813 mSettings.writeLP();
1814 }
1815 }
1816 }
1817
Dianne Hackborn854060af2009-07-09 18:14:31 -07001818 public boolean isProtectedBroadcast(String actionName) {
1819 synchronized (mPackages) {
1820 return mProtectedBroadcasts.contains(actionName);
1821 }
1822 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001824 public int checkSignatures(String pkg1, String pkg2) {
1825 synchronized (mPackages) {
1826 PackageParser.Package p1 = mPackages.get(pkg1);
1827 PackageParser.Package p2 = mPackages.get(pkg2);
1828 if (p1 == null || p1.mExtras == null
1829 || p2 == null || p2.mExtras == null) {
1830 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1831 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001832 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 }
1834 }
1835
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001836 public int checkUidSignatures(int uid1, int uid2) {
1837 synchronized (mPackages) {
1838 Signature[] s1;
1839 Signature[] s2;
1840 Object obj = mSettings.getUserIdLP(uid1);
1841 if (obj != null) {
1842 if (obj instanceof SharedUserSetting) {
1843 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1844 } else if (obj instanceof PackageSetting) {
1845 s1 = ((PackageSetting)obj).signatures.mSignatures;
1846 } else {
1847 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1848 }
1849 } else {
1850 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1851 }
1852 obj = mSettings.getUserIdLP(uid2);
1853 if (obj != null) {
1854 if (obj instanceof SharedUserSetting) {
1855 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1856 } else if (obj instanceof PackageSetting) {
1857 s2 = ((PackageSetting)obj).signatures.mSignatures;
1858 } else {
1859 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1860 }
1861 } else {
1862 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1863 }
1864 return checkSignaturesLP(s1, s2);
1865 }
1866 }
1867
1868 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1869 if (s1 == null) {
1870 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1872 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1873 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001874 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1876 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001877 HashSet<Signature> set1 = new HashSet<Signature>();
1878 for (Signature sig : s1) {
1879 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001881 HashSet<Signature> set2 = new HashSet<Signature>();
1882 for (Signature sig : s2) {
1883 set2.add(sig);
1884 }
1885 // Make sure s2 contains all signatures in s1.
1886 if (set1.equals(set2)) {
1887 return PackageManager.SIGNATURE_MATCH;
1888 }
1889 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
1891
1892 public String[] getPackagesForUid(int uid) {
1893 synchronized (mPackages) {
1894 Object obj = mSettings.getUserIdLP(uid);
1895 if (obj instanceof SharedUserSetting) {
1896 SharedUserSetting sus = (SharedUserSetting)obj;
1897 final int N = sus.packages.size();
1898 String[] res = new String[N];
1899 Iterator<PackageSetting> it = sus.packages.iterator();
1900 int i=0;
1901 while (it.hasNext()) {
1902 res[i++] = it.next().name;
1903 }
1904 return res;
1905 } else if (obj instanceof PackageSetting) {
1906 PackageSetting ps = (PackageSetting)obj;
1907 return new String[] { ps.name };
1908 }
1909 }
1910 return null;
1911 }
1912
1913 public String getNameForUid(int uid) {
1914 synchronized (mPackages) {
1915 Object obj = mSettings.getUserIdLP(uid);
1916 if (obj instanceof SharedUserSetting) {
1917 SharedUserSetting sus = (SharedUserSetting)obj;
1918 return sus.name + ":" + sus.userId;
1919 } else if (obj instanceof PackageSetting) {
1920 PackageSetting ps = (PackageSetting)obj;
1921 return ps.name;
1922 }
1923 }
1924 return null;
1925 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 public int getUidForSharedUser(String sharedUserName) {
1928 if(sharedUserName == null) {
1929 return -1;
1930 }
1931 synchronized (mPackages) {
1932 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1933 if(suid == null) {
1934 return -1;
1935 }
1936 return suid.userId;
1937 }
1938 }
1939
1940 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1941 int flags) {
1942 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001943 return chooseBestActivity(intent, resolvedType, flags, query);
1944 }
1945
Mihai Predaeae850c2009-05-13 10:13:48 +02001946 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1947 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 if (query != null) {
1949 final int N = query.size();
1950 if (N == 1) {
1951 return query.get(0);
1952 } else if (N > 1) {
1953 // If there is more than one activity with the same priority,
1954 // then let the user decide between them.
1955 ResolveInfo r0 = query.get(0);
1956 ResolveInfo r1 = query.get(1);
1957 if (false) {
1958 System.out.println(r0.activityInfo.name +
1959 "=" + r0.priority + " vs " +
1960 r1.activityInfo.name +
1961 "=" + r1.priority);
1962 }
1963 // If the first activity has a higher priority, or a different
1964 // default, then it is always desireable to pick it.
1965 if (r0.priority != r1.priority
1966 || r0.preferredOrder != r1.preferredOrder
1967 || r0.isDefault != r1.isDefault) {
1968 return query.get(0);
1969 }
1970 // If we have saved a preference for a preferred activity for
1971 // this Intent, use that.
1972 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1973 flags, query, r0.priority);
1974 if (ri != null) {
1975 return ri;
1976 }
1977 return mResolveInfo;
1978 }
1979 }
1980 return null;
1981 }
1982
1983 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1984 int flags, List<ResolveInfo> query, int priority) {
1985 synchronized (mPackages) {
1986 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1987 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001988 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001989 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
1990 if (prefs != null && prefs.size() > 0) {
1991 // First figure out how good the original match set is.
1992 // We will only allow preferred activities that came
1993 // from the same match quality.
1994 int match = 0;
1995 final int N = query.size();
1996 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
1997 for (int j=0; j<N; j++) {
1998 ResolveInfo ri = query.get(j);
1999 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2000 + ": 0x" + Integer.toHexString(match));
2001 if (ri.match > match) match = ri.match;
2002 }
2003 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2004 + Integer.toHexString(match));
2005 match &= IntentFilter.MATCH_CATEGORY_MASK;
2006 final int M = prefs.size();
2007 for (int i=0; i<M; i++) {
2008 PreferredActivity pa = prefs.get(i);
2009 if (pa.mMatch != match) {
2010 continue;
2011 }
2012 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2013 if (DEBUG_PREFERRED) {
2014 Log.v(TAG, "Got preferred activity:");
2015 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2016 }
2017 if (ai != null) {
2018 for (int j=0; j<N; j++) {
2019 ResolveInfo ri = query.get(j);
2020 if (!ri.activityInfo.applicationInfo.packageName
2021 .equals(ai.applicationInfo.packageName)) {
2022 continue;
2023 }
2024 if (!ri.activityInfo.name.equals(ai.name)) {
2025 continue;
2026 }
2027
2028 // Okay we found a previously set preferred app.
2029 // If the result set is different from when this
2030 // was created, we need to clear it and re-ask the
2031 // user their preference.
2032 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002033 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 + intent + " type " + resolvedType);
2035 mSettings.mPreferredActivities.removeFilter(pa);
2036 return null;
2037 }
2038
2039 // Yay!
2040 return ri;
2041 }
2042 }
2043 }
2044 }
2045 }
2046 return null;
2047 }
2048
2049 public List<ResolveInfo> queryIntentActivities(Intent intent,
2050 String resolvedType, int flags) {
2051 ComponentName comp = intent.getComponent();
2052 if (comp != null) {
2053 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2054 ActivityInfo ai = getActivityInfo(comp, flags);
2055 if (ai != null) {
2056 ResolveInfo ri = new ResolveInfo();
2057 ri.activityInfo = ai;
2058 list.add(ri);
2059 }
2060 return list;
2061 }
2062
2063 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002064 String pkgName = intent.getPackage();
2065 if (pkgName == null) {
2066 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2067 resolvedType, flags);
2068 }
2069 PackageParser.Package pkg = mPackages.get(pkgName);
2070 if (pkg != null) {
2071 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2072 resolvedType, flags, pkg.activities);
2073 }
2074 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 }
2076 }
2077
2078 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2079 Intent[] specifics, String[] specificTypes, Intent intent,
2080 String resolvedType, int flags) {
2081 final String resultsAction = intent.getAction();
2082
2083 List<ResolveInfo> results = queryIntentActivities(
2084 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2085 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2086
2087 int specificsPos = 0;
2088 int N;
2089
2090 // todo: note that the algorithm used here is O(N^2). This
2091 // isn't a problem in our current environment, but if we start running
2092 // into situations where we have more than 5 or 10 matches then this
2093 // should probably be changed to something smarter...
2094
2095 // First we go through and resolve each of the specific items
2096 // that were supplied, taking care of removing any corresponding
2097 // duplicate items in the generic resolve list.
2098 if (specifics != null) {
2099 for (int i=0; i<specifics.length; i++) {
2100 final Intent sintent = specifics[i];
2101 if (sintent == null) {
2102 continue;
2103 }
2104
2105 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2106 String action = sintent.getAction();
2107 if (resultsAction != null && resultsAction.equals(action)) {
2108 // If this action was explicitly requested, then don't
2109 // remove things that have it.
2110 action = null;
2111 }
2112 ComponentName comp = sintent.getComponent();
2113 ResolveInfo ri = null;
2114 ActivityInfo ai = null;
2115 if (comp == null) {
2116 ri = resolveIntent(
2117 sintent,
2118 specificTypes != null ? specificTypes[i] : null,
2119 flags);
2120 if (ri == null) {
2121 continue;
2122 }
2123 if (ri == mResolveInfo) {
2124 // ACK! Must do something better with this.
2125 }
2126 ai = ri.activityInfo;
2127 comp = new ComponentName(ai.applicationInfo.packageName,
2128 ai.name);
2129 } else {
2130 ai = getActivityInfo(comp, flags);
2131 if (ai == null) {
2132 continue;
2133 }
2134 }
2135
2136 // Look for any generic query activities that are duplicates
2137 // of this specific one, and remove them from the results.
2138 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2139 N = results.size();
2140 int j;
2141 for (j=specificsPos; j<N; j++) {
2142 ResolveInfo sri = results.get(j);
2143 if ((sri.activityInfo.name.equals(comp.getClassName())
2144 && sri.activityInfo.applicationInfo.packageName.equals(
2145 comp.getPackageName()))
2146 || (action != null && sri.filter.matchAction(action))) {
2147 results.remove(j);
2148 if (Config.LOGV) Log.v(
2149 TAG, "Removing duplicate item from " + j
2150 + " due to specific " + specificsPos);
2151 if (ri == null) {
2152 ri = sri;
2153 }
2154 j--;
2155 N--;
2156 }
2157 }
2158
2159 // Add this specific item to its proper place.
2160 if (ri == null) {
2161 ri = new ResolveInfo();
2162 ri.activityInfo = ai;
2163 }
2164 results.add(specificsPos, ri);
2165 ri.specificIndex = i;
2166 specificsPos++;
2167 }
2168 }
2169
2170 // Now we go through the remaining generic results and remove any
2171 // duplicate actions that are found here.
2172 N = results.size();
2173 for (int i=specificsPos; i<N-1; i++) {
2174 final ResolveInfo rii = results.get(i);
2175 if (rii.filter == null) {
2176 continue;
2177 }
2178
2179 // Iterate over all of the actions of this result's intent
2180 // filter... typically this should be just one.
2181 final Iterator<String> it = rii.filter.actionsIterator();
2182 if (it == null) {
2183 continue;
2184 }
2185 while (it.hasNext()) {
2186 final String action = it.next();
2187 if (resultsAction != null && resultsAction.equals(action)) {
2188 // If this action was explicitly requested, then don't
2189 // remove things that have it.
2190 continue;
2191 }
2192 for (int j=i+1; j<N; j++) {
2193 final ResolveInfo rij = results.get(j);
2194 if (rij.filter != null && rij.filter.hasAction(action)) {
2195 results.remove(j);
2196 if (Config.LOGV) Log.v(
2197 TAG, "Removing duplicate item from " + j
2198 + " due to action " + action + " at " + i);
2199 j--;
2200 N--;
2201 }
2202 }
2203 }
2204
2205 // If the caller didn't request filter information, drop it now
2206 // so we don't have to marshall/unmarshall it.
2207 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2208 rii.filter = null;
2209 }
2210 }
2211
2212 // Filter out the caller activity if so requested.
2213 if (caller != null) {
2214 N = results.size();
2215 for (int i=0; i<N; i++) {
2216 ActivityInfo ainfo = results.get(i).activityInfo;
2217 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2218 && caller.getClassName().equals(ainfo.name)) {
2219 results.remove(i);
2220 break;
2221 }
2222 }
2223 }
2224
2225 // If the caller didn't request filter information,
2226 // drop them now so we don't have to
2227 // marshall/unmarshall it.
2228 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2229 N = results.size();
2230 for (int i=0; i<N; i++) {
2231 results.get(i).filter = null;
2232 }
2233 }
2234
2235 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2236 return results;
2237 }
2238
2239 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2240 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002241 ComponentName comp = intent.getComponent();
2242 if (comp != null) {
2243 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2244 ActivityInfo ai = getReceiverInfo(comp, flags);
2245 if (ai != null) {
2246 ResolveInfo ri = new ResolveInfo();
2247 ri.activityInfo = ai;
2248 list.add(ri);
2249 }
2250 return list;
2251 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002254 String pkgName = intent.getPackage();
2255 if (pkgName == null) {
2256 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2257 resolvedType, flags);
2258 }
2259 PackageParser.Package pkg = mPackages.get(pkgName);
2260 if (pkg != null) {
2261 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2262 resolvedType, flags, pkg.receivers);
2263 }
2264 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 }
2266 }
2267
2268 public ResolveInfo resolveService(Intent intent, String resolvedType,
2269 int flags) {
2270 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2271 flags);
2272 if (query != null) {
2273 if (query.size() >= 1) {
2274 // If there is more than one service with the same priority,
2275 // just arbitrarily pick the first one.
2276 return query.get(0);
2277 }
2278 }
2279 return null;
2280 }
2281
2282 public List<ResolveInfo> queryIntentServices(Intent intent,
2283 String resolvedType, int flags) {
2284 ComponentName comp = intent.getComponent();
2285 if (comp != null) {
2286 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2287 ServiceInfo si = getServiceInfo(comp, flags);
2288 if (si != null) {
2289 ResolveInfo ri = new ResolveInfo();
2290 ri.serviceInfo = si;
2291 list.add(ri);
2292 }
2293 return list;
2294 }
2295
2296 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002297 String pkgName = intent.getPackage();
2298 if (pkgName == null) {
2299 return (List<ResolveInfo>)mServices.queryIntent(intent,
2300 resolvedType, flags);
2301 }
2302 PackageParser.Package pkg = mPackages.get(pkgName);
2303 if (pkg != null) {
2304 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2305 resolvedType, flags, pkg.services);
2306 }
2307 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002308 }
2309 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002311 public List<PackageInfo> getInstalledPackages(int flags) {
2312 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2313
2314 synchronized (mPackages) {
2315 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2316 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2317 while (i.hasNext()) {
2318 final PackageSetting ps = i.next();
2319 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2320 if(psPkg != null) {
2321 finalList.add(psPkg);
2322 }
2323 }
2324 }
2325 else {
2326 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2327 while (i.hasNext()) {
2328 final PackageParser.Package p = i.next();
2329 if (p.applicationInfo != null) {
2330 PackageInfo pi = generatePackageInfo(p, flags);
2331 if(pi != null) {
2332 finalList.add(pi);
2333 }
2334 }
2335 }
2336 }
2337 }
2338 return finalList;
2339 }
2340
2341 public List<ApplicationInfo> getInstalledApplications(int flags) {
2342 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2343 synchronized(mPackages) {
2344 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2345 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2346 while (i.hasNext()) {
2347 final PackageSetting ps = i.next();
2348 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2349 if(ai != null) {
2350 finalList.add(ai);
2351 }
2352 }
2353 }
2354 else {
2355 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2356 while (i.hasNext()) {
2357 final PackageParser.Package p = i.next();
2358 if (p.applicationInfo != null) {
2359 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2360 if(ai != null) {
2361 finalList.add(ai);
2362 }
2363 }
2364 }
2365 }
2366 }
2367 return finalList;
2368 }
2369
2370 public List<ApplicationInfo> getPersistentApplications(int flags) {
2371 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2372
2373 synchronized (mPackages) {
2374 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2375 while (i.hasNext()) {
2376 PackageParser.Package p = i.next();
2377 if (p.applicationInfo != null
2378 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
2379 && (!mSafeMode || (p.applicationInfo.flags
2380 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
Jey2eebf5c2009-11-18 18:37:31 -08002381 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 }
2383 }
2384 }
2385
2386 return finalList;
2387 }
2388
2389 public ProviderInfo resolveContentProvider(String name, int flags) {
2390 synchronized (mPackages) {
2391 final PackageParser.Provider provider = mProviders.get(name);
2392 return provider != null
2393 && mSettings.isEnabledLP(provider.info, flags)
2394 && (!mSafeMode || (provider.info.applicationInfo.flags
2395 &ApplicationInfo.FLAG_SYSTEM) != 0)
2396 ? PackageParser.generateProviderInfo(provider, flags)
2397 : null;
2398 }
2399 }
2400
Fred Quintana718d8a22009-04-29 17:53:20 -07002401 /**
2402 * @deprecated
2403 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 public void querySyncProviders(List outNames, List outInfo) {
2405 synchronized (mPackages) {
2406 Iterator<Map.Entry<String, PackageParser.Provider>> i
2407 = mProviders.entrySet().iterator();
2408
2409 while (i.hasNext()) {
2410 Map.Entry<String, PackageParser.Provider> entry = i.next();
2411 PackageParser.Provider p = entry.getValue();
2412
2413 if (p.syncable
2414 && (!mSafeMode || (p.info.applicationInfo.flags
2415 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2416 outNames.add(entry.getKey());
2417 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2418 }
2419 }
2420 }
2421 }
2422
2423 public List<ProviderInfo> queryContentProviders(String processName,
2424 int uid, int flags) {
2425 ArrayList<ProviderInfo> finalList = null;
2426
2427 synchronized (mPackages) {
2428 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2429 while (i.hasNext()) {
2430 PackageParser.Provider p = i.next();
2431 if (p.info.authority != null
2432 && (processName == null ||
2433 (p.info.processName.equals(processName)
2434 && p.info.applicationInfo.uid == uid))
2435 && mSettings.isEnabledLP(p.info, flags)
2436 && (!mSafeMode || (p.info.applicationInfo.flags
2437 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2438 if (finalList == null) {
2439 finalList = new ArrayList<ProviderInfo>(3);
2440 }
2441 finalList.add(PackageParser.generateProviderInfo(p,
2442 flags));
2443 }
2444 }
2445 }
2446
2447 if (finalList != null) {
2448 Collections.sort(finalList, mProviderInitOrderSorter);
2449 }
2450
2451 return finalList;
2452 }
2453
2454 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2455 int flags) {
2456 synchronized (mPackages) {
2457 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2458 return PackageParser.generateInstrumentationInfo(i, flags);
2459 }
2460 }
2461
2462 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2463 int flags) {
2464 ArrayList<InstrumentationInfo> finalList =
2465 new ArrayList<InstrumentationInfo>();
2466
2467 synchronized (mPackages) {
2468 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2469 while (i.hasNext()) {
2470 PackageParser.Instrumentation p = i.next();
2471 if (targetPackage == null
2472 || targetPackage.equals(p.info.targetPackage)) {
2473 finalList.add(PackageParser.generateInstrumentationInfo(p,
2474 flags));
2475 }
2476 }
2477 }
2478
2479 return finalList;
2480 }
2481
2482 private void scanDirLI(File dir, int flags, int scanMode) {
2483 Log.d(TAG, "Scanning app dir " + dir);
2484
2485 String[] files = dir.list();
2486
2487 int i;
2488 for (i=0; i<files.length; i++) {
2489 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002490 if (!isPackageFilename(files[i])) {
2491 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002492 continue;
2493 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002494 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002496 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002497 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2498 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002499 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002500 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002501 file.delete();
2502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 }
2504 }
2505
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002506 private static File getSettingsProblemFile() {
2507 File dataDir = Environment.getDataDirectory();
2508 File systemDir = new File(dataDir, "system");
2509 File fname = new File(systemDir, "uiderrors.txt");
2510 return fname;
2511 }
2512
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 private static void reportSettingsProblem(int priority, String msg) {
2514 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002515 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 FileOutputStream out = new FileOutputStream(fname, true);
2517 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002518 SimpleDateFormat formatter = new SimpleDateFormat();
2519 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2520 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 pw.close();
2522 FileUtils.setPermissions(
2523 fname.toString(),
2524 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2525 -1, -1);
2526 } catch (java.io.IOException e) {
2527 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002528 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 }
2530
2531 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2532 PackageParser.Package pkg, File srcFile, int parseFlags) {
2533 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002534 if (ps != null
2535 && ps.codePath.equals(srcFile)
2536 && ps.getTimeStamp() == srcFile.lastModified()) {
2537 if (ps.signatures.mSignatures != null
2538 && ps.signatures.mSignatures.length != 0) {
2539 // Optimization: reuse the existing cached certificates
2540 // if the package appears to be unchanged.
2541 pkg.mSignatures = ps.signatures.mSignatures;
2542 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 }
Jeff Browne7600722010-04-07 18:28:23 -07002544
2545 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002546 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002547 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2548 }
2549
2550 if (!pp.collectCertificates(pkg, parseFlags)) {
2551 mLastScanError = pp.getParseError();
2552 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 }
2554 }
2555 return true;
2556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 /*
2559 * Scan a package and return the newly parsed package.
2560 * Returns null in case of errors and the error code is stored in mLastScanError
2561 */
2562 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002563 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002565 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002567 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002570 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 if (pkg == null) {
2572 mLastScanError = pp.getParseError();
2573 return null;
2574 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002575 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 PackageSetting updatedPkg;
2577 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002578 // Look to see if we already know about this package.
2579 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002580 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002581 // This package has been renamed to its original name. Let's
2582 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002583 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002584 }
2585 // If there was no original package, see one for the real package name.
2586 if (ps == null) {
2587 ps = mSettings.peekPackageLP(pkg.packageName);
2588 }
2589 // Check to see if this package could be hiding/updating a system
2590 // package. Must look for it either under the original or real
2591 // package name depending on our state.
2592 updatedPkg = mSettings.mDisabledSysPackages.get(
2593 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002594 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002595 // First check if this is a system package that may involve an update
2596 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2597 if (!ps.codePath.equals(scanFile)) {
2598 // The path has changed from what was last scanned... check the
2599 // version of the new path against what we have stored to determine
2600 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002601 if (pkg.mVersionCode < ps.versionCode) {
2602 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002603 // Ignore entry. Skip it.
2604 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2605 + "ignored: updated version " + ps.versionCode
2606 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002607 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2608 return null;
2609 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002610 // The current app on the system partion is better than
2611 // what we have updated to on the data partition; switch
2612 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002613 // At this point, its safely assumed that package installation for
2614 // apps in system partition will go through. If not there won't be a working
2615 // version of the app
2616 synchronized (mPackages) {
2617 // Just remove the loaded entries from package lists.
2618 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002619 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002620 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002621 + "reverting from " + ps.codePathString
2622 + ": new version " + pkg.mVersionCode
2623 + " better than installed " + ps.versionCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002624 InstallArgs args = new FileInstallArgs(ps.codePathString, ps.resourcePathString);
2625 args.cleanUpResourcesLI();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07002626 removeNativeBinariesLI(pkg);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002627 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 }
2630 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002631 if (updatedPkg != null) {
2632 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2633 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2634 }
2635 // Verify certificates against what was last scanned
2636 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002637 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002638 return null;
2639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640 // The apk is forward locked (not public) if its code and resources
2641 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002642 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002644 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002645 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002646
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002647 String codePath = null;
2648 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002649 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2650 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002651 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002652 } else {
2653 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002654 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002655 }
2656 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002657 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002658 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002659 codePath = pkg.mScanPath;
2660 // Set application objects path explicitly.
2661 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002663 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002664 }
2665
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002666 private static void setApplicationInfoPaths(PackageParser.Package pkg,
2667 String destCodePath, String destResPath) {
2668 pkg.mPath = pkg.mScanPath = destCodePath;
2669 pkg.applicationInfo.sourceDir = destCodePath;
2670 pkg.applicationInfo.publicSourceDir = destResPath;
2671 }
2672
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 private static String fixProcessName(String defProcessName,
2674 String processName, int uid) {
2675 if (processName == null) {
2676 return defProcessName;
2677 }
2678 return processName;
2679 }
2680
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002681 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002682 PackageParser.Package pkg) {
2683 if (pkgSetting.signatures.mSignatures != null) {
2684 // Already existing package. Make sure signatures match
2685 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2686 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002687 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002688 + " signatures do not match the previously installed version; ignoring!");
2689 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002690 return false;
2691 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002692 }
2693 // Check for shared user signatures
2694 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2695 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2696 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2697 Slog.e(TAG, "Package " + pkg.packageName
2698 + " has no signatures that match those in shared user "
2699 + pkgSetting.sharedUser.name + "; ignoring!");
2700 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2701 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002702 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 }
2704 return true;
2705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002706
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002707 public boolean performDexOpt(String packageName) {
2708 if (!mNoDexOpt) {
2709 return false;
2710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002711
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002712 PackageParser.Package p;
2713 synchronized (mPackages) {
2714 p = mPackages.get(packageName);
2715 if (p == null || p.mDidDexOpt) {
2716 return false;
2717 }
2718 }
2719 synchronized (mInstallLock) {
2720 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2721 }
2722 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002723
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002724 static final int DEX_OPT_SKIPPED = 0;
2725 static final int DEX_OPT_PERFORMED = 1;
2726 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002727
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002728 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2729 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002730 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002731 String path = pkg.mScanPath;
2732 int ret = 0;
2733 try {
2734 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002735 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002736 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 pkg.mDidDexOpt = true;
2738 performed = true;
2739 }
2740 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002741 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002742 ret = -1;
2743 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002744 Slog.w(TAG, "IOException reading apk: " + path, e);
2745 ret = -1;
2746 } catch (dalvik.system.StaleDexCacheError e) {
2747 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2748 ret = -1;
2749 } catch (Exception e) {
2750 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002751 ret = -1;
2752 }
2753 if (ret < 0) {
2754 //error from installer
2755 return DEX_OPT_FAILED;
2756 }
2757 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002758
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002759 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2760 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002761
2762 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2763 return Environment.isEncryptedFilesystemEnabled() &&
2764 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2765 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002766
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002767 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2768 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002769 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002770 + " to " + newPkg.packageName
2771 + ": old package not in system partition");
2772 return false;
2773 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002774 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002775 + " to " + newPkg.packageName
2776 + ": old package still exists");
2777 return false;
2778 }
2779 return true;
2780 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002781
2782 private File getDataPathForPackage(PackageParser.Package pkg) {
2783 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2784 File dataPath;
2785 if (useEncryptedFSDir) {
2786 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2787 } else {
2788 dataPath = new File(mAppDataDir, pkg.packageName);
2789 }
2790 return dataPath;
2791 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002792
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002793 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2794 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002795 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002796 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2797 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002798 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002799 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002800 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2801 return null;
2802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002803 mScanningPath = scanFile;
2804 if (pkg == null) {
2805 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2806 return null;
2807 }
2808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2810 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2811 }
2812
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002813 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 synchronized (mPackages) {
2815 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002816 Slog.w(TAG, "*************************************************");
2817 Slog.w(TAG, "Core android package being redefined. Skipping.");
2818 Slog.w(TAG, " file=" + mScanningPath);
2819 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002820 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2821 return null;
2822 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002823
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 // Set up information for our fall-back user intent resolution
2825 // activity.
2826 mPlatformPackage = pkg;
2827 pkg.mVersionCode = mSdkVersion;
2828 mAndroidApplication = pkg.applicationInfo;
2829 mResolveActivity.applicationInfo = mAndroidApplication;
2830 mResolveActivity.name = ResolverActivity.class.getName();
2831 mResolveActivity.packageName = mAndroidApplication.packageName;
2832 mResolveActivity.processName = mAndroidApplication.processName;
2833 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2834 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2835 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2836 mResolveActivity.exported = true;
2837 mResolveActivity.enabled = true;
2838 mResolveInfo.activityInfo = mResolveActivity;
2839 mResolveInfo.priority = 0;
2840 mResolveInfo.preferredOrder = 0;
2841 mResolveInfo.match = 0;
2842 mResolveComponentName = new ComponentName(
2843 mAndroidApplication.packageName, mResolveActivity.name);
2844 }
2845 }
2846
2847 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002848 TAG, "Scanning package " + pkg.packageName);
2849 if (mPackages.containsKey(pkg.packageName)
2850 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002851 Slog.w(TAG, "*************************************************");
2852 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002854 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002855 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2856 return null;
2857 }
2858
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002859 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002860 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2861 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 SharedUserSetting suid = null;
2864 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002865
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002866 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2867 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002868 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002869 pkg.mRealPackage = null;
2870 pkg.mAdoptPermissions = null;
2871 }
2872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 synchronized (mPackages) {
2874 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002875 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2876 if (mTmpSharedLibraries == null ||
2877 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2878 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2879 }
2880 int num = 0;
2881 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2882 for (int i=0; i<N; i++) {
2883 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002884 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002885 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002887 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2889 return null;
2890 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002891 mTmpSharedLibraries[num] = file;
2892 num++;
2893 }
2894 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2895 for (int i=0; i<N; i++) {
2896 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2897 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002898 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002899 + " desires unavailable shared library "
2900 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2901 } else {
2902 mTmpSharedLibraries[num] = file;
2903 num++;
2904 }
2905 }
2906 if (num > 0) {
2907 pkg.usesLibraryFiles = new String[num];
2908 System.arraycopy(mTmpSharedLibraries, 0,
2909 pkg.usesLibraryFiles, 0, num);
2910 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002911
Dianne Hackborn49237342009-08-27 20:08:01 -07002912 if (pkg.reqFeatures != null) {
2913 N = pkg.reqFeatures.size();
2914 for (int i=0; i<N; i++) {
2915 FeatureInfo fi = pkg.reqFeatures.get(i);
2916 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2917 // Don't care.
2918 continue;
2919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002920
Dianne Hackborn49237342009-08-27 20:08:01 -07002921 if (fi.name != null) {
2922 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002923 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002924 + " requires unavailable feature "
2925 + fi.name + "; failing!");
2926 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2927 return null;
2928 }
2929 }
2930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002931 }
2932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 if (pkg.mSharedUserId != null) {
2935 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2936 pkg.applicationInfo.flags, true);
2937 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002938 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002939 + " for shared user failed");
2940 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2941 return null;
2942 }
2943 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2944 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2945 + suid.userId + "): packages=" + suid.packages);
2946 }
2947 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002948
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002949 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002950 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002951 Log.w(TAG, "WAITING FOR DEBUGGER");
2952 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002953 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2954 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002955 }
2956 }
2957
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002958 // Check if we are renaming from an original package name.
2959 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002961 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002962 // This package may need to be renamed to a previously
2963 // installed name. Let's check on that...
2964 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002965 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002966 // This package had originally been installed as the
2967 // original name, and we have already taken care of
2968 // transitioning to the new one. Just update the new
2969 // one to continue using the old name.
2970 realName = pkg.mRealPackage;
2971 if (!pkg.packageName.equals(renamed)) {
2972 // Callers into this function may have already taken
2973 // care of renaming the package; only do it here if
2974 // it is not already done.
2975 pkg.setPackageName(renamed);
2976 }
2977
Dianne Hackbornc1552392010-03-03 16:19:01 -08002978 } else {
2979 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2980 if ((origPackage=mSettings.peekPackageLP(
2981 pkg.mOriginalPackages.get(i))) != null) {
2982 // We do have the package already installed under its
2983 // original name... should we use it?
2984 if (!verifyPackageUpdate(origPackage, pkg)) {
2985 // New package is not compatible with original.
2986 origPackage = null;
2987 continue;
2988 } else if (origPackage.sharedUser != null) {
2989 // Make sure uid is compatible between packages.
2990 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002991 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08002992 + " to " + pkg.packageName + ": old uid "
2993 + origPackage.sharedUser.name
2994 + " differs from " + pkg.mSharedUserId);
2995 origPackage = null;
2996 continue;
2997 }
2998 } else {
2999 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3000 + pkg.packageName + " to old name " + origPackage.name);
3001 }
3002 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003003 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003004 }
3005 }
3006 }
3007
3008 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003009 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003010 + " was transferred to another, but its .apk remains");
3011 }
3012
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003013 // Just create the setting, don't add it yet. For already existing packages
3014 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003015 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 destResourceFile, pkg.applicationInfo.flags, true, false);
3017 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003018 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003019 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3020 return null;
3021 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003022
3023 if (pkgSetting.origPackage != null) {
3024 // If we are first transitioning from an original package,
3025 // fix up the new package's name now. We need to do this after
3026 // looking up the package under its new name, so getPackageLP
3027 // can take care of fiddling things correctly.
3028 pkg.setPackageName(origPackage.name);
3029
3030 // File a report about this.
3031 String msg = "New package " + pkgSetting.realName
3032 + " renamed to replace old package " + pkgSetting.name;
3033 reportSettingsProblem(Log.WARN, msg);
3034
3035 // Make a note of it.
3036 mTransferedPackages.add(origPackage.name);
3037
3038 // No longer need to retain this.
3039 pkgSetting.origPackage = null;
3040 }
3041
3042 if (realName != null) {
3043 // Make a note of it.
3044 mTransferedPackages.add(pkg.packageName);
3045 }
3046
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003047 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3049 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 pkg.applicationInfo.uid = pkgSetting.userId;
3052 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003053
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003054 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003055 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 return null;
3057 }
3058 // The signature has changed, but this package is in the system
3059 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003060 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 // However... if this package is part of a shared user, but it
3062 // doesn't match the signature of the shared user, let's fail.
3063 // What this means is that you can't change the signatures
3064 // associated with an overall shared user, which doesn't seem all
3065 // that unreasonable.
3066 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003067 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3068 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3069 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3071 return null;
3072 }
3073 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003074 // File a report about this.
3075 String msg = "System package " + pkg.packageName
3076 + " signature changed; retaining data.";
3077 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003079
The Android Open Source Project10592532009-03-18 17:39:46 -07003080 // Verify that this new package doesn't have any content providers
3081 // that conflict with existing packages. Only do this if the
3082 // package isn't already installed, since we don't want to break
3083 // things that are installed.
3084 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3085 int N = pkg.providers.size();
3086 int i;
3087 for (i=0; i<N; i++) {
3088 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003089 if (p.info.authority != null) {
3090 String names[] = p.info.authority.split(";");
3091 for (int j = 0; j < names.length; j++) {
3092 if (mProviders.containsKey(names[j])) {
3093 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003094 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003095 " (in package " + pkg.applicationInfo.packageName +
3096 ") is already used by "
3097 + ((other != null && other.getComponentName() != null)
3098 ? other.getComponentName().getPackageName() : "?"));
3099 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3100 return null;
3101 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003102 }
3103 }
3104 }
3105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 }
3107
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003108 final String pkgName = pkg.packageName;
3109
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003110 if (pkg.mAdoptPermissions != null) {
3111 // This package wants to adopt ownership of permissions from
3112 // another package.
3113 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3114 String origName = pkg.mAdoptPermissions.get(i);
3115 PackageSetting orig = mSettings.peekPackageLP(origName);
3116 if (orig != null) {
3117 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003118 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003119 + origName + " to " + pkg.packageName);
3120 mSettings.transferPermissions(origName, pkg.packageName);
3121 }
3122 }
3123 }
3124 }
3125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 long scanFileTime = scanFile.lastModified();
3127 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3128 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3129 pkg.applicationInfo.processName = fixProcessName(
3130 pkg.applicationInfo.packageName,
3131 pkg.applicationInfo.processName,
3132 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133
3134 File dataPath;
3135 if (mPlatformPackage == pkg) {
3136 // The system package is special.
3137 dataPath = new File (Environment.getDataDirectory(), "system");
3138 pkg.applicationInfo.dataDir = dataPath.getPath();
3139 } else {
3140 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003141 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003142 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003143
3144 boolean uidError = false;
3145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 if (dataPath.exists()) {
3147 mOutPermissions[1] = 0;
3148 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
3149 if (mOutPermissions[1] == pkg.applicationInfo.uid
3150 || !Process.supportsProcesses()) {
3151 pkg.applicationInfo.dataDir = dataPath.getPath();
3152 } else {
3153 boolean recovered = false;
3154 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3155 // If this is a system app, we can at least delete its
3156 // current data so the application will still work.
3157 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003158 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003159 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 // Old data gone!
3161 String msg = "System package " + pkg.packageName
3162 + " has changed from uid: "
3163 + mOutPermissions[1] + " to "
3164 + pkg.applicationInfo.uid + "; old data erased";
3165 reportSettingsProblem(Log.WARN, msg);
3166 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003167
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003169 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003170 pkg.applicationInfo.uid);
3171 if (ret == -1) {
3172 // Ack should not happen!
3173 msg = "System package " + pkg.packageName
3174 + " could not have data directory re-created after delete.";
3175 reportSettingsProblem(Log.WARN, msg);
3176 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3177 return null;
3178 }
3179 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 if (!recovered) {
3182 mHasSystemUidErrors = true;
3183 }
3184 }
3185 if (!recovered) {
3186 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3187 + pkg.applicationInfo.uid + "/fs_"
3188 + mOutPermissions[1];
3189 String msg = "Package " + pkg.packageName
3190 + " has mismatched uid: "
3191 + mOutPermissions[1] + " on disk, "
3192 + pkg.applicationInfo.uid + " in settings";
3193 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003194 mSettings.mReadMessages.append(msg);
3195 mSettings.mReadMessages.append('\n');
3196 uidError = true;
3197 if (!pkgSetting.uidError) {
3198 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 }
3201 }
3202 }
3203 pkg.applicationInfo.dataDir = dataPath.getPath();
3204 } else {
3205 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3206 Log.v(TAG, "Want this data dir: " + dataPath);
3207 //invoke installer to do the actual installation
3208 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003209 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 pkg.applicationInfo.uid);
3211 if(ret < 0) {
3212 // Error from installer
3213 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3214 return null;
3215 }
3216 } else {
3217 dataPath.mkdirs();
3218 if (dataPath.exists()) {
3219 FileUtils.setPermissions(
3220 dataPath.toString(),
3221 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3222 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3223 }
3224 }
3225 if (dataPath.exists()) {
3226 pkg.applicationInfo.dataDir = dataPath.getPath();
3227 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003228 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229 pkg.applicationInfo.dataDir = null;
3230 }
3231 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003232
3233 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003234 }
3235
3236 // Perform shared library installation and dex validation and
3237 // optimization, if this is not a system app.
3238 if (mInstaller != null) {
3239 String path = scanFile.getPath();
3240 if (scanFileNewer) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003241 // Note: We don't want to unpack the native binaries for
3242 // system applications, unless they have been updated
3243 // (the binaries are already under /system/lib).
3244 //
3245 // In other words, we're going to unpack the binaries
3246 // only for non-system apps and system app upgrades.
3247 //
3248 int flags = pkg.applicationInfo.flags;
3249 if ((flags & ApplicationInfo.FLAG_SYSTEM) == 0 ||
3250 (flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
3251 Log.i(TAG, path + " changed; unpacking");
3252 int err = cachePackageSharedLibsLI(pkg, scanFile);
3253 if (err != PackageManager.INSTALL_SUCCEEDED) {
3254 mLastScanError = err;
3255 return null;
3256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 }
3258 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003259 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003260
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003261 if ((scanMode&SCAN_NO_DEX) == 0) {
3262 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3264 return null;
3265 }
3266 }
3267 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003268
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 if (mFactoryTest && pkg.requestedPermissions.contains(
3270 android.Manifest.permission.FACTORY_TEST)) {
3271 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3272 }
3273
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003274 // Request the ActivityManager to kill the process(only for existing packages)
3275 // so that we do not end up in a confused state while the user is still using the older
3276 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003277 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003278 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003279 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003280 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003283 // We don't expect installation to fail beyond this point,
3284 if ((scanMode&SCAN_MONITOR) != 0) {
3285 mAppDirs.put(pkg.mPath, pkg);
3286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003288 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003290 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003291 // Make sure we don't accidentally delete its data.
3292 mSettings.mPackagesToBeCleaned.remove(pkgName);
3293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 int N = pkg.providers.size();
3295 StringBuilder r = null;
3296 int i;
3297 for (i=0; i<N; i++) {
3298 PackageParser.Provider p = pkg.providers.get(i);
3299 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3300 p.info.processName, pkg.applicationInfo.uid);
3301 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3302 p.info.name), p);
3303 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003304 if (p.info.authority != null) {
3305 String names[] = p.info.authority.split(";");
3306 p.info.authority = null;
3307 for (int j = 0; j < names.length; j++) {
3308 if (j == 1 && p.syncable) {
3309 // We only want the first authority for a provider to possibly be
3310 // syncable, so if we already added this provider using a different
3311 // authority clear the syncable flag. We copy the provider before
3312 // changing it because the mProviders object contains a reference
3313 // to a provider that we don't want to change.
3314 // Only do this for the second authority since the resulting provider
3315 // object can be the same for all future authorities for this provider.
3316 p = new PackageParser.Provider(p);
3317 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003319 if (!mProviders.containsKey(names[j])) {
3320 mProviders.put(names[j], p);
3321 if (p.info.authority == null) {
3322 p.info.authority = names[j];
3323 } else {
3324 p.info.authority = p.info.authority + ";" + names[j];
3325 }
3326 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3327 Log.d(TAG, "Registered content provider: " + names[j] +
3328 ", className = " + p.info.name +
3329 ", isSyncable = " + p.info.isSyncable);
3330 } else {
3331 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003332 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003333 " (in package " + pkg.applicationInfo.packageName +
3334 "): name already used by "
3335 + ((other != null && other.getComponentName() != null)
3336 ? other.getComponentName().getPackageName() : "?"));
3337 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 }
3339 }
3340 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3341 if (r == null) {
3342 r = new StringBuilder(256);
3343 } else {
3344 r.append(' ');
3345 }
3346 r.append(p.info.name);
3347 }
3348 }
3349 if (r != null) {
3350 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3351 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003352
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 N = pkg.services.size();
3354 r = null;
3355 for (i=0; i<N; i++) {
3356 PackageParser.Service s = pkg.services.get(i);
3357 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3358 s.info.processName, pkg.applicationInfo.uid);
3359 mServices.addService(s);
3360 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3361 if (r == null) {
3362 r = new StringBuilder(256);
3363 } else {
3364 r.append(' ');
3365 }
3366 r.append(s.info.name);
3367 }
3368 }
3369 if (r != null) {
3370 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3371 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 N = pkg.receivers.size();
3374 r = null;
3375 for (i=0; i<N; i++) {
3376 PackageParser.Activity a = pkg.receivers.get(i);
3377 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3378 a.info.processName, pkg.applicationInfo.uid);
3379 mReceivers.addActivity(a, "receiver");
3380 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3381 if (r == null) {
3382 r = new StringBuilder(256);
3383 } else {
3384 r.append(' ');
3385 }
3386 r.append(a.info.name);
3387 }
3388 }
3389 if (r != null) {
3390 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3391 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 N = pkg.activities.size();
3394 r = null;
3395 for (i=0; i<N; i++) {
3396 PackageParser.Activity a = pkg.activities.get(i);
3397 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3398 a.info.processName, pkg.applicationInfo.uid);
3399 mActivities.addActivity(a, "activity");
3400 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3401 if (r == null) {
3402 r = new StringBuilder(256);
3403 } else {
3404 r.append(' ');
3405 }
3406 r.append(a.info.name);
3407 }
3408 }
3409 if (r != null) {
3410 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3411 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 N = pkg.permissionGroups.size();
3414 r = null;
3415 for (i=0; i<N; i++) {
3416 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3417 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3418 if (cur == null) {
3419 mPermissionGroups.put(pg.info.name, pg);
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(pg.info.name);
3427 }
3428 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003429 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 + pg.info.packageName + " ignored: original from "
3431 + cur.info.packageName);
3432 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3433 if (r == null) {
3434 r = new StringBuilder(256);
3435 } else {
3436 r.append(' ');
3437 }
3438 r.append("DUP:");
3439 r.append(pg.info.name);
3440 }
3441 }
3442 }
3443 if (r != null) {
3444 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 N = pkg.permissions.size();
3448 r = null;
3449 for (i=0; i<N; i++) {
3450 PackageParser.Permission p = pkg.permissions.get(i);
3451 HashMap<String, BasePermission> permissionMap =
3452 p.tree ? mSettings.mPermissionTrees
3453 : mSettings.mPermissions;
3454 p.group = mPermissionGroups.get(p.info.group);
3455 if (p.info.group == null || p.group != null) {
3456 BasePermission bp = permissionMap.get(p.info.name);
3457 if (bp == null) {
3458 bp = new BasePermission(p.info.name, p.info.packageName,
3459 BasePermission.TYPE_NORMAL);
3460 permissionMap.put(p.info.name, bp);
3461 }
3462 if (bp.perm == null) {
3463 if (bp.sourcePackage == null
3464 || bp.sourcePackage.equals(p.info.packageName)) {
3465 BasePermission tree = findPermissionTreeLP(p.info.name);
3466 if (tree == null
3467 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003468 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 bp.perm = p;
3470 bp.uid = pkg.applicationInfo.uid;
3471 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3472 if (r == null) {
3473 r = new StringBuilder(256);
3474 } else {
3475 r.append(' ');
3476 }
3477 r.append(p.info.name);
3478 }
3479 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003480 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 + p.info.packageName + " ignored: base tree "
3482 + tree.name + " is from package "
3483 + tree.sourcePackage);
3484 }
3485 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003486 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 + p.info.packageName + " ignored: original from "
3488 + bp.sourcePackage);
3489 }
3490 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3491 if (r == null) {
3492 r = new StringBuilder(256);
3493 } else {
3494 r.append(' ');
3495 }
3496 r.append("DUP:");
3497 r.append(p.info.name);
3498 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003499 if (bp.perm == p) {
3500 bp.protectionLevel = p.info.protectionLevel;
3501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003503 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 + p.info.packageName + " ignored: no group "
3505 + p.group);
3506 }
3507 }
3508 if (r != null) {
3509 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3510 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003512 N = pkg.instrumentation.size();
3513 r = null;
3514 for (i=0; i<N; i++) {
3515 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3516 a.info.packageName = pkg.applicationInfo.packageName;
3517 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3518 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3519 a.info.dataDir = pkg.applicationInfo.dataDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003520 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003521 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3522 if (r == null) {
3523 r = new StringBuilder(256);
3524 } else {
3525 r.append(' ');
3526 }
3527 r.append(a.info.name);
3528 }
3529 }
3530 if (r != null) {
3531 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3532 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003533
Dianne Hackborn854060af2009-07-09 18:14:31 -07003534 if (pkg.protectedBroadcasts != null) {
3535 N = pkg.protectedBroadcasts.size();
3536 for (i=0; i<N; i++) {
3537 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3538 }
3539 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 pkgSetting.setTimeStamp(scanFileTime);
3542 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 return pkg;
3545 }
3546
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003547 private void killApplication(String pkgName, int uid) {
3548 // Request the ActivityManager to kill the process(only for existing packages)
3549 // so that we do not end up in a confused state while the user is still using the older
3550 // version of the application while the new one gets installed.
3551 IActivityManager am = ActivityManagerNative.getDefault();
3552 if (am != null) {
3553 try {
3554 am.killApplicationWithUid(pkgName, uid);
3555 } catch (RemoteException e) {
3556 }
3557 }
3558 }
3559
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003560 // The following constants are returned by cachePackageSharedLibsForAbiLI
3561 // to indicate if native shared libraries were found in the package.
3562 // Values are:
3563 // PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES => native libraries found and installed
3564 // PACKAGE_INSTALL_NATIVE_NO_LIBRARIES => no native libraries in package
3565 // PACKAGE_INSTALL_NATIVE_ABI_MISMATCH => native libraries for another ABI found
3566 // in package (and not installed)
3567 //
3568 private static final int PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES = 0;
3569 private static final int PACKAGE_INSTALL_NATIVE_NO_LIBRARIES = 1;
3570 private static final int PACKAGE_INSTALL_NATIVE_ABI_MISMATCH = 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003572 // Return the path of the directory that will contain the native binaries
3573 // of a given installed package. This is relative to the data path.
3574 //
3575 private static File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3576 return new File(pkg.applicationInfo.dataDir + "/lib");
3577 }
3578
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003579 // Find all files of the form lib/<cpuAbi>/lib<name>.so in the .apk
3580 // and automatically copy them to /data/data/<appname>/lib if present.
3581 //
3582 // NOTE: this method may throw an IOException if the library cannot
3583 // be copied to its final destination, e.g. if there isn't enough
3584 // room left on the data partition, or a ZipException if the package
3585 // file is malformed.
3586 //
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003587 private int cachePackageSharedLibsForAbiLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003588 File scanFile, String cpuAbi) throws IOException, ZipException {
3589 File sharedLibraryDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003590 final String apkLib = "lib/";
3591 final int apkLibLen = apkLib.length();
3592 final int cpuAbiLen = cpuAbi.length();
3593 final String libPrefix = "lib";
3594 final int libPrefixLen = libPrefix.length();
3595 final String libSuffix = ".so";
3596 final int libSuffixLen = libSuffix.length();
3597 boolean hasNativeLibraries = false;
3598 boolean installedNativeLibraries = false;
3599
3600 // the minimum length of a valid native shared library of the form
3601 // lib/<something>/lib<name>.so.
3602 final int minEntryLen = apkLibLen + 2 + libPrefixLen + 1 + libSuffixLen;
3603
3604 ZipFile zipFile = new ZipFile(scanFile);
3605 Enumeration<ZipEntry> entries =
3606 (Enumeration<ZipEntry>) zipFile.entries();
3607
3608 while (entries.hasMoreElements()) {
3609 ZipEntry entry = entries.nextElement();
3610 // skip directories
3611 if (entry.isDirectory()) {
3612 continue;
3613 }
3614 String entryName = entry.getName();
3615
3616 // check that the entry looks like lib/<something>/lib<name>.so
3617 // here, but don't check the ABI just yet.
3618 //
3619 // - must be sufficiently long
3620 // - must end with libSuffix, i.e. ".so"
3621 // - must start with apkLib, i.e. "lib/"
3622 if (entryName.length() < minEntryLen ||
3623 !entryName.endsWith(libSuffix) ||
3624 !entryName.startsWith(apkLib) ) {
3625 continue;
3626 }
3627
3628 // file name must start with libPrefix, i.e. "lib"
3629 int lastSlash = entryName.lastIndexOf('/');
3630
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003631 if (lastSlash < 0 ||
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003632 !entryName.regionMatches(lastSlash+1, libPrefix, 0, libPrefixLen) ) {
3633 continue;
3634 }
3635
3636 hasNativeLibraries = true;
3637
3638 // check the cpuAbi now, between lib/ and /lib<name>.so
3639 //
3640 if (lastSlash != apkLibLen + cpuAbiLen ||
3641 !entryName.regionMatches(apkLibLen, cpuAbi, 0, cpuAbiLen) )
3642 continue;
3643
3644 // extract the library file name, ensure it doesn't contain
3645 // weird characters. we're guaranteed here that it doesn't contain
3646 // a directory separator though.
3647 String libFileName = entryName.substring(lastSlash+1);
3648 if (!FileUtils.isFilenameSafe(new File(libFileName))) {
3649 continue;
3650 }
3651
3652 installedNativeLibraries = true;
3653
David 'Digit' Turner63909292010-06-03 14:37:42 -07003654 // Always extract the shared library
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003655 String sharedLibraryFilePath = sharedLibraryDir.getPath() +
3656 File.separator + libFileName;
3657 File sharedLibraryFile = new File(sharedLibraryFilePath);
David 'Digit' Turner63909292010-06-03 14:37:42 -07003658
3659 if (Config.LOGD) {
3660 Log.d(TAG, "Caching shared lib " + entry.getName());
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003661 }
David 'Digit' Turner63909292010-06-03 14:37:42 -07003662 if (mInstaller == null) {
3663 sharedLibraryDir.mkdir();
3664 }
3665 cacheNativeBinaryLI(pkg, zipFile, entry, sharedLibraryDir,
3666 sharedLibraryFile);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003667 }
3668 if (!hasNativeLibraries)
3669 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3670
3671 if (!installedNativeLibraries)
3672 return PACKAGE_INSTALL_NATIVE_ABI_MISMATCH;
3673
3674 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3675 }
3676
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003677 // Find the gdbserver executable program in a package at
3678 // lib/<cpuAbi>/gdbserver and copy it to /data/data/<name>/lib/gdbserver
3679 //
3680 // Returns PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES on success,
3681 // or PACKAGE_INSTALL_NATIVE_NO_LIBRARIES otherwise.
3682 //
3683 private int cachePackageGdbServerLI(PackageParser.Package pkg,
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003684 File scanFile, String cpuAbi) throws IOException, ZipException {
3685 File installGdbServerDir = getNativeBinaryDirForPackage(pkg);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003686 final String GDBSERVER = "gdbserver";
3687 final String apkGdbServerPath = "lib/" + cpuAbi + "/" + GDBSERVER;
3688
3689 ZipFile zipFile = new ZipFile(scanFile);
3690 Enumeration<ZipEntry> entries =
3691 (Enumeration<ZipEntry>) zipFile.entries();
3692
3693 while (entries.hasMoreElements()) {
3694 ZipEntry entry = entries.nextElement();
3695 // skip directories
3696 if (entry.isDirectory()) {
3697 continue;
3698 }
3699 String entryName = entry.getName();
3700
3701 if (!entryName.equals(apkGdbServerPath)) {
3702 continue;
3703 }
3704
3705 String installGdbServerPath = installGdbServerDir.getPath() +
3706 "/" + GDBSERVER;
3707 File installGdbServerFile = new File(installGdbServerPath);
David 'Digit' Turner63909292010-06-03 14:37:42 -07003708
3709 if (Config.LOGD) {
3710 Log.d(TAG, "Caching gdbserver " + entry.getName());
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003711 }
David 'Digit' Turner63909292010-06-03 14:37:42 -07003712 if (mInstaller == null) {
3713 installGdbServerDir.mkdir();
3714 }
3715 cacheNativeBinaryLI(pkg, zipFile, entry, installGdbServerDir,
3716 installGdbServerFile);
3717
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003718 return PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES;
3719 }
3720 return PACKAGE_INSTALL_NATIVE_NO_LIBRARIES;
3721 }
3722
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003723 // extract shared libraries stored in the APK as lib/<cpuAbi>/lib<name>.so
3724 // and copy them to /data/data/<appname>/lib.
3725 //
3726 // This function will first try the main CPU ABI defined by Build.CPU_ABI
3727 // (which corresponds to ro.product.cpu.abi), and also try an alternate
3728 // one if ro.product.cpu.abi2 is defined.
3729 //
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003730 private int cachePackageSharedLibsLI(PackageParser.Package pkg, File scanFile) {
David 'Digit' Turner63909292010-06-03 14:37:42 -07003731 // Remove all native binaries from a directory. This is used when upgrading
3732 // a package: in case the new .apk doesn't contain a native binary that was
3733 // in the old one (and thus installed), we need to remove it from
3734 // /data/data/<appname>/lib
3735 //
3736 // The simplest way to do that is to remove all files in this directory,
3737 // since it is owned by "system", applications are not supposed to write
3738 // anything there.
3739 removeNativeBinariesLI(pkg);
3740
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003741 String cpuAbi = Build.CPU_ABI;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003742 try {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003743 int result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003744
3745 // some architectures are capable of supporting several CPU ABIs
3746 // for example, 'armeabi-v7a' also supports 'armeabi' native code
3747 // this is indicated by the definition of the ro.product.cpu.abi2
3748 // system property.
3749 //
3750 // only scan the package twice in case of ABI mismatch
3751 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003752 final String cpuAbi2 = SystemProperties.get("ro.product.cpu.abi2",null);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003753 if (cpuAbi2 != null) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003754 result = cachePackageSharedLibsForAbiLI(pkg, scanFile, cpuAbi2);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003756
3757 if (result == PACKAGE_INSTALL_NATIVE_ABI_MISMATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003758 Slog.w(TAG,"Native ABI mismatch from package file");
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003759 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 }
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003761
3762 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3763 cpuAbi = cpuAbi2;
3764 }
3765 }
3766
3767 // for debuggable packages, also extract gdbserver from lib/<abi>
3768 // into /data/data/<appname>/lib too.
3769 if (result == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES &&
3770 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003771 int result2 = cachePackageGdbServerLI(pkg, scanFile, cpuAbi);
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003772 if (result2 == PACKAGE_INSTALL_NATIVE_FOUND_LIBRARIES) {
3773 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_NATIVE_DEBUGGABLE;
3774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 }
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003776 } catch (ZipException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003777 Slog.w(TAG, "Failed to extract data from package file", e);
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -08003778 return PackageManager.INSTALL_FAILED_INVALID_APK;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003780 Slog.w(TAG, "Failed to cache package shared libs", e);
Dianne Hackbornb1811182009-05-21 15:45:42 -07003781 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 }
Dianne Hackbornb1811182009-05-21 15:45:42 -07003783 return PackageManager.INSTALL_SUCCEEDED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 }
3785
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003786 private void cacheNativeBinaryLI(PackageParser.Package pkg,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 ZipFile zipFile, ZipEntry entry,
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003788 File binaryDir,
3789 File binaryFile) throws IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 InputStream inputStream = zipFile.getInputStream(entry);
3791 try {
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003792 File tempFile = File.createTempFile("tmp", "tmp", binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 String tempFilePath = tempFile.getPath();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003794 // XXX package manager can't change owner, so the executable files for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 // now need to be left as world readable and owned by the system.
3796 if (! FileUtils.copyToFile(inputStream, tempFile) ||
3797 ! tempFile.setLastModified(entry.getTime()) ||
3798 FileUtils.setPermissions(tempFilePath,
3799 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003800 |FileUtils.S_IXUSR|FileUtils.S_IXGRP|FileUtils.S_IXOTH
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 |FileUtils.S_IROTH, -1, -1) != 0 ||
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003802 ! tempFile.renameTo(binaryFile)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003803 // Failed to properly write file.
3804 tempFile.delete();
David 'Digit' Turner1edab2b2010-01-21 15:15:23 -08003805 throw new IOException("Couldn't create cached binary "
3806 + binaryFile + " in " + binaryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 }
3808 } finally {
3809 inputStream.close();
3810 }
3811 }
3812
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003813 // Remove the native binaries of a given package. This simply
3814 // gets rid of the files in the 'lib' sub-directory.
3815 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3816 File binaryDir = getNativeBinaryDirForPackage(pkg);
3817
3818 if (DEBUG_NATIVE) {
3819 Slog.w(TAG,"Deleting native binaries from: " + binaryDir.getPath());
3820 }
3821
3822 // Just remove any file in the directory. Since the directory
3823 // is owned by the 'system' UID, the application is not supposed
3824 // to have written anything there.
3825 //
3826 if (binaryDir.exists()) {
3827 File[] binaries = binaryDir.listFiles();
3828 if (binaries != null) {
3829 for (int nn=0; nn < binaries.length; nn++) {
3830 if (DEBUG_NATIVE) {
3831 Slog.d(TAG," Deleting " + binaries[nn].getName());
3832 }
3833 if (!binaries[nn].delete()) {
3834 Slog.w(TAG,"Could not delete native binary: " +
3835 binaries[nn].getPath());
3836 }
3837 }
3838 }
3839 // Do not delete 'lib' directory itself, or this will prevent
3840 // installation of future updates.
3841 }
3842 }
3843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003844 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3845 if (chatty && Config.LOGD) Log.d(
3846 TAG, "Removing package " + pkg.applicationInfo.packageName );
3847
3848 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 mPackages.remove(pkg.applicationInfo.packageName);
3852 if (pkg.mPath != null) {
3853 mAppDirs.remove(pkg.mPath);
3854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003856 PackageSetting ps = (PackageSetting)pkg.mExtras;
3857 if (ps != null && ps.sharedUser != null) {
3858 // XXX don't do this until the data is removed.
3859 if (false) {
3860 ps.sharedUser.packages.remove(ps);
3861 if (ps.sharedUser.packages.size() == 0) {
3862 // Remove.
3863 }
3864 }
3865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 int N = pkg.providers.size();
3868 StringBuilder r = null;
3869 int i;
3870 for (i=0; i<N; i++) {
3871 PackageParser.Provider p = pkg.providers.get(i);
3872 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3873 p.info.name));
3874 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003876 /* The is another ContentProvider with this authority when
3877 * this app was installed so this authority is null,
3878 * Ignore it as we don't have to unregister the provider.
3879 */
3880 continue;
3881 }
3882 String names[] = p.info.authority.split(";");
3883 for (int j = 0; j < names.length; j++) {
3884 if (mProviders.get(names[j]) == p) {
3885 mProviders.remove(names[j]);
3886 if (chatty && Config.LOGD) Log.d(
3887 TAG, "Unregistered content provider: " + names[j] +
3888 ", className = " + p.info.name +
3889 ", isSyncable = " + p.info.isSyncable);
3890 }
3891 }
3892 if (chatty) {
3893 if (r == null) {
3894 r = new StringBuilder(256);
3895 } else {
3896 r.append(' ');
3897 }
3898 r.append(p.info.name);
3899 }
3900 }
3901 if (r != null) {
3902 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3903 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 N = pkg.services.size();
3906 r = null;
3907 for (i=0; i<N; i++) {
3908 PackageParser.Service s = pkg.services.get(i);
3909 mServices.removeService(s);
3910 if (chatty) {
3911 if (r == null) {
3912 r = new StringBuilder(256);
3913 } else {
3914 r.append(' ');
3915 }
3916 r.append(s.info.name);
3917 }
3918 }
3919 if (r != null) {
3920 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3921 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923 N = pkg.receivers.size();
3924 r = null;
3925 for (i=0; i<N; i++) {
3926 PackageParser.Activity a = pkg.receivers.get(i);
3927 mReceivers.removeActivity(a, "receiver");
3928 if (chatty) {
3929 if (r == null) {
3930 r = new StringBuilder(256);
3931 } else {
3932 r.append(' ');
3933 }
3934 r.append(a.info.name);
3935 }
3936 }
3937 if (r != null) {
3938 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3939 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003941 N = pkg.activities.size();
3942 r = null;
3943 for (i=0; i<N; i++) {
3944 PackageParser.Activity a = pkg.activities.get(i);
3945 mActivities.removeActivity(a, "activity");
3946 if (chatty) {
3947 if (r == null) {
3948 r = new StringBuilder(256);
3949 } else {
3950 r.append(' ');
3951 }
3952 r.append(a.info.name);
3953 }
3954 }
3955 if (r != null) {
3956 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3957 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003958
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 N = pkg.permissions.size();
3960 r = null;
3961 for (i=0; i<N; i++) {
3962 PackageParser.Permission p = pkg.permissions.get(i);
3963 boolean tree = false;
3964 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3965 if (bp == null) {
3966 tree = true;
3967 bp = mSettings.mPermissionTrees.get(p.info.name);
3968 }
3969 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003970 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003971 if (chatty) {
3972 if (r == null) {
3973 r = new StringBuilder(256);
3974 } else {
3975 r.append(' ');
3976 }
3977 r.append(p.info.name);
3978 }
3979 }
3980 }
3981 if (r != null) {
3982 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3983 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 N = pkg.instrumentation.size();
3986 r = null;
3987 for (i=0; i<N; i++) {
3988 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003989 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 if (chatty) {
3991 if (r == null) {
3992 r = new StringBuilder(256);
3993 } else {
3994 r.append(' ');
3995 }
3996 r.append(a.info.name);
3997 }
3998 }
3999 if (r != null) {
4000 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
4001 }
4002 }
4003 }
4004
4005 private static final boolean isPackageFilename(String name) {
4006 return name != null && name.endsWith(".apk");
4007 }
4008
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004009 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
4010 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
4011 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
4012 return true;
4013 }
4014 }
4015 return false;
4016 }
4017
4018 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004019 PackageParser.Package pkgInfo, boolean grantPermissions,
4020 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004021 // Make sure there are no dangling permission trees.
4022 Iterator<BasePermission> it = mSettings.mPermissionTrees
4023 .values().iterator();
4024 while (it.hasNext()) {
4025 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004026 if (bp.packageSetting == null) {
4027 // We may not yet have parsed the package, so just see if
4028 // we still know about its settings.
4029 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4030 }
4031 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004032 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 + " from package " + bp.sourcePackage);
4034 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004035 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4036 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4037 Slog.i(TAG, "Removing old permission tree: " + bp.name
4038 + " from package " + bp.sourcePackage);
4039 grantPermissions = true;
4040 it.remove();
4041 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004042 }
4043 }
4044
4045 // Make sure all dynamic permissions have been assigned to a package,
4046 // and make sure there are no dangling permissions.
4047 it = mSettings.mPermissions.values().iterator();
4048 while (it.hasNext()) {
4049 BasePermission bp = it.next();
4050 if (bp.type == BasePermission.TYPE_DYNAMIC) {
4051 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
4052 + bp.name + " pkg=" + bp.sourcePackage
4053 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004054 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 BasePermission tree = findPermissionTreeLP(bp.name);
4056 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004057 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 bp.perm = new PackageParser.Permission(tree.perm.owner,
4059 new PermissionInfo(bp.pendingInfo));
4060 bp.perm.info.packageName = tree.perm.info.packageName;
4061 bp.perm.info.name = bp.name;
4062 bp.uid = tree.uid;
4063 }
4064 }
4065 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004066 if (bp.packageSetting == null) {
4067 // We may not yet have parsed the package, so just see if
4068 // we still know about its settings.
4069 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
4070 }
4071 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004072 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 + " from package " + bp.sourcePackage);
4074 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004075 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
4076 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
4077 Slog.i(TAG, "Removing old permission: " + bp.name
4078 + " from package " + bp.sourcePackage);
4079 grantPermissions = true;
4080 it.remove();
4081 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 }
4083 }
4084
4085 // Now update the permissions for all packages, in particular
4086 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004087 if (grantPermissions) {
4088 for (PackageParser.Package pkg : mPackages.values()) {
4089 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004090 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004091 }
4092 }
4093 }
4094
4095 if (pkgInfo != null) {
4096 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004097 }
4098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004100 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
4101 final PackageSetting ps = (PackageSetting)pkg.mExtras;
4102 if (ps == null) {
4103 return;
4104 }
4105 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004106 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004107
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 if (replace) {
4109 ps.permissionsFixed = false;
4110 if (gp == ps) {
4111 gp.grantedPermissions.clear();
4112 gp.gids = mGlobalGids;
4113 }
4114 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004116 if (gp.gids == null) {
4117 gp.gids = mGlobalGids;
4118 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 final int N = pkg.requestedPermissions.size();
4121 for (int i=0; i<N; i++) {
4122 String name = pkg.requestedPermissions.get(i);
4123 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004124 if (false) {
4125 if (gp != ps) {
4126 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004127 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 }
4129 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004130 if (bp != null && bp.packageSetting != null) {
4131 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004132 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004133 boolean allowedSig = false;
4134 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
4135 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004136 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07004137 } else if (bp.packageSetting == null) {
4138 // This permission is invalid; skip it.
4139 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004140 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
4141 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
4142 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07004144 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004146 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004147 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
4148 // For updated system applications, the signatureOrSystem permission
4149 // is granted only if it had been defined by the original application.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004150 if ((pkg.applicationInfo.flags
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004151 & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) {
4152 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
4153 if(sysPs.grantedPermissions.contains(perm)) {
4154 allowed = true;
4155 } else {
4156 allowed = false;
4157 }
4158 } else {
4159 allowed = true;
4160 }
4161 }
4162 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004163 if (allowed) {
4164 allowedSig = true;
4165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 } else {
4167 allowed = false;
4168 }
4169 if (false) {
4170 if (gp != ps) {
4171 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
4172 }
4173 }
4174 if (allowed) {
4175 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
4176 && ps.permissionsFixed) {
4177 // If this is an existing, non-system package, then
4178 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07004179 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07004181 // Except... if this is a permission that was added
4182 // to the platform (note: need to only do this when
4183 // updating the platform).
4184 final int NP = PackageParser.NEW_PERMISSIONS.length;
4185 for (int ip=0; ip<NP; ip++) {
4186 final PackageParser.NewPermissionInfo npi
4187 = PackageParser.NEW_PERMISSIONS[ip];
4188 if (npi.name.equals(perm)
4189 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
4190 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07004191 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07004192 + pkg.packageName);
4193 break;
4194 }
4195 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 }
4197 }
4198 if (allowed) {
4199 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004200 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004201 gp.grantedPermissions.add(perm);
4202 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004203 } else if (!ps.haveGids) {
4204 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004205 }
4206 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004207 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 + " to package " + pkg.packageName
4209 + " because it was previously installed without");
4210 }
4211 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004212 if (gp.grantedPermissions.remove(perm)) {
4213 changedPermission = true;
4214 gp.gids = removeInts(gp.gids, bp.gids);
4215 Slog.i(TAG, "Un-granting permission " + perm
4216 + " from package " + pkg.packageName
4217 + " (protectionLevel=" + bp.protectionLevel
4218 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4219 + ")");
4220 } else {
4221 Slog.w(TAG, "Not granting permission " + perm
4222 + " to package " + pkg.packageName
4223 + " (protectionLevel=" + bp.protectionLevel
4224 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4225 + ")");
4226 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 }
4228 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004229 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 + " in package " + pkg.packageName);
4231 }
4232 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004233
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004234 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004235 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4236 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 // This is the first that we have heard about this package, so the
4238 // permissions we have now selected are fixed until explicitly
4239 // changed.
4240 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004241 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004242 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 private final class ActivityIntentResolver
4246 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004247 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004248 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004249 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004250 }
4251
Mihai Preda074edef2009-05-18 17:13:31 +02004252 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004253 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004254 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004255 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4256 }
4257
Mihai Predaeae850c2009-05-13 10:13:48 +02004258 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4259 ArrayList<PackageParser.Activity> packageActivities) {
4260 if (packageActivities == null) {
4261 return null;
4262 }
4263 mFlags = flags;
4264 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4265 int N = packageActivities.size();
4266 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4267 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004268
4269 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004270 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004271 intentFilters = packageActivities.get(i).intents;
4272 if (intentFilters != null && intentFilters.size() > 0) {
4273 listCut.add(intentFilters);
4274 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004275 }
4276 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4277 }
4278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004279 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004280 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004281 if (SHOW_INFO || Config.LOGV) Log.v(
4282 TAG, " " + type + " " +
4283 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4284 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4285 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004286 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004287 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4288 if (SHOW_INFO || Config.LOGV) {
4289 Log.v(TAG, " IntentFilter:");
4290 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4291 }
4292 if (!intent.debugCheck()) {
4293 Log.w(TAG, "==> For Activity " + a.info.name);
4294 }
4295 addFilter(intent);
4296 }
4297 }
4298
4299 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004300 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004301 if (SHOW_INFO || Config.LOGV) Log.v(
4302 TAG, " " + type + " " +
4303 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4304 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4305 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004306 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004307 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4308 if (SHOW_INFO || Config.LOGV) {
4309 Log.v(TAG, " IntentFilter:");
4310 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4311 }
4312 removeFilter(intent);
4313 }
4314 }
4315
4316 @Override
4317 protected boolean allowFilterResult(
4318 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4319 ActivityInfo filterAi = filter.activity.info;
4320 for (int i=dest.size()-1; i>=0; i--) {
4321 ActivityInfo destAi = dest.get(i).activityInfo;
4322 if (destAi.name == filterAi.name
4323 && destAi.packageName == filterAi.packageName) {
4324 return false;
4325 }
4326 }
4327 return true;
4328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004330 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004331 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4332 return info.activity.owner.packageName;
4333 }
4334
4335 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004336 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4337 int match) {
4338 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4339 return null;
4340 }
4341 final PackageParser.Activity activity = info.activity;
4342 if (mSafeMode && (activity.info.applicationInfo.flags
4343 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4344 return null;
4345 }
4346 final ResolveInfo res = new ResolveInfo();
4347 res.activityInfo = PackageParser.generateActivityInfo(activity,
4348 mFlags);
4349 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4350 res.filter = info;
4351 }
4352 res.priority = info.getPriority();
4353 res.preferredOrder = activity.owner.mPreferredOrder;
4354 //System.out.println("Result: " + res.activityInfo.className +
4355 // " = " + res.priority);
4356 res.match = match;
4357 res.isDefault = info.hasDefault;
4358 res.labelRes = info.labelRes;
4359 res.nonLocalizedLabel = info.nonLocalizedLabel;
4360 res.icon = info.icon;
4361 return res;
4362 }
4363
4364 @Override
4365 protected void sortResults(List<ResolveInfo> results) {
4366 Collections.sort(results, mResolvePrioritySorter);
4367 }
4368
4369 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004370 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004371 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004372 out.print(prefix); out.print(
4373 Integer.toHexString(System.identityHashCode(filter.activity)));
4374 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004375 out.print(filter.activity.getComponentShortName());
4376 out.print(" filter ");
4377 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004378 }
4379
4380// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4381// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4382// final List<ResolveInfo> retList = Lists.newArrayList();
4383// while (i.hasNext()) {
4384// final ResolveInfo resolveInfo = i.next();
4385// if (isEnabledLP(resolveInfo.activityInfo)) {
4386// retList.add(resolveInfo);
4387// }
4388// }
4389// return retList;
4390// }
4391
4392 // Keys are String (activity class name), values are Activity.
4393 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4394 = new HashMap<ComponentName, PackageParser.Activity>();
4395 private int mFlags;
4396 }
4397
4398 private final class ServiceIntentResolver
4399 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004400 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004401 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004402 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403 }
4404
Mihai Preda074edef2009-05-18 17:13:31 +02004405 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004406 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004407 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004408 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4409 }
4410
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004411 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4412 ArrayList<PackageParser.Service> packageServices) {
4413 if (packageServices == null) {
4414 return null;
4415 }
4416 mFlags = flags;
4417 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4418 int N = packageServices.size();
4419 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4420 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4421
4422 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4423 for (int i = 0; i < N; ++i) {
4424 intentFilters = packageServices.get(i).intents;
4425 if (intentFilters != null && intentFilters.size() > 0) {
4426 listCut.add(intentFilters);
4427 }
4428 }
4429 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4430 }
4431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004433 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434 if (SHOW_INFO || Config.LOGV) Log.v(
4435 TAG, " " + (s.info.nonLocalizedLabel != null
4436 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4437 if (SHOW_INFO || Config.LOGV) Log.v(
4438 TAG, " Class=" + s.info.name);
4439 int NI = s.intents.size();
4440 int j;
4441 for (j=0; j<NI; j++) {
4442 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4443 if (SHOW_INFO || Config.LOGV) {
4444 Log.v(TAG, " IntentFilter:");
4445 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4446 }
4447 if (!intent.debugCheck()) {
4448 Log.w(TAG, "==> For Service " + s.info.name);
4449 }
4450 addFilter(intent);
4451 }
4452 }
4453
4454 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004455 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004456 if (SHOW_INFO || Config.LOGV) Log.v(
4457 TAG, " " + (s.info.nonLocalizedLabel != null
4458 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4459 if (SHOW_INFO || Config.LOGV) Log.v(
4460 TAG, " Class=" + s.info.name);
4461 int NI = s.intents.size();
4462 int j;
4463 for (j=0; j<NI; j++) {
4464 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4465 if (SHOW_INFO || Config.LOGV) {
4466 Log.v(TAG, " IntentFilter:");
4467 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4468 }
4469 removeFilter(intent);
4470 }
4471 }
4472
4473 @Override
4474 protected boolean allowFilterResult(
4475 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4476 ServiceInfo filterSi = filter.service.info;
4477 for (int i=dest.size()-1; i>=0; i--) {
4478 ServiceInfo destAi = dest.get(i).serviceInfo;
4479 if (destAi.name == filterSi.name
4480 && destAi.packageName == filterSi.packageName) {
4481 return false;
4482 }
4483 }
4484 return true;
4485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004487 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004488 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4489 return info.service.owner.packageName;
4490 }
4491
4492 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004493 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4494 int match) {
4495 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4496 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4497 return null;
4498 }
4499 final PackageParser.Service service = info.service;
4500 if (mSafeMode && (service.info.applicationInfo.flags
4501 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4502 return null;
4503 }
4504 final ResolveInfo res = new ResolveInfo();
4505 res.serviceInfo = PackageParser.generateServiceInfo(service,
4506 mFlags);
4507 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4508 res.filter = filter;
4509 }
4510 res.priority = info.getPriority();
4511 res.preferredOrder = service.owner.mPreferredOrder;
4512 //System.out.println("Result: " + res.activityInfo.className +
4513 // " = " + res.priority);
4514 res.match = match;
4515 res.isDefault = info.hasDefault;
4516 res.labelRes = info.labelRes;
4517 res.nonLocalizedLabel = info.nonLocalizedLabel;
4518 res.icon = info.icon;
4519 return res;
4520 }
4521
4522 @Override
4523 protected void sortResults(List<ResolveInfo> results) {
4524 Collections.sort(results, mResolvePrioritySorter);
4525 }
4526
4527 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004528 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004530 out.print(prefix); out.print(
4531 Integer.toHexString(System.identityHashCode(filter.service)));
4532 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004533 out.print(filter.service.getComponentShortName());
4534 out.print(" filter ");
4535 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004536 }
4537
4538// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4539// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4540// final List<ResolveInfo> retList = Lists.newArrayList();
4541// while (i.hasNext()) {
4542// final ResolveInfo resolveInfo = (ResolveInfo) i;
4543// if (isEnabledLP(resolveInfo.serviceInfo)) {
4544// retList.add(resolveInfo);
4545// }
4546// }
4547// return retList;
4548// }
4549
4550 // Keys are String (activity class name), values are Activity.
4551 private final HashMap<ComponentName, PackageParser.Service> mServices
4552 = new HashMap<ComponentName, PackageParser.Service>();
4553 private int mFlags;
4554 };
4555
4556 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4557 new Comparator<ResolveInfo>() {
4558 public int compare(ResolveInfo r1, ResolveInfo r2) {
4559 int v1 = r1.priority;
4560 int v2 = r2.priority;
4561 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4562 if (v1 != v2) {
4563 return (v1 > v2) ? -1 : 1;
4564 }
4565 v1 = r1.preferredOrder;
4566 v2 = r2.preferredOrder;
4567 if (v1 != v2) {
4568 return (v1 > v2) ? -1 : 1;
4569 }
4570 if (r1.isDefault != r2.isDefault) {
4571 return r1.isDefault ? -1 : 1;
4572 }
4573 v1 = r1.match;
4574 v2 = r2.match;
4575 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4576 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4577 }
4578 };
4579
4580 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4581 new Comparator<ProviderInfo>() {
4582 public int compare(ProviderInfo p1, ProviderInfo p2) {
4583 final int v1 = p1.initOrder;
4584 final int v2 = p2.initOrder;
4585 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4586 }
4587 };
4588
Kenny Root93565c4b2010-06-18 15:46:06 -07004589 private static final boolean DEBUG_OBB = false;
4590
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004591 private static final void sendPackageBroadcast(String action, String pkg,
4592 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004593 IActivityManager am = ActivityManagerNative.getDefault();
4594 if (am != null) {
4595 try {
4596 final Intent intent = new Intent(action,
4597 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4598 if (extras != null) {
4599 intent.putExtras(extras);
4600 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004601 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004602 am.broadcastIntent(null, intent, null, finishedReceiver,
4603 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 } catch (RemoteException ex) {
4605 }
4606 }
4607 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004608
4609 public String nextPackageToClean(String lastPackage) {
4610 synchronized (mPackages) {
4611 if (!mMediaMounted) {
4612 // If the external storage is no longer mounted at this point,
4613 // the caller may not have been able to delete all of this
4614 // packages files and can not delete any more. Bail.
4615 return null;
4616 }
4617 if (lastPackage != null) {
4618 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4619 }
4620 return mSettings.mPackagesToBeCleaned.size() > 0
4621 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4622 }
4623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004624
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004625 void schedulePackageCleaning(String packageName) {
4626 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4627 }
4628
4629 void startCleaningPackages() {
4630 synchronized (mPackages) {
4631 if (!mMediaMounted) {
4632 return;
4633 }
4634 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4635 return;
4636 }
4637 }
4638 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4639 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4640 IActivityManager am = ActivityManagerNative.getDefault();
4641 if (am != null) {
4642 try {
4643 am.startService(null, intent, null);
4644 } catch (RemoteException e) {
4645 }
4646 }
4647 }
4648
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004649 private final class AppDirObserver extends FileObserver {
4650 public AppDirObserver(String path, int mask, boolean isrom) {
4651 super(path, mask);
4652 mRootDir = path;
4653 mIsRom = isrom;
4654 }
4655
4656 public void onEvent(int event, String path) {
4657 String removedPackage = null;
4658 int removedUid = -1;
4659 String addedPackage = null;
4660 int addedUid = -1;
4661
4662 synchronized (mInstallLock) {
4663 String fullPathStr = null;
4664 File fullPath = null;
4665 if (path != null) {
4666 fullPath = new File(mRootDir, path);
4667 fullPathStr = fullPath.getPath();
4668 }
4669
4670 if (Config.LOGV) Log.v(
4671 TAG, "File " + fullPathStr + " changed: "
4672 + Integer.toHexString(event));
4673
4674 if (!isPackageFilename(path)) {
4675 if (Config.LOGV) Log.v(
4676 TAG, "Ignoring change of non-package file: " + fullPathStr);
4677 return;
4678 }
4679
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004680 // Ignore packages that are being installed or
4681 // have just been installed.
4682 if (ignoreCodePath(fullPathStr)) {
4683 return;
4684 }
4685 PackageParser.Package p = null;
4686 synchronized (mPackages) {
4687 p = mAppDirs.get(fullPathStr);
4688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004689 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004690 if (p != null) {
4691 removePackageLI(p, true);
4692 removedPackage = p.applicationInfo.packageName;
4693 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 }
4695 }
4696
4697 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004698 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004699 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004700 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4701 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004702 PackageParser.PARSE_CHATTY |
4703 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004704 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004705 if (p != null) {
4706 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004707 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004708 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004709 }
4710 addedPackage = p.applicationInfo.packageName;
4711 addedUid = p.applicationInfo.uid;
4712 }
4713 }
4714 }
4715
4716 synchronized (mPackages) {
4717 mSettings.writeLP();
4718 }
4719 }
4720
4721 if (removedPackage != null) {
4722 Bundle extras = new Bundle(1);
4723 extras.putInt(Intent.EXTRA_UID, removedUid);
4724 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004725 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4726 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004727 }
4728 if (addedPackage != null) {
4729 Bundle extras = new Bundle(1);
4730 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004731 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4732 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004733 }
4734 }
4735
4736 private final String mRootDir;
4737 private final boolean mIsRom;
4738 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740 /* Called when a downloaded package installation has been confirmed by the user */
4741 public void installPackage(
4742 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004743 installPackage(packageURI, observer, flags, null);
4744 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004745
Jacek Surazski65e13172009-04-28 15:26:38 +02004746 /* Called when a downloaded package installation has been confirmed by the user */
4747 public void installPackage(
4748 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4749 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004750 mContext.enforceCallingOrSelfPermission(
4751 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004752
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004753 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004754 msg.obj = new InstallParams(packageURI, observer, flags,
4755 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004756 mHandler.sendMessage(msg);
4757 }
4758
Christopher Tate1bb69062010-02-19 17:02:12 -08004759 public void finishPackageInstall(int token) {
4760 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4761 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4762 mHandler.sendMessage(msg);
4763 }
4764
Kenny Root93565c4b2010-06-18 15:46:06 -07004765 public void setPackageObbPath(String packageName, String path) {
4766 if (DEBUG_OBB)
4767 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4768 PackageSetting pkgSetting;
4769 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004770 final int permission = mContext.checkCallingPermission(
4771 android.Manifest.permission.INSTALL_PACKAGES);
4772 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004773 synchronized (mPackages) {
4774 pkgSetting = mSettings.mPackages.get(packageName);
4775 if (pkgSetting == null) {
4776 throw new IllegalArgumentException("Unknown package: " + packageName);
4777 }
4778 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4779 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4780 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4781 + pkgSetting.userId);
4782 }
4783 pkgSetting.obbPathString = path;
4784 mSettings.writeLP();
4785 }
4786 }
4787
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004788 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004789 // Queue up an async operation since the package installation may take a little while.
4790 mHandler.post(new Runnable() {
4791 public void run() {
4792 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004793 // Result object to be returned
4794 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004795 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004796 res.uid = -1;
4797 res.pkg = null;
4798 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004799 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004800 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004801 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004802 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004803 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004804 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004805 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004806
4807 // A restore should be performed at this point if (a) the install
4808 // succeeded, (b) the operation is not an update, and (c) the new
4809 // package has a backupAgent defined.
4810 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004811 boolean doRestore = (!update
4812 && res.pkg != null
4813 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004814
4815 // Set up the post-install work request bookkeeping. This will be used
4816 // and cleaned up by the post-install event handling regardless of whether
4817 // there's a restore pass performed. Token values are >= 1.
4818 int token;
4819 if (mNextInstallToken < 0) mNextInstallToken = 1;
4820 token = mNextInstallToken++;
4821
4822 PostInstallData data = new PostInstallData(args, res);
4823 mRunningInstalls.put(token, data);
4824 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4825
4826 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4827 // Pass responsibility to the Backup Manager. It will perform a
4828 // restore if appropriate, then pass responsibility back to the
4829 // Package Manager to run the post-install observer callbacks
4830 // and broadcasts.
4831 IBackupManager bm = IBackupManager.Stub.asInterface(
4832 ServiceManager.getService(Context.BACKUP_SERVICE));
4833 if (bm != null) {
4834 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4835 + " to BM for possible restore");
4836 try {
4837 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4838 } catch (RemoteException e) {
4839 // can't happen; the backup manager is local
4840 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004841 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004842 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004843 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004844 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004845 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004846 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004847 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004848 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004849
4850 if (!doRestore) {
4851 // No restore possible, or the Backup Manager was mysteriously not
4852 // available -- just fire the post-install work request directly.
4853 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4854 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4855 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004857 }
4858 });
4859 }
4860
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004861 abstract class HandlerParams {
4862 final static int MAX_RETRIES = 4;
4863 int retry = 0;
4864 final void startCopy() {
4865 try {
4866 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4867 retry++;
4868 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004869 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004870 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4871 handleServiceError();
4872 return;
4873 } else {
4874 handleStartCopy();
4875 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4876 mHandler.sendEmptyMessage(MCS_UNBIND);
4877 }
4878 } catch (RemoteException e) {
4879 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4880 mHandler.sendEmptyMessage(MCS_RECONNECT);
4881 }
4882 handleReturnCode();
4883 }
4884
4885 final void serviceError() {
4886 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4887 handleServiceError();
4888 handleReturnCode();
4889 }
4890 abstract void handleStartCopy() throws RemoteException;
4891 abstract void handleServiceError();
4892 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004893 }
4894
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004895 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004896 final IPackageInstallObserver observer;
4897 int flags;
4898 final Uri packageURI;
4899 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004900 private InstallArgs mArgs;
4901 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004902 InstallParams(Uri packageURI,
4903 IPackageInstallObserver observer, int flags,
4904 String installerPackageName) {
4905 this.packageURI = packageURI;
4906 this.flags = flags;
4907 this.observer = observer;
4908 this.installerPackageName = installerPackageName;
4909 }
4910
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004911 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4912 String packageName = pkgLite.packageName;
4913 int installLocation = pkgLite.installLocation;
4914 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4915 synchronized (mPackages) {
4916 PackageParser.Package pkg = mPackages.get(packageName);
4917 if (pkg != null) {
4918 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4919 // Check for updated system application.
4920 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4921 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004922 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004923 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4924 }
4925 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4926 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004927 if (onSd) {
4928 // Install flag overrides everything.
4929 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4930 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004931 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004932 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4933 // Application explicitly specified internal.
4934 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4935 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4936 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004937 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004938 // Prefer previous location
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004939 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) {
4940 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4941 }
4942 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004943 }
4944 }
4945 } else {
4946 // Invalid install. Return error code
4947 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4948 }
4949 }
4950 }
4951 // All the special cases have been taken care of.
4952 // Return result based on recommended install location.
4953 if (onSd) {
4954 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4955 }
4956 return pkgLite.recommendedInstallLocation;
4957 }
4958
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004959 /*
4960 * Invoke remote method to get package information and install
4961 * location values. Override install location based on default
4962 * policy if needed and then create install arguments based
4963 * on the install location.
4964 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004965 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004966 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004967 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4968 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004969 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4970 if (onInt && onSd) {
4971 // Check if both bits are set.
4972 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4973 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4974 } else if (fwdLocked && onSd) {
4975 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004976 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004977 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004978 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004979 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004980 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004981 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004982 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4983 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4984 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4985 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4986 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004987 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4988 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4989 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004990 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4991 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004992 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004993 // Override with defaults if needed.
4994 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004995 if (!onSd && !onInt) {
4996 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004997 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4998 // Set the flag to install on external media.
4999 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005000 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005001 } else {
5002 // Make sure the flag for installing on external
5003 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07005004 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005005 flags &= ~PackageManager.INSTALL_EXTERNAL;
5006 }
5007 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005008 }
5009 }
5010 // Create the file args now.
5011 mArgs = createInstallArgs(this);
5012 if (ret == PackageManager.INSTALL_SUCCEEDED) {
5013 // Create copy only if we are not in an erroneous state.
5014 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005015 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005016 }
5017 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005018 }
5019
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005020 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005021 void handleReturnCode() {
5022 processPendingInstall(mArgs, mRet);
5023 }
5024
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005025 @Override
5026 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005027 mArgs = createInstallArgs(this);
5028 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005029 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005030 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005031
5032 /*
5033 * Utility class used in movePackage api.
5034 * srcArgs and targetArgs are not set for invalid flags and make
5035 * sure to do null checks when invoking methods on them.
5036 * We probably want to return ErrorPrams for both failed installs
5037 * and moves.
5038 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005039 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005040 final IPackageMoveObserver observer;
5041 final int flags;
5042 final String packageName;
5043 final InstallArgs srcArgs;
5044 final InstallArgs targetArgs;
5045 int mRet;
5046 MoveParams(InstallArgs srcArgs,
5047 IPackageMoveObserver observer,
5048 int flags, String packageName) {
5049 this.srcArgs = srcArgs;
5050 this.observer = observer;
5051 this.flags = flags;
5052 this.packageName = packageName;
5053 if (srcArgs != null) {
5054 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
5055 targetArgs = createInstallArgs(packageUri, flags, packageName);
5056 } else {
5057 targetArgs = null;
5058 }
5059 }
5060
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005061 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005062 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5063 // Check for storage space on target medium
5064 if (!targetArgs.checkFreeStorage(mContainerService)) {
5065 Log.w(TAG, "Insufficient storage to install");
5066 return;
5067 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005068 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005069 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005070 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005071 if (DEBUG_SD_INSTALL) {
5072 StringBuilder builder = new StringBuilder();
5073 if (srcArgs != null) {
5074 builder.append("src: ");
5075 builder.append(srcArgs.getCodePath());
5076 }
5077 if (targetArgs != null) {
5078 builder.append(" target : ");
5079 builder.append(targetArgs.getCodePath());
5080 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005081 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005082 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005083 }
5084
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005085 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005086 void handleReturnCode() {
5087 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005088 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
5089 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
5090 currentStatus = PackageManager.MOVE_SUCCEEDED;
5091 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
5092 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
5093 }
5094 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005095 }
5096
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005097 @Override
5098 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005099 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005100 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005101 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005102
5103 private InstallArgs createInstallArgs(InstallParams params) {
5104 if (installOnSd(params.flags)) {
5105 return new SdInstallArgs(params);
5106 } else {
5107 return new FileInstallArgs(params);
5108 }
5109 }
5110
5111 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath) {
5112 if (installOnSd(flags)) {
5113 return new SdInstallArgs(fullCodePath, fullResourcePath);
5114 } else {
5115 return new FileInstallArgs(fullCodePath, fullResourcePath);
5116 }
5117 }
5118
Suchi Amalapurapu9a212ad2010-05-18 11:06:53 -07005119 private InstallArgs createInstallArgs(Uri packageURI, int flags,
5120 String pkgName) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005121 if (installOnSd(flags)) {
5122 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
5123 return new SdInstallArgs(packageURI, cid);
5124 } else {
5125 return new FileInstallArgs(packageURI, pkgName);
5126 }
5127 }
5128
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005129 static abstract class InstallArgs {
5130 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005131 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005132 final int flags;
5133 final Uri packageURI;
5134 final String installerPackageName;
5135
5136 InstallArgs(Uri packageURI,
5137 IPackageInstallObserver observer, int flags,
5138 String installerPackageName) {
5139 this.packageURI = packageURI;
5140 this.flags = flags;
5141 this.observer = observer;
5142 this.installerPackageName = installerPackageName;
5143 }
5144
5145 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005146 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005147 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005148 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005149 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005150 abstract String getCodePath();
5151 abstract String getResourcePath();
5152 // Need installer lock especially for dex file removal.
5153 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005154 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005155 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005156 }
5157
5158 class FileInstallArgs extends InstallArgs {
5159 File installDir;
5160 String codeFileName;
5161 String resourceFileName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005162 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005163
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005164 FileInstallArgs(InstallParams params) {
5165 super(params.packageURI, params.observer,
5166 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005167 }
5168
5169 FileInstallArgs(String fullCodePath, String fullResourcePath) {
5170 super(null, null, 0, null);
5171 File codeFile = new File(fullCodePath);
5172 installDir = codeFile.getParentFile();
5173 codeFileName = fullCodePath;
5174 resourceFileName = fullResourcePath;
5175 }
5176
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005177 FileInstallArgs(Uri packageURI, String pkgName) {
5178 super(packageURI, null, 0, null);
5179 boolean fwdLocked = isFwdLocked(flags);
5180 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5181 String apkName = getNextCodePath(null, pkgName, ".apk");
5182 codeFileName = new File(installDir, apkName + ".apk").getPath();
5183 resourceFileName = getResourcePathFromCodePath();
5184 }
5185
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005186 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5187 return imcs.checkFreeStorage(false, packageURI);
5188 }
5189
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005190 String getCodePath() {
5191 return codeFileName;
5192 }
5193
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005194 void createCopyFile() {
5195 boolean fwdLocked = isFwdLocked(flags);
5196 installDir = fwdLocked ? mDrmAppPrivateInstallDir : mAppInstallDir;
5197 codeFileName = createTempPackageFile(installDir).getPath();
5198 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005199 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005200 }
5201
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005202 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005203 if (temp) {
5204 // Generate temp file name
5205 createCopyFile();
5206 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005207 // Get a ParcelFileDescriptor to write to the output file
5208 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005209 if (!created) {
5210 try {
5211 codeFile.createNewFile();
5212 // Set permissions
5213 if (!setPermissions()) {
5214 // Failed setting permissions.
5215 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5216 }
5217 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005218 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005219 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5220 }
5221 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005222 ParcelFileDescriptor out = null;
5223 try {
5224 out = ParcelFileDescriptor.open(codeFile,
5225 ParcelFileDescriptor.MODE_READ_WRITE);
5226 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005227 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005228 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5229 }
5230 // Copy the resource now
5231 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5232 try {
5233 if (imcs.copyResource(packageURI, out)) {
5234 ret = PackageManager.INSTALL_SUCCEEDED;
5235 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005236 } finally {
5237 try { if (out != null) out.close(); } catch (IOException e) {}
5238 }
5239 return ret;
5240 }
5241
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005242 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005243 if (status != PackageManager.INSTALL_SUCCEEDED) {
5244 cleanUp();
5245 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005246 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005247 }
5248
5249 boolean doRename(int status, final String pkgName, String oldCodePath) {
5250 if (status != PackageManager.INSTALL_SUCCEEDED) {
5251 cleanUp();
5252 return false;
5253 } else {
5254 // Rename based on packageName
5255 File codeFile = new File(getCodePath());
5256 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5257 File desFile = new File(installDir, apkName + ".apk");
5258 if (!codeFile.renameTo(desFile)) {
5259 return false;
5260 }
5261 // Reset paths since the file has been renamed.
5262 codeFileName = desFile.getPath();
5263 resourceFileName = getResourcePathFromCodePath();
5264 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005265 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005266 // Failed setting permissions.
5267 return false;
5268 }
5269 return true;
5270 }
5271 }
5272
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005273 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005274 if (status != PackageManager.INSTALL_SUCCEEDED) {
5275 cleanUp();
5276 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005277 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005278 }
5279
5280 String getResourcePath() {
5281 return resourceFileName;
5282 }
5283
5284 String getResourcePathFromCodePath() {
5285 String codePath = getCodePath();
5286 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5287 String apkNameOnly = getApkName(codePath);
5288 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5289 } else {
5290 return codePath;
5291 }
5292 }
5293
5294 private boolean cleanUp() {
5295 boolean ret = true;
5296 String sourceDir = getCodePath();
5297 String publicSourceDir = getResourcePath();
5298 if (sourceDir != null) {
5299 File sourceFile = new File(sourceDir);
5300 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005301 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005302 ret = false;
5303 }
5304 // Delete application's code and resources
5305 sourceFile.delete();
5306 }
5307 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5308 final File publicSourceFile = new File(publicSourceDir);
5309 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005310 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 }
5312 if (publicSourceFile.exists()) {
5313 publicSourceFile.delete();
5314 }
5315 }
5316 return ret;
5317 }
5318
5319 void cleanUpResourcesLI() {
5320 String sourceDir = getCodePath();
5321 if (cleanUp() && mInstaller != null) {
5322 int retCode = mInstaller.rmdex(sourceDir);
5323 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005324 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005325 + " at location "
5326 + sourceDir + ", retcode=" + retCode);
5327 // we don't consider this to be a failure of the core package deletion
5328 }
5329 }
5330 }
5331
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005332 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005333 // TODO Do this in a more elegant way later on. for now just a hack
5334 if (!isFwdLocked(flags)) {
5335 final int filePermissions =
5336 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5337 |FileUtils.S_IROTH;
5338 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5339 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005340 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005341 getCodePath()
5342 + ". The return code was: " + retCode);
5343 // TODO Define new internal error
5344 return false;
5345 }
5346 return true;
5347 }
5348 return true;
5349 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005350
5351 boolean doPostDeleteLI(boolean delete) {
5352 cleanUpResourcesLI();
5353 return true;
5354 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005355 }
5356
5357 class SdInstallArgs extends InstallArgs {
5358 String cid;
5359 String cachePath;
5360 static final String RES_FILE_NAME = "pkg.apk";
5361
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005362 SdInstallArgs(InstallParams params) {
5363 super(params.packageURI, params.observer,
5364 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005365 }
5366
5367 SdInstallArgs(String fullCodePath, String fullResourcePath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005368 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005369 // Extract cid from fullCodePath
5370 int eidx = fullCodePath.lastIndexOf("/");
5371 String subStr1 = fullCodePath.substring(0, eidx);
5372 int sidx = subStr1.lastIndexOf("/");
5373 cid = subStr1.substring(sidx+1, eidx);
5374 cachePath = subStr1;
5375 }
5376
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005377 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005378 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5379 this.cid = cid;
Suchi Amalapurapu9a212ad2010-05-18 11:06:53 -07005380 cachePath = PackageHelper.getSdDir(cid);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005381 }
5382
5383 SdInstallArgs(Uri packageURI, String cid) {
5384 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005385 this.cid = cid;
5386 }
5387
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005388 void createCopyFile() {
5389 cid = getTempContainerId();
5390 }
5391
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005392 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5393 return imcs.checkFreeStorage(true, packageURI);
5394 }
5395
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005396 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005397 if (temp) {
5398 createCopyFile();
5399 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005400 cachePath = imcs.copyResourceToContainer(
5401 packageURI, cid,
5402 getEncryptKey(), RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005403 return (cachePath == null) ? PackageManager.INSTALL_FAILED_CONTAINER_ERROR :
5404 PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005405 }
5406
5407 @Override
5408 String getCodePath() {
5409 return cachePath + "/" + RES_FILE_NAME;
5410 }
5411
5412 @Override
5413 String getResourcePath() {
5414 return cachePath + "/" + RES_FILE_NAME;
5415 }
5416
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005417 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005418 if (status != PackageManager.INSTALL_SUCCEEDED) {
5419 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005420 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005421 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005422 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005423 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005424 cachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), Process.SYSTEM_UID);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005425 if (cachePath == null) {
5426 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5427 }
5428 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005429 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005430 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005431 }
5432
5433 boolean doRename(int status, final String pkgName,
5434 String oldCodePath) {
5435 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005436 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005437 if (PackageHelper.isContainerMounted(cid)) {
5438 // Unmount the container
5439 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005440 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005441 return false;
5442 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005443 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005444 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005445 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5446 " which might be stale. Will try to clean up.");
5447 // Clean up the stale container and proceed to recreate.
5448 if (!PackageHelper.destroySdDir(newCacheId)) {
5449 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5450 return false;
5451 }
5452 // Successfully cleaned up stale container. Try to rename again.
5453 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5454 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5455 + " inspite of cleaning it up.");
5456 return false;
5457 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005458 }
5459 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005460 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005461 newCachePath = PackageHelper.mountSdDir(newCacheId,
5462 getEncryptKey(), Process.SYSTEM_UID);
5463 } else {
5464 newCachePath = PackageHelper.getSdDir(newCacheId);
5465 }
5466 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005467 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005468 return false;
5469 }
5470 Log.i(TAG, "Succesfully renamed " + cid +
5471 " at path: " + cachePath + " to " + newCacheId +
5472 " at new path: " + newCachePath);
5473 cid = newCacheId;
5474 cachePath = newCachePath;
5475 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005476 }
5477
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005478 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005479 if (status != PackageManager.INSTALL_SUCCEEDED) {
5480 cleanUp();
5481 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005482 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005483 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005484 PackageHelper.mountSdDir(cid,
5485 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005486 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005487 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005488 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005489 }
5490
5491 private void cleanUp() {
5492 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005493 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005494 }
5495
5496 void cleanUpResourcesLI() {
5497 String sourceFile = getCodePath();
5498 // Remove dex file
5499 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005500 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005501 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005502 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005503 + " at location "
5504 + sourceFile.toString() + ", retcode=" + retCode);
5505 // we don't consider this to be a failure of the core package deletion
5506 }
5507 }
5508 cleanUp();
5509 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005510
5511 boolean matchContainer(String app) {
5512 if (cid.startsWith(app)) {
5513 return true;
5514 }
5515 return false;
5516 }
5517
5518 String getPackageName() {
5519 int idx = cid.lastIndexOf("-");
5520 if (idx == -1) {
5521 return cid;
5522 }
5523 return cid.substring(0, idx);
5524 }
5525
5526 boolean doPostDeleteLI(boolean delete) {
5527 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005528 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005529 if (mounted) {
5530 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005531 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005532 }
5533 if (ret && delete) {
5534 cleanUpResourcesLI();
5535 }
5536 return ret;
5537 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005538 };
5539
5540 // Utility method used to create code paths based on package name and available index.
5541 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5542 String idxStr = "";
5543 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005544 // Fall back to default value of idx=1 if prefix is not
5545 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005546 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005547 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005548 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005549 if (subStr.endsWith(suffix)) {
5550 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005551 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005552 // If oldCodePath already contains prefix find out the
5553 // ending index to either increment or decrement.
5554 int sidx = subStr.lastIndexOf(prefix);
5555 if (sidx != -1) {
5556 subStr = subStr.substring(sidx + prefix.length());
5557 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005558 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5559 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005560 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005561 try {
5562 idx = Integer.parseInt(subStr);
5563 if (idx <= 1) {
5564 idx++;
5565 } else {
5566 idx--;
5567 }
5568 } catch(NumberFormatException e) {
5569 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005570 }
5571 }
5572 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005573 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005574 return prefix + idxStr;
5575 }
5576
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005577 // Utility method used to ignore ADD/REMOVE events
5578 // by directory observer.
5579 private static boolean ignoreCodePath(String fullPathStr) {
5580 String apkName = getApkName(fullPathStr);
5581 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5582 if (idx != -1 && ((idx+1) < apkName.length())) {
5583 // Make sure the package ends with a numeral
5584 String version = apkName.substring(idx+1);
5585 try {
5586 Integer.parseInt(version);
5587 return true;
5588 } catch (NumberFormatException e) {}
5589 }
5590 return false;
5591 }
5592
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005593 // Utility method that returns the relative package path with respect
5594 // to the installation directory. Like say for /data/data/com.test-1.apk
5595 // string com.test-1 is returned.
5596 static String getApkName(String codePath) {
5597 if (codePath == null) {
5598 return null;
5599 }
5600 int sidx = codePath.lastIndexOf("/");
5601 int eidx = codePath.lastIndexOf(".");
5602 if (eidx == -1) {
5603 eidx = codePath.length();
5604 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005605 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005606 return null;
5607 }
5608 return codePath.substring(sidx+1, eidx);
5609 }
5610
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005611 class PackageInstalledInfo {
5612 String name;
5613 int uid;
5614 PackageParser.Package pkg;
5615 int returnCode;
5616 PackageRemovedInfo removedInfo;
5617 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005619 /*
5620 * Install a non-existing package.
5621 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005622 private void installNewPackageLI(PackageParser.Package pkg,
5623 int parseFlags,
5624 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005625 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005626 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005627 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005628
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005629 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005630 res.name = pkgName;
5631 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005632 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5633 // A package with the same name is already installed, though
5634 // it has been renamed to an older name. The package we
5635 // are trying to install should be installed as an update to
5636 // the existing one, but that has not been requested, so bail.
5637 Slog.w(TAG, "Attempt to re-install " + pkgName
5638 + " without first uninstalling package running as "
5639 + mSettings.mRenamedPackages.get(pkgName));
5640 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5641 return;
5642 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005643 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005644 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005645 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 + " without first uninstalling.");
5647 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5648 return;
5649 }
5650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005651 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005652 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005653 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005654 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5656 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5657 }
5658 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005659 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005660 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 res);
5662 // delete the partially installed application. the data directory will have to be
5663 // restored if it was already existing
5664 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5665 // remove package from internal structures. Note that we want deletePackageX to
5666 // delete the package data and cache directories that it created in
5667 // scanPackageLocked, unless those directories existed before we even tried to
5668 // install.
5669 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005670 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005671 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5672 res.removedInfo);
5673 }
5674 }
5675 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005676
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005677 private void replacePackageLI(PackageParser.Package pkg,
5678 int parseFlags,
5679 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005680 String installerPackageName, PackageInstalledInfo res) {
5681
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005682 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005683 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 // First find the old package info and check signatures
5685 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005686 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005687 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005688 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005689 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5690 return;
5691 }
5692 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005693 boolean sysPkg = ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005694 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005695 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005696 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005697 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005698 }
5699 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005701 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005702 PackageParser.Package pkg,
5703 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005704 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005705 PackageParser.Package newPackage = null;
5706 String pkgName = deletedPackage.packageName;
5707 boolean deletedPkg = true;
5708 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005709
Jacek Surazski65e13172009-04-28 15:26:38 +02005710 String oldInstallerPackageName = null;
5711 synchronized (mPackages) {
5712 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005716 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005717 res.removedInfo)) {
5718 // If the existing package was'nt successfully deleted
5719 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5720 deletedPkg = false;
5721 } else {
5722 // Successfully deleted the old package. Now proceed with re-installation
5723 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005724 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005725 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005726 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5728 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005729 }
5730 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005731 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005732 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 res);
5734 updatedSettings = true;
5735 }
5736 }
5737
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005738 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005739 // remove package from internal structures. Note that we want deletePackageX to
5740 // delete the package data and cache directories that it created in
5741 // scanPackageLocked, unless those directories existed before we even tried to
5742 // install.
5743 if(updatedSettings) {
5744 deletePackageLI(
5745 pkgName, true,
5746 PackageManager.DONT_DELETE_DATA,
5747 res.removedInfo);
5748 }
5749 // Since we failed to install the new package we need to restore the old
5750 // package that we deleted.
5751 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005752 File restoreFile = new File(deletedPackage.mPath);
5753 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005754 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005755 return;
5756 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005757 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005758 boolean oldOnSd = isExternal(deletedPackage);
5759 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5760 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5761 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5762 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5763 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5764 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5765 return;
5766 }
5767 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005768 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005769 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005770 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005771 mSettings.writeLP();
5772 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005773 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005774 }
5775 }
5776 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005778 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005779 PackageParser.Package pkg,
5780 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005781 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005782 PackageParser.Package newPackage = null;
5783 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005784 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005785 PackageParser.PARSE_IS_SYSTEM;
5786 String packageName = deletedPackage.packageName;
5787 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5788 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005789 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005790 return;
5791 }
5792 PackageParser.Package oldPkg;
5793 PackageSetting oldPkgSetting;
5794 synchronized (mPackages) {
5795 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005796 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005797 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5798 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005799 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005800 return;
5801 }
5802 }
5803 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5804 res.removedInfo.removedPackage = packageName;
5805 // Remove existing system package
5806 removePackageLI(oldPkg, true);
5807 synchronized (mPackages) {
5808 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5809 }
5810
5811 // Successfully disabled the old package. Now proceed with re-installation
5812 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5813 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005814 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005815 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005816 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005817 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5818 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5819 }
5820 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005821 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 updatedSettings = true;
5823 }
5824
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005825 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005826 // Re installation failed. Restore old information
5827 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005828 if (newPackage != null) {
5829 removePackageLI(newPackage, true);
5830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005831 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005832 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005834 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 // Restore the old system information in Settings
5836 synchronized(mPackages) {
5837 if(updatedSettings) {
5838 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005839 mSettings.setInstallerPackageName(packageName,
5840 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005841 }
5842 mSettings.writeLP();
5843 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005844 } else {
5845 // If this is an update to an existing update, setup
5846 // to remove the existing update.
5847 synchronized (mPackages) {
5848 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5849 if (ps != null && ps.codePathString != null &&
5850 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5851 int installFlags = 0;
5852 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
5853 oldPkgSetting.resourcePathString);
5854 }
5855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 }
5857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005858
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005859 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005860 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005861 int retCode;
5862 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5863 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5864 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005865 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005866 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5867 }
5868 }
5869 return PackageManager.INSTALL_SUCCEEDED;
5870 }
5871
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005872 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005873 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005874 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 synchronized (mPackages) {
5876 //write settings. the installStatus will be incomplete at this stage.
5877 //note that the new package setting would have already been
5878 //added to mPackages. It hasn't been persisted yet.
5879 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5880 mSettings.writeLP();
5881 }
5882
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005883 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005884 != PackageManager.INSTALL_SUCCEEDED) {
5885 // Discontinue if moving dex files failed.
5886 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005887 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005888 if((res.returnCode = setPermissionsLI(newPackage))
5889 != PackageManager.INSTALL_SUCCEEDED) {
5890 if (mInstaller != null) {
5891 mInstaller.rmdex(newPackage.mScanPath);
5892 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005893 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005895 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005897 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005898 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005899 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005900 res.name = pkgName;
5901 res.uid = newPackage.applicationInfo.uid;
5902 res.pkg = newPackage;
5903 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005904 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005905 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5906 //to update install status
5907 mSettings.writeLP();
5908 }
5909 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005910
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005911 private void installPackageLI(InstallArgs args,
5912 boolean newInstall, PackageInstalledInfo res) {
5913 int pFlags = args.flags;
5914 String installerPackageName = args.installerPackageName;
5915 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005916 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005917 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005918 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005919 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005920 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005921 // Result object to be returned
5922 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5923
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005924 // Retrieve PackageSettings and parse package
5925 int parseFlags = PackageParser.PARSE_CHATTY |
5926 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5927 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5928 parseFlags |= mDefParseFlags;
5929 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5930 pp.setSeparateProcesses(mSeparateProcesses);
5931 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5932 null, mMetrics, parseFlags);
5933 if (pkg == null) {
5934 res.returnCode = pp.getParseError();
5935 return;
5936 }
5937 String pkgName = res.name = pkg.packageName;
5938 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5939 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5940 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5941 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005942 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005943 }
5944 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5945 res.returnCode = pp.getParseError();
5946 return;
5947 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005948 // Get rid of all references to package scan path via parser.
5949 pp = null;
5950 String oldCodePath = null;
5951 boolean systemApp = false;
5952 synchronized (mPackages) {
5953 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005954 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5955 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005956 if (pkg.mOriginalPackages != null
5957 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005958 && mPackages.containsKey(oldName)) {
5959 // This package is derived from an original package,
5960 // and this device has been updating from that original
5961 // name. We must continue using the original name, so
5962 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005963 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005964 pkgName = pkg.packageName;
5965 replace = true;
5966 } else if (mPackages.containsKey(pkgName)) {
5967 // This package, under its official name, already exists
5968 // on the device; we should replace it.
5969 replace = true;
5970 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005971 }
5972 PackageSetting ps = mSettings.mPackages.get(pkgName);
5973 if (ps != null) {
5974 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5975 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5976 systemApp = (ps.pkg.applicationInfo.flags &
5977 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005978 }
5979 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005980 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005981
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005982 if (systemApp && onSd) {
5983 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005984 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005985 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5986 return;
5987 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005988
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005989 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5990 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5991 return;
5992 }
5993 // Set application objects path explicitly after the rename
5994 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005995 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005996 replacePackageLI(pkg, parseFlags, scanMode,
5997 installerPackageName, res);
5998 } else {
5999 installNewPackageLI(pkg, parseFlags, scanMode,
6000 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006001 }
6002 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006003
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006004 private int setPermissionsLI(PackageParser.Package newPackage) {
6005 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006006 int retCode = 0;
6007 // TODO Gross hack but fix later. Ideally move this to be a post installation
6008 // check after alloting uid.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006009 if ((newPackage.applicationInfo.flags
6010 & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
6011 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 try {
6013 extractPublicFiles(newPackage, destResourceFile);
6014 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006015 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 -08006016 " forward-locked app.");
6017 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
6018 } finally {
6019 //TODO clean up the extracted public files
6020 }
6021 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006022 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006023 newPackage.applicationInfo.uid);
6024 } else {
6025 final int filePermissions =
6026 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006027 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006028 newPackage.applicationInfo.uid);
6029 }
6030 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006031 // The permissions on the resource file was set when it was copied for
6032 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006035 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006036 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006037 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006038 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006039 // TODO Define new internal error
6040 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 }
6042 return PackageManager.INSTALL_SUCCEEDED;
6043 }
6044
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006045 private boolean isForwardLocked(PackageParser.Package pkg) {
6046 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006047 }
6048
Suchi Amalapurapuae181712010-03-30 14:01:02 -07006049 private boolean isExternal(PackageParser.Package pkg) {
6050 return ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0);
6051 }
6052
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006053 private void extractPublicFiles(PackageParser.Package newPackage,
6054 File publicZipFile) throws IOException {
6055 final ZipOutputStream publicZipOutStream =
6056 new ZipOutputStream(new FileOutputStream(publicZipFile));
6057 final ZipFile privateZip = new ZipFile(newPackage.mPath);
6058
6059 // Copy manifest, resources.arsc and res directory to public zip
6060
6061 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
6062 while (privateZipEntries.hasMoreElements()) {
6063 final ZipEntry zipEntry = privateZipEntries.nextElement();
6064 final String zipEntryName = zipEntry.getName();
6065 if ("AndroidManifest.xml".equals(zipEntryName)
6066 || "resources.arsc".equals(zipEntryName)
6067 || zipEntryName.startsWith("res/")) {
6068 try {
6069 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
6070 } catch (IOException e) {
6071 try {
6072 publicZipOutStream.close();
6073 throw e;
6074 } finally {
6075 publicZipFile.delete();
6076 }
6077 }
6078 }
6079 }
6080
6081 publicZipOutStream.close();
6082 FileUtils.setPermissions(
6083 publicZipFile.getAbsolutePath(),
6084 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
6085 -1, -1);
6086 }
6087
6088 private static void copyZipEntry(ZipEntry zipEntry,
6089 ZipFile inZipFile,
6090 ZipOutputStream outZipStream) throws IOException {
6091 byte[] buffer = new byte[4096];
6092 int num;
6093
6094 ZipEntry newEntry;
6095 if (zipEntry.getMethod() == ZipEntry.STORED) {
6096 // Preserve the STORED method of the input entry.
6097 newEntry = new ZipEntry(zipEntry);
6098 } else {
6099 // Create a new entry so that the compressed len is recomputed.
6100 newEntry = new ZipEntry(zipEntry.getName());
6101 }
6102 outZipStream.putNextEntry(newEntry);
6103
6104 InputStream data = inZipFile.getInputStream(zipEntry);
6105 while ((num = data.read(buffer)) > 0) {
6106 outZipStream.write(buffer, 0, num);
6107 }
6108 outZipStream.flush();
6109 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006111 private void deleteTempPackageFiles() {
6112 FilenameFilter filter = new FilenameFilter() {
6113 public boolean accept(File dir, String name) {
6114 return name.startsWith("vmdl") && name.endsWith(".tmp");
6115 }
6116 };
6117 String tmpFilesList[] = mAppInstallDir.list(filter);
6118 if(tmpFilesList == null) {
6119 return;
6120 }
6121 for(int i = 0; i < tmpFilesList.length; i++) {
6122 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
6123 tmpFile.delete();
6124 }
6125 }
6126
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006127 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006128 File tmpPackageFile;
6129 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006130 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006132 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006133 return null;
6134 }
6135 try {
6136 FileUtils.setPermissions(
6137 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
6138 -1, -1);
6139 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006140 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006141 return null;
6142 }
6143 return tmpPackageFile;
6144 }
6145
6146 public void deletePackage(final String packageName,
6147 final IPackageDeleteObserver observer,
6148 final int flags) {
6149 mContext.enforceCallingOrSelfPermission(
6150 android.Manifest.permission.DELETE_PACKAGES, null);
6151 // Queue up an async operation since the package deletion may take a little while.
6152 mHandler.post(new Runnable() {
6153 public void run() {
6154 mHandler.removeCallbacks(this);
6155 final boolean succeded = deletePackageX(packageName, true, true, flags);
6156 if (observer != null) {
6157 try {
6158 observer.packageDeleted(succeded);
6159 } catch (RemoteException e) {
6160 Log.i(TAG, "Observer no longer exists.");
6161 } //end catch
6162 } //end if
6163 } //end run
6164 });
6165 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 /**
6168 * This method is an internal method that could be get invoked either
6169 * to delete an installed package or to clean up a failed installation.
6170 * After deleting an installed package, a broadcast is sent to notify any
6171 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006172 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006173 * installation wouldn't have sent the initial broadcast either
6174 * The key steps in deleting a package are
6175 * deleting the package information in internal structures like mPackages,
6176 * deleting the packages base directories through installd
6177 * updating mSettings to reflect current status
6178 * persisting settings for later use
6179 * sending a broadcast if necessary
6180 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006181 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6182 boolean deleteCodeAndResources, int flags) {
6183 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006184 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006185
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006186 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6187 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6188 try {
6189 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006190 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006191 return false;
6192 }
6193 } catch (RemoteException e) {
6194 }
6195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006196 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006197 res = deletePackageLI(packageName, deleteCodeAndResources,
6198 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006199 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006200
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006201 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006202 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006203 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006204
6205 // If the removed package was a system update, the old system packaged
6206 // was re-enabled; we need to broadcast this information
6207 if (systemUpdate) {
6208 Bundle extras = new Bundle(1);
6209 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6210 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6211
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006212 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6213 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006216 // Force a gc here.
6217 Runtime.getRuntime().gc();
6218 // Delete the resources here after sending the broadcast to let
6219 // other processes clean up before deleting resources.
6220 if (info.args != null) {
6221 synchronized (mInstallLock) {
6222 info.args.doPostDeleteLI(deleteCodeAndResources);
6223 }
6224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 return res;
6226 }
6227
6228 static class PackageRemovedInfo {
6229 String removedPackage;
6230 int uid = -1;
6231 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006232 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006233 // Clean up resources deleted packages.
6234 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006235
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006236 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006237 Bundle extras = new Bundle(1);
6238 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6239 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6240 if (replacing) {
6241 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6242 }
6243 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006244 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 }
6246 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006247 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 }
6249 }
6250 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 /*
6253 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6254 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006255 * 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 -08006256 * delete a partially installed application.
6257 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006258 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 int flags) {
6260 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006261 if (outInfo != null) {
6262 outInfo.removedPackage = packageName;
6263 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006264 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006265 // Retrieve object to delete permissions for shared user later on
6266 PackageSetting deletedPs;
6267 synchronized (mPackages) {
6268 deletedPs = mSettings.mPackages.get(packageName);
6269 }
6270 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006271 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006273 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006275 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 + packageName + ", retcode=" + retCode);
6277 // we don't consider this to be a failure of the core package deletion
6278 }
6279 } else {
6280 //for emulator
6281 PackageParser.Package pkg = mPackages.get(packageName);
6282 File dataDir = new File(pkg.applicationInfo.dataDir);
6283 dataDir.delete();
6284 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 }
6286 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006287 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006288 schedulePackageCleaning(packageName);
6289
6290 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6291 if (outInfo != null) {
6292 outInfo.removedUid = mSettings.removePackageLP(packageName);
6293 }
6294 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006295 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006296 if (deletedPs.sharedUser != null) {
6297 // remove permissions associated with package
6298 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6299 }
6300 }
6301 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006302 // remove from preferred activities.
6303 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6304 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6305 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6306 removed.add(pa);
6307 }
6308 }
6309 for (PreferredActivity pa : removed) {
6310 mSettings.mPreferredActivities.removeFilter(pa);
6311 }
6312 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006313 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006314 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006315 }
6316 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006318 /*
6319 * Tries to delete system package.
6320 */
6321 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006322 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006323 ApplicationInfo applicationInfo = p.applicationInfo;
6324 //applicable for non-partially installed applications only
6325 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006326 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006327 return false;
6328 }
6329 PackageSetting ps = null;
6330 // Confirm if the system package has been updated
6331 // An updated system app can be deleted. This will also have to restore
6332 // the system pkg from system partition
6333 synchronized (mPackages) {
6334 ps = mSettings.getDisabledSystemPkg(p.packageName);
6335 }
6336 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006337 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006338 return false;
6339 } else {
6340 Log.i(TAG, "Deleting system pkg from data partition");
6341 }
6342 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006343 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006344 boolean deleteCodeAndResources = false;
6345 if (ps.versionCode < p.mVersionCode) {
6346 // Delete code and resources for downgrades
6347 deleteCodeAndResources = true;
6348 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6349 flags &= ~PackageManager.DONT_DELETE_DATA;
6350 }
6351 } else {
6352 // Preserve data by setting flag
6353 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6354 flags |= PackageManager.DONT_DELETE_DATA;
6355 }
6356 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006357 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6358 if (!ret) {
6359 return false;
6360 }
6361 synchronized (mPackages) {
6362 // Reinstate the old system package
6363 mSettings.enableSystemPackageLP(p.packageName);
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006364 // Remove any native libraries.
6365 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 }
6367 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006368 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006370 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006371
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006373 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006374 return false;
6375 }
6376 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006377 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 mSettings.writeLP();
6379 }
6380 return true;
6381 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006382
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006383 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6384 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6385 ApplicationInfo applicationInfo = p.applicationInfo;
6386 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006387 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006388 return false;
6389 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006390 if (outInfo != null) {
6391 outInfo.uid = applicationInfo.uid;
6392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006393
6394 // Delete package data from internal structures and also remove data if flag is set
6395 removePackageDataLI(p, outInfo, flags);
6396
6397 // Delete application code and resources
6398 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006399 // TODO can pick up from PackageSettings as well
Suchi Amalapurapu6069beb2010-03-10 09:46:49 -08006400 int installFlags = ((p.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE)!=0) ?
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08006401 PackageManager.INSTALL_EXTERNAL : 0;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006402 installFlags |= ((p.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK)!=0) ?
6403 PackageManager.INSTALL_FORWARD_LOCK : 0;
6404 outInfo.args = createInstallArgs(installFlags,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006405 applicationInfo.sourceDir, applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006406 }
6407 return true;
6408 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006409
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006410 /*
6411 * This method handles package deletion in general
6412 */
6413 private boolean deletePackageLI(String packageName,
6414 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6415 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006416 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 return false;
6418 }
6419 PackageParser.Package p;
6420 boolean dataOnly = false;
6421 synchronized (mPackages) {
6422 p = mPackages.get(packageName);
6423 if (p == null) {
6424 //this retrieves partially installed apps
6425 dataOnly = true;
6426 PackageSetting ps = mSettings.mPackages.get(packageName);
6427 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006428 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006429 return false;
6430 }
6431 p = ps.pkg;
6432 }
6433 }
6434 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006435 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006436 return false;
6437 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006439 if (dataOnly) {
6440 // Delete application data first
6441 removePackageDataLI(p, outInfo, flags);
6442 return true;
6443 }
6444 // At this point the package should have ApplicationInfo associated with it
6445 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006446 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006447 return false;
6448 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006449 boolean ret = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006450 if ( (p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
6451 Log.i(TAG, "Removing system package:"+p.packageName);
6452 // When an updated system application is deleted we delete the existing resources as well and
6453 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006454 ret = deleteSystemPackageLI(p, flags, outInfo);
6455 } else {
6456 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006457 // Kill application pre-emptively especially for apps on sd.
6458 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006459 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006460 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006461 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006462 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006463
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006464 public void clearApplicationUserData(final String packageName,
6465 final IPackageDataObserver observer) {
6466 mContext.enforceCallingOrSelfPermission(
6467 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6468 // Queue up an async operation since the package deletion may take a little while.
6469 mHandler.post(new Runnable() {
6470 public void run() {
6471 mHandler.removeCallbacks(this);
6472 final boolean succeeded;
6473 synchronized (mInstallLock) {
6474 succeeded = clearApplicationUserDataLI(packageName);
6475 }
6476 if (succeeded) {
6477 // invoke DeviceStorageMonitor's update method to clear any notifications
6478 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6479 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6480 if (dsm != null) {
6481 dsm.updateMemory();
6482 }
6483 }
6484 if(observer != null) {
6485 try {
6486 observer.onRemoveCompleted(packageName, succeeded);
6487 } catch (RemoteException e) {
6488 Log.i(TAG, "Observer no longer exists.");
6489 }
6490 } //end if observer
6491 } //end run
6492 });
6493 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006495 private boolean clearApplicationUserDataLI(String packageName) {
6496 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006497 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 return false;
6499 }
6500 PackageParser.Package p;
6501 boolean dataOnly = false;
6502 synchronized (mPackages) {
6503 p = mPackages.get(packageName);
6504 if(p == null) {
6505 dataOnly = true;
6506 PackageSetting ps = mSettings.mPackages.get(packageName);
6507 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006508 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006509 return false;
6510 }
6511 p = ps.pkg;
6512 }
6513 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006514 boolean useEncryptedFSDir = false;
6515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006516 if(!dataOnly) {
6517 //need to check this only for fully installed applications
6518 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006519 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006520 return false;
6521 }
6522 final ApplicationInfo applicationInfo = p.applicationInfo;
6523 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006524 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 return false;
6526 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006527 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006528 }
6529 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006530 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006532 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 + packageName);
6534 return false;
6535 }
6536 }
6537 return true;
6538 }
6539
6540 public void deleteApplicationCacheFiles(final String packageName,
6541 final IPackageDataObserver observer) {
6542 mContext.enforceCallingOrSelfPermission(
6543 android.Manifest.permission.DELETE_CACHE_FILES, null);
6544 // Queue up an async operation since the package deletion may take a little while.
6545 mHandler.post(new Runnable() {
6546 public void run() {
6547 mHandler.removeCallbacks(this);
6548 final boolean succeded;
6549 synchronized (mInstallLock) {
6550 succeded = deleteApplicationCacheFilesLI(packageName);
6551 }
6552 if(observer != null) {
6553 try {
6554 observer.onRemoveCompleted(packageName, succeded);
6555 } catch (RemoteException e) {
6556 Log.i(TAG, "Observer no longer exists.");
6557 }
6558 } //end if observer
6559 } //end run
6560 });
6561 }
6562
6563 private boolean deleteApplicationCacheFilesLI(String packageName) {
6564 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006565 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006566 return false;
6567 }
6568 PackageParser.Package p;
6569 synchronized (mPackages) {
6570 p = mPackages.get(packageName);
6571 }
6572 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006573 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006574 return false;
6575 }
6576 final ApplicationInfo applicationInfo = p.applicationInfo;
6577 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006578 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 return false;
6580 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006581 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006582 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006583 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006584 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006585 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006586 + packageName);
6587 return false;
6588 }
6589 }
6590 return true;
6591 }
6592
6593 public void getPackageSizeInfo(final String packageName,
6594 final IPackageStatsObserver observer) {
6595 mContext.enforceCallingOrSelfPermission(
6596 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6597 // Queue up an async operation since the package deletion may take a little while.
6598 mHandler.post(new Runnable() {
6599 public void run() {
6600 mHandler.removeCallbacks(this);
6601 PackageStats lStats = new PackageStats(packageName);
6602 final boolean succeded;
6603 synchronized (mInstallLock) {
6604 succeded = getPackageSizeInfoLI(packageName, lStats);
6605 }
6606 if(observer != null) {
6607 try {
6608 observer.onGetStatsCompleted(lStats, succeded);
6609 } catch (RemoteException e) {
6610 Log.i(TAG, "Observer no longer exists.");
6611 }
6612 } //end if observer
6613 } //end run
6614 });
6615 }
6616
6617 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6618 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006619 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006620 return false;
6621 }
6622 PackageParser.Package p;
6623 boolean dataOnly = false;
6624 synchronized (mPackages) {
6625 p = mPackages.get(packageName);
6626 if(p == null) {
6627 dataOnly = true;
6628 PackageSetting ps = mSettings.mPackages.get(packageName);
6629 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006630 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006631 return false;
6632 }
6633 p = ps.pkg;
6634 }
6635 }
6636 String publicSrcDir = null;
6637 if(!dataOnly) {
6638 final ApplicationInfo applicationInfo = p.applicationInfo;
6639 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006640 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006641 return false;
6642 }
6643 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6644 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006645 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006646 if (mInstaller != null) {
6647 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006648 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006649 if (res < 0) {
6650 return false;
6651 } else {
6652 return true;
6653 }
6654 }
6655 return true;
6656 }
6657
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006658
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006659 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006660 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006661 }
6662
6663 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006664 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006665 }
6666
6667 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006668 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 }
6670
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006671 int getUidTargetSdkVersionLockedLP(int uid) {
6672 Object obj = mSettings.getUserIdLP(uid);
6673 if (obj instanceof SharedUserSetting) {
6674 SharedUserSetting sus = (SharedUserSetting)obj;
6675 final int N = sus.packages.size();
6676 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6677 Iterator<PackageSetting> it = sus.packages.iterator();
6678 int i=0;
6679 while (it.hasNext()) {
6680 PackageSetting ps = it.next();
6681 if (ps.pkg != null) {
6682 int v = ps.pkg.applicationInfo.targetSdkVersion;
6683 if (v < vers) vers = v;
6684 }
6685 }
6686 return vers;
6687 } else if (obj instanceof PackageSetting) {
6688 PackageSetting ps = (PackageSetting)obj;
6689 if (ps.pkg != null) {
6690 return ps.pkg.applicationInfo.targetSdkVersion;
6691 }
6692 }
6693 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6694 }
6695
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 public void addPreferredActivity(IntentFilter filter, int match,
6697 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006699 if (mContext.checkCallingOrSelfPermission(
6700 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6701 != PackageManager.PERMISSION_GRANTED) {
6702 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6703 < Build.VERSION_CODES.FROYO) {
6704 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6705 + Binder.getCallingUid());
6706 return;
6707 }
6708 mContext.enforceCallingOrSelfPermission(
6709 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6710 }
6711
6712 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6714 mSettings.mPreferredActivities.addFilter(
6715 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006716 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 }
6718 }
6719
Satish Sampath8dbe6122009-06-02 23:35:54 +01006720 public void replacePreferredActivity(IntentFilter filter, int match,
6721 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006722 if (filter.countActions() != 1) {
6723 throw new IllegalArgumentException(
6724 "replacePreferredActivity expects filter to have only 1 action.");
6725 }
6726 if (filter.countCategories() != 1) {
6727 throw new IllegalArgumentException(
6728 "replacePreferredActivity expects filter to have only 1 category.");
6729 }
6730 if (filter.countDataAuthorities() != 0
6731 || filter.countDataPaths() != 0
6732 || filter.countDataSchemes() != 0
6733 || filter.countDataTypes() != 0) {
6734 throw new IllegalArgumentException(
6735 "replacePreferredActivity expects filter to have no data authorities, " +
6736 "paths, schemes or types.");
6737 }
6738 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006739 if (mContext.checkCallingOrSelfPermission(
6740 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6741 != PackageManager.PERMISSION_GRANTED) {
6742 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6743 < Build.VERSION_CODES.FROYO) {
6744 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6745 + Binder.getCallingUid());
6746 return;
6747 }
6748 mContext.enforceCallingOrSelfPermission(
6749 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6750 }
6751
Satish Sampath8dbe6122009-06-02 23:35:54 +01006752 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6753 String action = filter.getAction(0);
6754 String category = filter.getCategory(0);
6755 while (it.hasNext()) {
6756 PreferredActivity pa = it.next();
6757 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6758 it.remove();
6759 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6760 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6761 }
6762 }
6763 addPreferredActivity(filter, match, set, activity);
6764 }
6765 }
6766
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006769 int uid = Binder.getCallingUid();
6770 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006771 if (pkg == null || pkg.applicationInfo.uid != uid) {
6772 if (mContext.checkCallingOrSelfPermission(
6773 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6774 != PackageManager.PERMISSION_GRANTED) {
6775 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6776 < Build.VERSION_CODES.FROYO) {
6777 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6778 + Binder.getCallingUid());
6779 return;
6780 }
6781 mContext.enforceCallingOrSelfPermission(
6782 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6783 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006784 }
6785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006786 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006787 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006788 }
6789 }
6790 }
6791
6792 boolean clearPackagePreferredActivitiesLP(String packageName) {
6793 boolean changed = false;
6794 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6795 while (it.hasNext()) {
6796 PreferredActivity pa = it.next();
6797 if (pa.mActivity.getPackageName().equals(packageName)) {
6798 it.remove();
6799 changed = true;
6800 }
6801 }
6802 return changed;
6803 }
6804
6805 public int getPreferredActivities(List<IntentFilter> outFilters,
6806 List<ComponentName> outActivities, String packageName) {
6807
6808 int num = 0;
6809 synchronized (mPackages) {
6810 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6811 while (it.hasNext()) {
6812 PreferredActivity pa = it.next();
6813 if (packageName == null
6814 || pa.mActivity.getPackageName().equals(packageName)) {
6815 if (outFilters != null) {
6816 outFilters.add(new IntentFilter(pa));
6817 }
6818 if (outActivities != null) {
6819 outActivities.add(pa.mActivity);
6820 }
6821 }
6822 }
6823 }
6824
6825 return num;
6826 }
6827
6828 public void setApplicationEnabledSetting(String appPackageName,
6829 int newState, int flags) {
6830 setEnabledSetting(appPackageName, null, newState, flags);
6831 }
6832
6833 public void setComponentEnabledSetting(ComponentName componentName,
6834 int newState, int flags) {
6835 setEnabledSetting(componentName.getPackageName(),
6836 componentName.getClassName(), newState, flags);
6837 }
6838
6839 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006840 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006841 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6842 || newState == COMPONENT_ENABLED_STATE_ENABLED
6843 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6844 throw new IllegalArgumentException("Invalid new component state: "
6845 + newState);
6846 }
6847 PackageSetting pkgSetting;
6848 final int uid = Binder.getCallingUid();
6849 final int permission = mContext.checkCallingPermission(
6850 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6851 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006852 boolean sendNow = false;
6853 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006854 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006855 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006856 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006857 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006858 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006859 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006860 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006861 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006862 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 }
6864 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006865 "Unknown component: " + packageName
6866 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867 }
6868 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6869 throw new SecurityException(
6870 "Permission Denial: attempt to change component state from pid="
6871 + Binder.getCallingPid()
6872 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6873 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006874 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006875 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006876 if (pkgSetting.enabled == newState) {
6877 // Nothing to do
6878 return;
6879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006880 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006881 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006882 } else {
6883 // We're dealing with a component level state change
6884 switch (newState) {
6885 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006886 if (!pkgSetting.enableComponentLP(className)) {
6887 return;
6888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006889 break;
6890 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006891 if (!pkgSetting.disableComponentLP(className)) {
6892 return;
6893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006894 break;
6895 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006896 if (!pkgSetting.restoreComponentLP(className)) {
6897 return;
6898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006899 break;
6900 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006901 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006902 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006903 }
6904 }
6905 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006906 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006907 components = mPendingBroadcasts.get(packageName);
6908 boolean newPackage = components == null;
6909 if (newPackage) {
6910 components = new ArrayList<String>();
6911 }
6912 if (!components.contains(componentName)) {
6913 components.add(componentName);
6914 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006915 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6916 sendNow = true;
6917 // Purge entry from pending broadcast list if another one exists already
6918 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006919 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006920 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006921 if (newPackage) {
6922 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006923 }
6924 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6925 // Schedule a message
6926 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6927 }
6928 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006929 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006930
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931 long callingId = Binder.clearCallingIdentity();
6932 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006933 if (sendNow) {
6934 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006935 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006937 } finally {
6938 Binder.restoreCallingIdentity(callingId);
6939 }
6940 }
6941
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006942 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006943 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6944 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6945 + " components=" + componentNames);
6946 Bundle extras = new Bundle(4);
6947 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6948 String nameList[] = new String[componentNames.size()];
6949 componentNames.toArray(nameList);
6950 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006951 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6952 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006953 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006954 }
6955
Jacek Surazski65e13172009-04-28 15:26:38 +02006956 public String getInstallerPackageName(String packageName) {
6957 synchronized (mPackages) {
6958 PackageSetting pkg = mSettings.mPackages.get(packageName);
6959 if (pkg == null) {
6960 throw new IllegalArgumentException("Unknown package: " + packageName);
6961 }
6962 return pkg.installerPackageName;
6963 }
6964 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006965
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006966 public int getApplicationEnabledSetting(String appPackageName) {
6967 synchronized (mPackages) {
6968 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6969 if (pkg == null) {
6970 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6971 }
6972 return pkg.enabled;
6973 }
6974 }
6975
6976 public int getComponentEnabledSetting(ComponentName componentName) {
6977 synchronized (mPackages) {
6978 final String packageNameStr = componentName.getPackageName();
6979 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6980 if (pkg == null) {
6981 throw new IllegalArgumentException("Unknown component: " + componentName);
6982 }
6983 final String classNameStr = componentName.getClassName();
6984 return pkg.currentEnabledStateLP(classNameStr);
6985 }
6986 }
6987
6988 public void enterSafeMode() {
6989 if (!mSystemReady) {
6990 mSafeMode = true;
6991 }
6992 }
6993
6994 public void systemReady() {
6995 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006996
6997 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006998 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006999 mContext.getContentResolver(),
7000 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007001 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007002 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07007003 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07007004 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007005 }
7006
7007 public boolean isSafeMode() {
7008 return mSafeMode;
7009 }
7010
7011 public boolean hasSystemUidErrors() {
7012 return mHasSystemUidErrors;
7013 }
7014
7015 static String arrayToString(int[] array) {
7016 StringBuffer buf = new StringBuffer(128);
7017 buf.append('[');
7018 if (array != null) {
7019 for (int i=0; i<array.length; i++) {
7020 if (i > 0) buf.append(", ");
7021 buf.append(array[i]);
7022 }
7023 }
7024 buf.append(']');
7025 return buf.toString();
7026 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007028 @Override
7029 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
7030 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
7031 != PackageManager.PERMISSION_GRANTED) {
7032 pw.println("Permission Denial: can't dump ActivityManager from from pid="
7033 + Binder.getCallingPid()
7034 + ", uid=" + Binder.getCallingUid()
7035 + " without permission "
7036 + android.Manifest.permission.DUMP);
7037 return;
7038 }
7039
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007040 String packageName = null;
7041
7042 int opti = 0;
7043 while (opti < args.length) {
7044 String opt = args[opti];
7045 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
7046 break;
7047 }
7048 opti++;
7049 if ("-a".equals(opt)) {
7050 // Right now we only know how to print all.
7051 } else if ("-h".equals(opt)) {
7052 pw.println("Package manager dump options:");
7053 pw.println(" [-h] [cmd] ...");
7054 pw.println(" cmd may be one of:");
7055 pw.println(" [package.name]: info about given package");
7056 return;
7057 } else {
7058 pw.println("Unknown argument: " + opt + "; use -h for help");
7059 }
7060 }
7061
7062 // Is the caller requesting to dump a particular piece of data?
7063 if (opti < args.length) {
7064 String cmd = args[opti];
7065 opti++;
7066 // Is this a package name?
7067 if ("android".equals(cmd) || cmd.contains(".")) {
7068 packageName = cmd;
7069 }
7070 }
7071
7072 boolean printedTitle = false;
7073
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007074 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007075 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
7076 printedTitle = true;
7077 }
7078 if (mReceivers.dump(pw, printedTitle
7079 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
7080 " ", packageName)) {
7081 printedTitle = true;
7082 }
7083 if (mServices.dump(pw, printedTitle
7084 ? "\nService Resolver Table:" : "Service Resolver Table:",
7085 " ", packageName)) {
7086 printedTitle = true;
7087 }
7088 if (mSettings.mPreferredActivities.dump(pw, printedTitle
7089 ? "\nPreferred Activities:" : "Preferred Activities:",
7090 " ", packageName)) {
7091 printedTitle = true;
7092 }
7093 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007094 {
7095 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007096 if (packageName != null && !packageName.equals(p.sourcePackage)) {
7097 continue;
7098 }
7099 if (!printedSomething) {
7100 if (printedTitle) pw.println(" ");
7101 pw.println("Permissions:");
7102 printedSomething = true;
7103 printedTitle = true;
7104 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007105 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
7106 pw.print(Integer.toHexString(System.identityHashCode(p)));
7107 pw.println("):");
7108 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
7109 pw.print(" uid="); pw.print(p.uid);
7110 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007111 pw.print(" type="); pw.print(p.type);
7112 pw.print(" prot="); pw.println(p.protectionLevel);
7113 if (p.packageSetting != null) {
7114 pw.print(" packageSetting="); pw.println(p.packageSetting);
7115 }
7116 if (p.perm != null) {
7117 pw.print(" perm="); pw.println(p.perm);
7118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007119 }
7120 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007121 printedSomething = false;
7122 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007123 {
7124 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007125 if (packageName != null && !packageName.equals(ps.realName)
7126 && !packageName.equals(ps.name)) {
7127 continue;
7128 }
7129 if (!printedSomething) {
7130 if (printedTitle) pw.println(" ");
7131 pw.println("Packages:");
7132 printedSomething = true;
7133 printedTitle = true;
7134 }
7135 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007136 pw.print(" Package [");
7137 pw.print(ps.realName != null ? ps.realName : ps.name);
7138 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007139 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7140 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007141 if (ps.realName != null) {
7142 pw.print(" compat name="); pw.println(ps.name);
7143 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007144 pw.print(" userId="); pw.print(ps.userId);
7145 pw.print(" gids="); pw.println(arrayToString(ps.gids));
7146 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7147 pw.print(" pkg="); pw.println(ps.pkg);
7148 pw.print(" codePath="); pw.println(ps.codePathString);
7149 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07007150 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007151 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007152 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007153 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007154 pw.print(" supportsScreens=[");
7155 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007156 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007157 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7158 if (!first) pw.print(", ");
7159 first = false;
7160 pw.print("small");
7161 }
7162 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007163 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007164 if (!first) pw.print(", ");
7165 first = false;
7166 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007167 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007168 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007169 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007170 if (!first) pw.print(", ");
7171 first = false;
7172 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007173 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007174 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007175 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007176 if (!first) pw.print(", ");
7177 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007178 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007179 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007180 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007181 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007182 if (!first) pw.print(", ");
7183 first = false;
7184 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007185 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007186 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007187 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7188 if (!first) pw.print(", ");
7189 first = false;
7190 pw.print("anyDensity");
7191 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007192 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007193 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007194 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7195 pw.print(" signatures="); pw.println(ps.signatures);
7196 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007197 pw.print(" haveGids="); pw.println(ps.haveGids);
7198 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007199 pw.print(" installStatus="); pw.print(ps.installStatus);
7200 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007201 if (ps.disabledComponents.size() > 0) {
7202 pw.println(" disabledComponents:");
7203 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007204 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007205 }
7206 }
7207 if (ps.enabledComponents.size() > 0) {
7208 pw.println(" enabledComponents:");
7209 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007210 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007211 }
7212 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007213 if (ps.grantedPermissions.size() > 0) {
7214 pw.println(" grantedPermissions:");
7215 for (String s : ps.grantedPermissions) {
7216 pw.print(" "); pw.println(s);
7217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007219 }
7220 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007221 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007222 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007223 for (HashMap.Entry<String, String> e
7224 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007225 if (packageName != null && !packageName.equals(e.getKey())
7226 && !packageName.equals(e.getValue())) {
7227 continue;
7228 }
7229 if (!printedSomething) {
7230 if (printedTitle) pw.println(" ");
7231 pw.println("Renamed packages:");
7232 printedSomething = true;
7233 printedTitle = true;
7234 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007235 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7236 pw.println(e.getValue());
7237 }
7238 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007239 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007240 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007241 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007242 if (packageName != null && !packageName.equals(ps.realName)
7243 && !packageName.equals(ps.name)) {
7244 continue;
7245 }
7246 if (!printedSomething) {
7247 if (printedTitle) pw.println(" ");
7248 pw.println("Hidden system packages:");
7249 printedSomething = true;
7250 printedTitle = true;
7251 }
7252 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007253 pw.print(ps.realName != null ? ps.realName : ps.name);
7254 pw.print("] (");
7255 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7256 pw.println("):");
7257 if (ps.realName != null) {
7258 pw.print(" compat name="); pw.println(ps.name);
7259 }
7260 pw.print(" userId="); pw.println(ps.userId);
7261 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7262 pw.print(" codePath="); pw.println(ps.codePathString);
7263 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7264 }
7265 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007266 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007267 {
7268 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007269 if (packageName != null && su != packageSharedUser) {
7270 continue;
7271 }
7272 if (!printedSomething) {
7273 if (printedTitle) pw.println(" ");
7274 pw.println("Shared users:");
7275 printedSomething = true;
7276 printedTitle = true;
7277 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007278 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7279 pw.print(Integer.toHexString(System.identityHashCode(su)));
7280 pw.println("):");
7281 pw.print(" userId="); pw.print(su.userId);
7282 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007283 pw.println(" grantedPermissions:");
7284 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007285 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007287 }
7288 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007289
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007290 if (packageName == null) {
7291 if (printedTitle) pw.println(" ");
7292 printedTitle = true;
7293 pw.println("Settings parse messages:");
7294 pw.println(mSettings.mReadMessages.toString());
7295
7296 pw.println(" ");
7297 pw.println("Package warning messages:");
7298 File fname = getSettingsProblemFile();
7299 FileInputStream in;
7300 try {
7301 in = new FileInputStream(fname);
7302 int avail = in.available();
7303 byte[] data = new byte[avail];
7304 in.read(data);
7305 pw.println(new String(data));
7306 } catch (FileNotFoundException e) {
7307 } catch (IOException e) {
7308 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007309 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007311
7312 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007313 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007314 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007315 if (packageName != null && !packageName.equals(p.info.packageName)) {
7316 continue;
7317 }
7318 if (!printedSomething) {
7319 if (printedTitle) pw.println(" ");
7320 pw.println("Registered ContentProviders:");
7321 printedSomething = true;
7322 printedTitle = true;
7323 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007324 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007325 pw.println(p.toString());
7326 }
7327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007328 }
7329
7330 static final class BasePermission {
7331 final static int TYPE_NORMAL = 0;
7332 final static int TYPE_BUILTIN = 1;
7333 final static int TYPE_DYNAMIC = 2;
7334
7335 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007336 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007337 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007338 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007339 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007340 PackageParser.Permission perm;
7341 PermissionInfo pendingInfo;
7342 int uid;
7343 int[] gids;
7344
7345 BasePermission(String _name, String _sourcePackage, int _type) {
7346 name = _name;
7347 sourcePackage = _sourcePackage;
7348 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007349 // Default to most conservative protection level.
7350 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7351 }
7352
7353 public String toString() {
7354 return "BasePermission{"
7355 + Integer.toHexString(System.identityHashCode(this))
7356 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007357 }
7358 }
7359
7360 static class PackageSignatures {
7361 private Signature[] mSignatures;
7362
7363 PackageSignatures(Signature[] sigs) {
7364 assignSignatures(sigs);
7365 }
7366
7367 PackageSignatures() {
7368 }
7369
7370 void writeXml(XmlSerializer serializer, String tagName,
7371 ArrayList<Signature> pastSignatures) throws IOException {
7372 if (mSignatures == null) {
7373 return;
7374 }
7375 serializer.startTag(null, tagName);
7376 serializer.attribute(null, "count",
7377 Integer.toString(mSignatures.length));
7378 for (int i=0; i<mSignatures.length; i++) {
7379 serializer.startTag(null, "cert");
7380 final Signature sig = mSignatures[i];
7381 final int sigHash = sig.hashCode();
7382 final int numPast = pastSignatures.size();
7383 int j;
7384 for (j=0; j<numPast; j++) {
7385 Signature pastSig = pastSignatures.get(j);
7386 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7387 serializer.attribute(null, "index", Integer.toString(j));
7388 break;
7389 }
7390 }
7391 if (j >= numPast) {
7392 pastSignatures.add(sig);
7393 serializer.attribute(null, "index", Integer.toString(numPast));
7394 serializer.attribute(null, "key", sig.toCharsString());
7395 }
7396 serializer.endTag(null, "cert");
7397 }
7398 serializer.endTag(null, tagName);
7399 }
7400
7401 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7402 throws IOException, XmlPullParserException {
7403 String countStr = parser.getAttributeValue(null, "count");
7404 if (countStr == null) {
7405 reportSettingsProblem(Log.WARN,
7406 "Error in package manager settings: <signatures> has"
7407 + " no count at " + parser.getPositionDescription());
7408 XmlUtils.skipCurrentTag(parser);
7409 }
7410 final int count = Integer.parseInt(countStr);
7411 mSignatures = new Signature[count];
7412 int pos = 0;
7413
7414 int outerDepth = parser.getDepth();
7415 int type;
7416 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7417 && (type != XmlPullParser.END_TAG
7418 || parser.getDepth() > outerDepth)) {
7419 if (type == XmlPullParser.END_TAG
7420 || type == XmlPullParser.TEXT) {
7421 continue;
7422 }
7423
7424 String tagName = parser.getName();
7425 if (tagName.equals("cert")) {
7426 if (pos < count) {
7427 String index = parser.getAttributeValue(null, "index");
7428 if (index != null) {
7429 try {
7430 int idx = Integer.parseInt(index);
7431 String key = parser.getAttributeValue(null, "key");
7432 if (key == null) {
7433 if (idx >= 0 && idx < pastSignatures.size()) {
7434 Signature sig = pastSignatures.get(idx);
7435 if (sig != null) {
7436 mSignatures[pos] = pastSignatures.get(idx);
7437 pos++;
7438 } else {
7439 reportSettingsProblem(Log.WARN,
7440 "Error in package manager settings: <cert> "
7441 + "index " + index + " is not defined at "
7442 + parser.getPositionDescription());
7443 }
7444 } else {
7445 reportSettingsProblem(Log.WARN,
7446 "Error in package manager settings: <cert> "
7447 + "index " + index + " is out of bounds at "
7448 + parser.getPositionDescription());
7449 }
7450 } else {
7451 while (pastSignatures.size() <= idx) {
7452 pastSignatures.add(null);
7453 }
7454 Signature sig = new Signature(key);
7455 pastSignatures.set(idx, sig);
7456 mSignatures[pos] = sig;
7457 pos++;
7458 }
7459 } catch (NumberFormatException e) {
7460 reportSettingsProblem(Log.WARN,
7461 "Error in package manager settings: <cert> "
7462 + "index " + index + " is not a number at "
7463 + parser.getPositionDescription());
7464 }
7465 } else {
7466 reportSettingsProblem(Log.WARN,
7467 "Error in package manager settings: <cert> has"
7468 + " no index at " + parser.getPositionDescription());
7469 }
7470 } else {
7471 reportSettingsProblem(Log.WARN,
7472 "Error in package manager settings: too "
7473 + "many <cert> tags, expected " + count
7474 + " at " + parser.getPositionDescription());
7475 }
7476 } else {
7477 reportSettingsProblem(Log.WARN,
7478 "Unknown element under <cert>: "
7479 + parser.getName());
7480 }
7481 XmlUtils.skipCurrentTag(parser);
7482 }
7483
7484 if (pos < count) {
7485 // Should never happen -- there is an error in the written
7486 // settings -- but if it does we don't want to generate
7487 // a bad array.
7488 Signature[] newSigs = new Signature[pos];
7489 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7490 mSignatures = newSigs;
7491 }
7492 }
7493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007494 private void assignSignatures(Signature[] sigs) {
7495 if (sigs == null) {
7496 mSignatures = null;
7497 return;
7498 }
7499 mSignatures = new Signature[sigs.length];
7500 for (int i=0; i<sigs.length; i++) {
7501 mSignatures[i] = sigs[i];
7502 }
7503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007505 @Override
7506 public String toString() {
7507 StringBuffer buf = new StringBuffer(128);
7508 buf.append("PackageSignatures{");
7509 buf.append(Integer.toHexString(System.identityHashCode(this)));
7510 buf.append(" [");
7511 if (mSignatures != null) {
7512 for (int i=0; i<mSignatures.length; i++) {
7513 if (i > 0) buf.append(", ");
7514 buf.append(Integer.toHexString(
7515 System.identityHashCode(mSignatures[i])));
7516 }
7517 }
7518 buf.append("]}");
7519 return buf.toString();
7520 }
7521 }
7522
7523 static class PreferredActivity extends IntentFilter {
7524 final int mMatch;
7525 final String[] mSetPackages;
7526 final String[] mSetClasses;
7527 final String[] mSetComponents;
7528 final ComponentName mActivity;
7529 final String mShortActivity;
7530 String mParseError;
7531
7532 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7533 ComponentName activity) {
7534 super(filter);
7535 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7536 mActivity = activity;
7537 mShortActivity = activity.flattenToShortString();
7538 mParseError = null;
7539 if (set != null) {
7540 final int N = set.length;
7541 String[] myPackages = new String[N];
7542 String[] myClasses = new String[N];
7543 String[] myComponents = new String[N];
7544 for (int i=0; i<N; i++) {
7545 ComponentName cn = set[i];
7546 if (cn == null) {
7547 mSetPackages = null;
7548 mSetClasses = null;
7549 mSetComponents = null;
7550 return;
7551 }
7552 myPackages[i] = cn.getPackageName().intern();
7553 myClasses[i] = cn.getClassName().intern();
7554 myComponents[i] = cn.flattenToShortString().intern();
7555 }
7556 mSetPackages = myPackages;
7557 mSetClasses = myClasses;
7558 mSetComponents = myComponents;
7559 } else {
7560 mSetPackages = null;
7561 mSetClasses = null;
7562 mSetComponents = null;
7563 }
7564 }
7565
7566 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7567 IOException {
7568 mShortActivity = parser.getAttributeValue(null, "name");
7569 mActivity = ComponentName.unflattenFromString(mShortActivity);
7570 if (mActivity == null) {
7571 mParseError = "Bad activity name " + mShortActivity;
7572 }
7573 String matchStr = parser.getAttributeValue(null, "match");
7574 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7575 String setCountStr = parser.getAttributeValue(null, "set");
7576 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7577
7578 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7579 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7580 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7581
7582 int setPos = 0;
7583
7584 int outerDepth = parser.getDepth();
7585 int type;
7586 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7587 && (type != XmlPullParser.END_TAG
7588 || parser.getDepth() > outerDepth)) {
7589 if (type == XmlPullParser.END_TAG
7590 || type == XmlPullParser.TEXT) {
7591 continue;
7592 }
7593
7594 String tagName = parser.getName();
7595 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7596 // + parser.getDepth() + " tag=" + tagName);
7597 if (tagName.equals("set")) {
7598 String name = parser.getAttributeValue(null, "name");
7599 if (name == null) {
7600 if (mParseError == null) {
7601 mParseError = "No name in set tag in preferred activity "
7602 + mShortActivity;
7603 }
7604 } else if (setPos >= setCount) {
7605 if (mParseError == null) {
7606 mParseError = "Too many set tags in preferred activity "
7607 + mShortActivity;
7608 }
7609 } else {
7610 ComponentName cn = ComponentName.unflattenFromString(name);
7611 if (cn == null) {
7612 if (mParseError == null) {
7613 mParseError = "Bad set name " + name + " in preferred activity "
7614 + mShortActivity;
7615 }
7616 } else {
7617 myPackages[setPos] = cn.getPackageName();
7618 myClasses[setPos] = cn.getClassName();
7619 myComponents[setPos] = name;
7620 setPos++;
7621 }
7622 }
7623 XmlUtils.skipCurrentTag(parser);
7624 } else if (tagName.equals("filter")) {
7625 //Log.i(TAG, "Starting to parse filter...");
7626 readFromXml(parser);
7627 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7628 // + parser.getDepth() + " tag=" + parser.getName());
7629 } else {
7630 reportSettingsProblem(Log.WARN,
7631 "Unknown element under <preferred-activities>: "
7632 + parser.getName());
7633 XmlUtils.skipCurrentTag(parser);
7634 }
7635 }
7636
7637 if (setPos != setCount) {
7638 if (mParseError == null) {
7639 mParseError = "Not enough set tags (expected " + setCount
7640 + " but found " + setPos + ") in " + mShortActivity;
7641 }
7642 }
7643
7644 mSetPackages = myPackages;
7645 mSetClasses = myClasses;
7646 mSetComponents = myComponents;
7647 }
7648
7649 public void writeToXml(XmlSerializer serializer) throws IOException {
7650 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7651 serializer.attribute(null, "name", mShortActivity);
7652 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7653 serializer.attribute(null, "set", Integer.toString(NS));
7654 for (int s=0; s<NS; s++) {
7655 serializer.startTag(null, "set");
7656 serializer.attribute(null, "name", mSetComponents[s]);
7657 serializer.endTag(null, "set");
7658 }
7659 serializer.startTag(null, "filter");
7660 super.writeToXml(serializer);
7661 serializer.endTag(null, "filter");
7662 }
7663
7664 boolean sameSet(List<ResolveInfo> query, int priority) {
7665 if (mSetPackages == null) return false;
7666 final int NQ = query.size();
7667 final int NS = mSetPackages.length;
7668 int numMatch = 0;
7669 for (int i=0; i<NQ; i++) {
7670 ResolveInfo ri = query.get(i);
7671 if (ri.priority != priority) continue;
7672 ActivityInfo ai = ri.activityInfo;
7673 boolean good = false;
7674 for (int j=0; j<NS; j++) {
7675 if (mSetPackages[j].equals(ai.packageName)
7676 && mSetClasses[j].equals(ai.name)) {
7677 numMatch++;
7678 good = true;
7679 break;
7680 }
7681 }
7682 if (!good) return false;
7683 }
7684 return numMatch == NS;
7685 }
7686 }
7687
7688 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007689 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007691 HashSet<String> grantedPermissions = new HashSet<String>();
7692 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007694 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007695 setFlags(pkgFlags);
7696 }
7697
7698 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007699 this.pkgFlags = pkgFlags & (
7700 ApplicationInfo.FLAG_SYSTEM |
7701 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007702 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007703 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007704 }
7705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 /**
7708 * Settings base class for pending and resolved classes.
7709 */
7710 static class PackageSettingBase extends GrantedPermissions {
7711 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007712 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007713 File codePath;
7714 String codePathString;
7715 File resourcePath;
7716 String resourcePathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007717 String obbPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007718 private long timeStamp;
7719 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007720 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007721
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007722 boolean uidError;
7723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007724 PackageSignatures signatures = new PackageSignatures();
7725
7726 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007727 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 /* Explicitly disabled components */
7730 HashSet<String> disabledComponents = new HashSet<String>(0);
7731 /* Explicitly enabled components */
7732 HashSet<String> enabledComponents = new HashSet<String>(0);
7733 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7734 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007735
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007736 PackageSettingBase origPackage;
7737
Jacek Surazski65e13172009-04-28 15:26:38 +02007738 /* package name of the app that installed this package */
7739 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007740
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007741 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007742 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 super(pkgFlags);
7744 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007745 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007746 init(codePath, resourcePath, pVersionCode);
7747 }
7748
7749 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007750 this.codePath = codePath;
7751 this.codePathString = codePath.toString();
7752 this.resourcePath = resourcePath;
7753 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007754 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007755 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007756
Jacek Surazski65e13172009-04-28 15:26:38 +02007757 public void setInstallerPackageName(String packageName) {
7758 installerPackageName = packageName;
7759 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007760
Jacek Surazski65e13172009-04-28 15:26:38 +02007761 String getInstallerPackageName() {
7762 return installerPackageName;
7763 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007765 public void setInstallStatus(int newStatus) {
7766 installStatus = newStatus;
7767 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007769 public int getInstallStatus() {
7770 return installStatus;
7771 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 public void setTimeStamp(long newStamp) {
7774 if (newStamp != timeStamp) {
7775 timeStamp = newStamp;
7776 timeStampString = Long.toString(newStamp);
7777 }
7778 }
7779
7780 public void setTimeStamp(long newStamp, String newStampStr) {
7781 timeStamp = newStamp;
7782 timeStampString = newStampStr;
7783 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007785 public long getTimeStamp() {
7786 return timeStamp;
7787 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007789 public String getTimeStampStr() {
7790 return timeStampString;
7791 }
7792
7793 public void copyFrom(PackageSettingBase base) {
7794 grantedPermissions = base.grantedPermissions;
7795 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 timeStamp = base.timeStamp;
7798 timeStampString = base.timeStampString;
7799 signatures = base.signatures;
7800 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007801 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007802 disabledComponents = base.disabledComponents;
7803 enabledComponents = base.enabledComponents;
7804 enabled = base.enabled;
7805 installStatus = base.installStatus;
7806 }
7807
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007808 boolean enableComponentLP(String componentClassName) {
7809 boolean changed = disabledComponents.remove(componentClassName);
7810 changed |= enabledComponents.add(componentClassName);
7811 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812 }
7813
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007814 boolean disableComponentLP(String componentClassName) {
7815 boolean changed = enabledComponents.remove(componentClassName);
7816 changed |= disabledComponents.add(componentClassName);
7817 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 }
7819
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007820 boolean restoreComponentLP(String componentClassName) {
7821 boolean changed = enabledComponents.remove(componentClassName);
7822 changed |= disabledComponents.remove(componentClassName);
7823 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007824 }
7825
7826 int currentEnabledStateLP(String componentName) {
7827 if (enabledComponents.contains(componentName)) {
7828 return COMPONENT_ENABLED_STATE_ENABLED;
7829 } else if (disabledComponents.contains(componentName)) {
7830 return COMPONENT_ENABLED_STATE_DISABLED;
7831 } else {
7832 return COMPONENT_ENABLED_STATE_DEFAULT;
7833 }
7834 }
7835 }
7836
7837 /**
7838 * Settings data for a particular package we know about.
7839 */
7840 static final class PackageSetting extends PackageSettingBase {
7841 int userId;
7842 PackageParser.Package pkg;
7843 SharedUserSetting sharedUser;
7844
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007845 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007846 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007847 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007848 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 @Override
7851 public String toString() {
7852 return "PackageSetting{"
7853 + Integer.toHexString(System.identityHashCode(this))
7854 + " " + name + "/" + userId + "}";
7855 }
7856 }
7857
7858 /**
7859 * Settings data for a particular shared user ID we know about.
7860 */
7861 static final class SharedUserSetting extends GrantedPermissions {
7862 final String name;
7863 int userId;
7864 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7865 final PackageSignatures signatures = new PackageSignatures();
7866
7867 SharedUserSetting(String _name, int _pkgFlags) {
7868 super(_pkgFlags);
7869 name = _name;
7870 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 @Override
7873 public String toString() {
7874 return "SharedUserSetting{"
7875 + Integer.toHexString(System.identityHashCode(this))
7876 + " " + name + "/" + userId + "}";
7877 }
7878 }
7879
7880 /**
7881 * Holds information about dynamic settings.
7882 */
7883 private static final class Settings {
7884 private final File mSettingsFilename;
7885 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007886 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007887 private final HashMap<String, PackageSetting> mPackages =
7888 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007889 // List of replaced system applications
7890 final HashMap<String, PackageSetting> mDisabledSysPackages =
7891 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007892
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007893 // These are the last platform API version we were using for
7894 // the apps installed on internal and external storage. It is
7895 // used to grant newer permissions one time during a system upgrade.
7896 int mInternalSdkPlatform;
7897 int mExternalSdkPlatform;
7898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 // The user's preferred activities associated with particular intent
7900 // filters.
7901 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7902 new IntentResolver<PreferredActivity, PreferredActivity>() {
7903 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007904 protected String packageForFilter(PreferredActivity filter) {
7905 return filter.mActivity.getPackageName();
7906 }
7907 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007908 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007909 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007910 out.print(prefix); out.print(
7911 Integer.toHexString(System.identityHashCode(filter)));
7912 out.print(' ');
7913 out.print(filter.mActivity.flattenToShortString());
7914 out.print(" match=0x");
7915 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007916 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007917 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007918 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007919 out.print(prefix); out.print(" ");
7920 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 }
7922 }
7923 }
7924 };
7925 private final HashMap<String, SharedUserSetting> mSharedUsers =
7926 new HashMap<String, SharedUserSetting>();
7927 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7928 private final SparseArray<Object> mOtherUserIds =
7929 new SparseArray<Object>();
7930
7931 // For reading/writing settings file.
7932 private final ArrayList<Signature> mPastSignatures =
7933 new ArrayList<Signature>();
7934
7935 // Mapping from permission names to info about them.
7936 final HashMap<String, BasePermission> mPermissions =
7937 new HashMap<String, BasePermission>();
7938
7939 // Mapping from permission tree names to info about them.
7940 final HashMap<String, BasePermission> mPermissionTrees =
7941 new HashMap<String, BasePermission>();
7942
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007943 // Packages that have been uninstalled and still need their external
7944 // storage data deleted.
7945 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7946
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007947 // Packages that have been renamed since they were first installed.
7948 // Keys are the new names of the packages, values are the original
7949 // names. The packages appear everwhere else under their original
7950 // names.
7951 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007953 private final StringBuilder mReadMessages = new StringBuilder();
7954
7955 private static final class PendingPackage extends PackageSettingBase {
7956 final int sharedId;
7957
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007958 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007959 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007960 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007961 this.sharedId = sharedId;
7962 }
7963 }
7964 private final ArrayList<PendingPackage> mPendingPackages
7965 = new ArrayList<PendingPackage>();
7966
7967 Settings() {
7968 File dataDir = Environment.getDataDirectory();
7969 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007970 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7971 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007972 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007973 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007974 FileUtils.setPermissions(systemDir.toString(),
7975 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7976 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7977 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007978 FileUtils.setPermissions(systemSecureDir.toString(),
7979 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7980 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7981 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007982 mSettingsFilename = new File(systemDir, "packages.xml");
7983 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007984 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007985 }
7986
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007987 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007988 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007989 int pkgFlags, boolean create, boolean add) {
7990 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007991 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007992 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007993 return p;
7994 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007995
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007996 PackageSetting peekPackageLP(String name) {
7997 return mPackages.get(name);
7998 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007999 PackageSetting p = mPackages.get(name);
8000 if (p != null && p.codePath.getPath().equals(codePath)) {
8001 return p;
8002 }
8003 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008004 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008006
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008007 void setInstallStatus(String pkgName, int status) {
8008 PackageSetting p = mPackages.get(pkgName);
8009 if(p != null) {
8010 if(p.getInstallStatus() != status) {
8011 p.setInstallStatus(status);
8012 }
8013 }
8014 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008015
Jacek Surazski65e13172009-04-28 15:26:38 +02008016 void setInstallerPackageName(String pkgName,
8017 String installerPkgName) {
8018 PackageSetting p = mPackages.get(pkgName);
8019 if(p != null) {
8020 p.setInstallerPackageName(installerPkgName);
8021 }
8022 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008023
Jacek Surazski65e13172009-04-28 15:26:38 +02008024 String getInstallerPackageName(String pkgName) {
8025 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008026 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02008027 }
8028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008029 int getInstallStatus(String pkgName) {
8030 PackageSetting p = mPackages.get(pkgName);
8031 if(p != null) {
8032 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008034 return -1;
8035 }
8036
8037 SharedUserSetting getSharedUserLP(String name,
8038 int pkgFlags, boolean create) {
8039 SharedUserSetting s = mSharedUsers.get(name);
8040 if (s == null) {
8041 if (!create) {
8042 return null;
8043 }
8044 s = new SharedUserSetting(name, pkgFlags);
8045 if (MULTIPLE_APPLICATION_UIDS) {
8046 s.userId = newUserIdLP(s);
8047 } else {
8048 s.userId = FIRST_APPLICATION_UID;
8049 }
8050 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
8051 // < 0 means we couldn't assign a userid; fall out and return
8052 // s, which is currently null
8053 if (s.userId >= 0) {
8054 mSharedUsers.put(name, s);
8055 }
8056 }
8057
8058 return s;
8059 }
8060
8061 int disableSystemPackageLP(String name) {
8062 PackageSetting p = mPackages.get(name);
8063 if(p == null) {
8064 Log.w(TAG, "Package:"+name+" is not an installed package");
8065 return -1;
8066 }
8067 PackageSetting dp = mDisabledSysPackages.get(name);
8068 // always make sure the system package code and resource paths dont change
8069 if(dp == null) {
8070 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8071 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8072 }
8073 mDisabledSysPackages.put(name, p);
8074 }
8075 return removePackageLP(name);
8076 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008078 PackageSetting enableSystemPackageLP(String name) {
8079 PackageSetting p = mDisabledSysPackages.get(name);
8080 if(p == null) {
8081 Log.w(TAG, "Package:"+name+" is not disabled");
8082 return null;
8083 }
8084 // Reset flag in ApplicationInfo object
8085 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
8086 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
8087 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008088 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008089 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008090 mDisabledSysPackages.remove(name);
8091 return ret;
8092 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008093
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008094 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008095 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008096 PackageSetting p = mPackages.get(name);
8097 if (p != null) {
8098 if (p.userId == uid) {
8099 return p;
8100 }
8101 reportSettingsProblem(Log.ERROR,
8102 "Adding duplicate package, keeping first: " + name);
8103 return null;
8104 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008105 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008106 p.userId = uid;
8107 if (addUserIdLP(uid, p, name)) {
8108 mPackages.put(name, p);
8109 return p;
8110 }
8111 return null;
8112 }
8113
8114 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
8115 SharedUserSetting s = mSharedUsers.get(name);
8116 if (s != null) {
8117 if (s.userId == uid) {
8118 return s;
8119 }
8120 reportSettingsProblem(Log.ERROR,
8121 "Adding duplicate shared user, keeping first: " + name);
8122 return null;
8123 }
8124 s = new SharedUserSetting(name, pkgFlags);
8125 s.userId = uid;
8126 if (addUserIdLP(uid, s, name)) {
8127 mSharedUsers.put(name, s);
8128 return s;
8129 }
8130 return null;
8131 }
8132
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008133 // Transfer ownership of permissions from one package to another.
8134 private void transferPermissions(String origPkg, String newPkg) {
8135 // Transfer ownership of permissions to the new package.
8136 for (int i=0; i<2; i++) {
8137 HashMap<String, BasePermission> permissions =
8138 i == 0 ? mPermissionTrees : mPermissions;
8139 for (BasePermission bp : permissions.values()) {
8140 if (origPkg.equals(bp.sourcePackage)) {
8141 if (DEBUG_UPGRADE) Log.v(TAG,
8142 "Moving permission " + bp.name
8143 + " from pkg " + bp.sourcePackage
8144 + " to " + newPkg);
8145 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008146 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008147 bp.perm = null;
8148 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008149 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008150 }
8151 bp.uid = 0;
8152 bp.gids = null;
8153 }
8154 }
8155 }
8156 }
8157
8158 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008159 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008160 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008161 PackageSetting p = mPackages.get(name);
8162 if (p != null) {
8163 if (!p.codePath.equals(codePath)) {
8164 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008165 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008166 // This is an updated system app with versions in both system
8167 // and data partition. Just let the most recent version
8168 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008169 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008170 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008171 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008172 // Just a change in the code path is not an issue, but
8173 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008174 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008175 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008176 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008177 }
8178 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008179 reportSettingsProblem(Log.WARN,
8180 "Package " + name + " shared user changed from "
8181 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8182 + " to "
8183 + (sharedUser != null ? sharedUser.name : "<nothing>")
8184 + "; replacing with new");
8185 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008186 } else {
8187 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8188 // If what we are scanning is a system package, then
8189 // make it so, regardless of whether it was previously
8190 // installed only in the data partition.
8191 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8192 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008193 }
8194 }
8195 if (p == null) {
8196 // Create a new PackageSettings entry. this can end up here because
8197 // of code path mismatch or user id mismatch of an updated system partition
8198 if (!create) {
8199 return null;
8200 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008201 if (origPackage != null) {
8202 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008203 p = new PackageSetting(origPackage.name, name, codePath,
8204 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008205 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8206 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008207 // Note that we will retain the new package's signature so
8208 // that we can keep its data.
8209 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008210 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008211 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008212 p.sharedUser = origPackage.sharedUser;
8213 p.userId = origPackage.userId;
8214 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008215 mRenamedPackages.put(name, origPackage.name);
8216 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008217 // Update new package state.
8218 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008219 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008220 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008221 p.setTimeStamp(codePath.lastModified());
8222 p.sharedUser = sharedUser;
8223 if (sharedUser != null) {
8224 p.userId = sharedUser.userId;
8225 } else if (MULTIPLE_APPLICATION_UIDS) {
8226 // Clone the setting here for disabled system packages
8227 PackageSetting dis = mDisabledSysPackages.get(name);
8228 if (dis != null) {
8229 // For disabled packages a new setting is created
8230 // from the existing user id. This still has to be
8231 // added to list of user id's
8232 // Copy signatures from previous setting
8233 if (dis.signatures.mSignatures != null) {
8234 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8235 }
8236 p.userId = dis.userId;
8237 // Clone permissions
8238 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008239 // Clone component info
8240 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8241 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8242 // Add new setting to list of user ids
8243 addUserIdLP(p.userId, p, name);
8244 } else {
8245 // Assign new user id
8246 p.userId = newUserIdLP(p);
8247 }
8248 } else {
8249 p.userId = FIRST_APPLICATION_UID;
8250 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008251 }
8252 if (p.userId < 0) {
8253 reportSettingsProblem(Log.WARN,
8254 "Package " + name + " could not be assigned a valid uid");
8255 return null;
8256 }
8257 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008258 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008260 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008261 }
8262 }
8263 return p;
8264 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008265
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008266 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008267 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008268 pkg.mSetEnabled = p.enabled;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008269 String codePath = pkg.applicationInfo.sourceDir;
8270 String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008271 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008272 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008273 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008274 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008275 p.codePath = new File(codePath);
8276 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008277 }
8278 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008279 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008280 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008281 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008282 p.resourcePath = new File(resourcePath);
8283 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008284 }
8285 // Update version code if needed
8286 if (pkg.mVersionCode != p.versionCode) {
8287 p.versionCode = pkg.mVersionCode;
8288 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008289 // Update signatures if needed.
8290 if (p.signatures.mSignatures == null) {
8291 p.signatures.assignSignatures(pkg.mSignatures);
8292 }
8293 // If this app defines a shared user id initialize
8294 // the shared user signatures as well.
8295 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8296 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8297 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008298 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8299 }
8300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008301 // Utility method that adds a PackageSetting to mPackages and
8302 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008303 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 SharedUserSetting sharedUser) {
8305 mPackages.put(name, p);
8306 if (sharedUser != null) {
8307 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8308 reportSettingsProblem(Log.ERROR,
8309 "Package " + p.name + " was user "
8310 + p.sharedUser + " but is now " + sharedUser
8311 + "; I am not changing its files so it will probably fail!");
8312 p.sharedUser.packages.remove(p);
8313 } else if (p.userId != sharedUser.userId) {
8314 reportSettingsProblem(Log.ERROR,
8315 "Package " + p.name + " was user id " + p.userId
8316 + " but is now user " + sharedUser
8317 + " with id " + sharedUser.userId
8318 + "; I am not changing its files so it will probably fail!");
8319 }
8320
8321 sharedUser.packages.add(p);
8322 p.sharedUser = sharedUser;
8323 p.userId = sharedUser.userId;
8324 }
8325 }
8326
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008327 /*
8328 * Update the shared user setting when a package using
8329 * specifying the shared user id is removed. The gids
8330 * associated with each permission of the deleted package
8331 * are removed from the shared user's gid list only if its
8332 * not in use by other permissions of packages in the
8333 * shared user setting.
8334 */
8335 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008336 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008337 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008338 return;
8339 }
8340 // No sharedUserId
8341 if (deletedPs.sharedUser == null) {
8342 return;
8343 }
8344 SharedUserSetting sus = deletedPs.sharedUser;
8345 // Update permissions
8346 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8347 boolean used = false;
8348 if (!sus.grantedPermissions.contains (eachPerm)) {
8349 continue;
8350 }
8351 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008352 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008353 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008354 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008355 used = true;
8356 break;
8357 }
8358 }
8359 if (!used) {
8360 // can safely delete this permission from list
8361 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008362 }
8363 }
8364 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008365 int newGids[] = globalGids;
8366 for (String eachPerm : sus.grantedPermissions) {
8367 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008368 if (bp != null) {
8369 newGids = appendInts(newGids, bp.gids);
8370 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008371 }
8372 sus.gids = newGids;
8373 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008375 private int removePackageLP(String name) {
8376 PackageSetting p = mPackages.get(name);
8377 if (p != null) {
8378 mPackages.remove(name);
8379 if (p.sharedUser != null) {
8380 p.sharedUser.packages.remove(p);
8381 if (p.sharedUser.packages.size() == 0) {
8382 mSharedUsers.remove(p.sharedUser.name);
8383 removeUserIdLP(p.sharedUser.userId);
8384 return p.sharedUser.userId;
8385 }
8386 } else {
8387 removeUserIdLP(p.userId);
8388 return p.userId;
8389 }
8390 }
8391 return -1;
8392 }
8393
8394 private boolean addUserIdLP(int uid, Object obj, Object name) {
8395 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8396 return false;
8397 }
8398
8399 if (uid >= FIRST_APPLICATION_UID) {
8400 int N = mUserIds.size();
8401 final int index = uid - FIRST_APPLICATION_UID;
8402 while (index >= N) {
8403 mUserIds.add(null);
8404 N++;
8405 }
8406 if (mUserIds.get(index) != null) {
8407 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008408 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008409 + " name=" + name);
8410 return false;
8411 }
8412 mUserIds.set(index, obj);
8413 } else {
8414 if (mOtherUserIds.get(uid) != null) {
8415 reportSettingsProblem(Log.ERROR,
8416 "Adding duplicate shared id: " + uid
8417 + " name=" + name);
8418 return false;
8419 }
8420 mOtherUserIds.put(uid, obj);
8421 }
8422 return true;
8423 }
8424
8425 public Object getUserIdLP(int uid) {
8426 if (uid >= FIRST_APPLICATION_UID) {
8427 int N = mUserIds.size();
8428 final int index = uid - FIRST_APPLICATION_UID;
8429 return index < N ? mUserIds.get(index) : null;
8430 } else {
8431 return mOtherUserIds.get(uid);
8432 }
8433 }
8434
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008435 private Set<String> findPackagesWithFlag(int flag) {
8436 Set<String> ret = new HashSet<String>();
8437 for (PackageSetting ps : mPackages.values()) {
8438 // Has to match atleast all the flag bits set on flag
8439 if ((ps.pkgFlags & flag) == flag) {
8440 ret.add(ps.name);
8441 }
8442 }
8443 return ret;
8444 }
8445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008446 private void removeUserIdLP(int uid) {
8447 if (uid >= FIRST_APPLICATION_UID) {
8448 int N = mUserIds.size();
8449 final int index = uid - FIRST_APPLICATION_UID;
8450 if (index < N) mUserIds.set(index, null);
8451 } else {
8452 mOtherUserIds.remove(uid);
8453 }
8454 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456 void writeLP() {
8457 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8458
8459 // Keep the old settings around until we know the new ones have
8460 // been successfully written.
8461 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008462 // Presence of backup settings file indicates that we failed
8463 // to persist settings earlier. So preserve the older
8464 // backup for future reference since the current settings
8465 // might have been corrupted.
8466 if (!mBackupSettingsFilename.exists()) {
8467 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008468 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008469 return;
8470 }
8471 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008472 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008473 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008475 }
8476
8477 mPastSignatures.clear();
8478
8479 try {
8480 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8481
8482 //XmlSerializer serializer = XmlUtils.serializerInstance();
8483 XmlSerializer serializer = new FastXmlSerializer();
8484 serializer.setOutput(str, "utf-8");
8485 serializer.startDocument(null, true);
8486 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8487
8488 serializer.startTag(null, "packages");
8489
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008490 serializer.startTag(null, "last-platform-version");
8491 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8492 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8493 serializer.endTag(null, "last-platform-version");
8494
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 serializer.startTag(null, "permission-trees");
8496 for (BasePermission bp : mPermissionTrees.values()) {
8497 writePermission(serializer, bp);
8498 }
8499 serializer.endTag(null, "permission-trees");
8500
8501 serializer.startTag(null, "permissions");
8502 for (BasePermission bp : mPermissions.values()) {
8503 writePermission(serializer, bp);
8504 }
8505 serializer.endTag(null, "permissions");
8506
8507 for (PackageSetting pkg : mPackages.values()) {
8508 writePackage(serializer, pkg);
8509 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008510
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008511 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8512 writeDisabledSysPackage(serializer, pkg);
8513 }
8514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008515 serializer.startTag(null, "preferred-activities");
8516 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8517 serializer.startTag(null, "item");
8518 pa.writeToXml(serializer);
8519 serializer.endTag(null, "item");
8520 }
8521 serializer.endTag(null, "preferred-activities");
8522
8523 for (SharedUserSetting usr : mSharedUsers.values()) {
8524 serializer.startTag(null, "shared-user");
8525 serializer.attribute(null, "name", usr.name);
8526 serializer.attribute(null, "userId",
8527 Integer.toString(usr.userId));
8528 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8529 serializer.startTag(null, "perms");
8530 for (String name : usr.grantedPermissions) {
8531 serializer.startTag(null, "item");
8532 serializer.attribute(null, "name", name);
8533 serializer.endTag(null, "item");
8534 }
8535 serializer.endTag(null, "perms");
8536 serializer.endTag(null, "shared-user");
8537 }
8538
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008539 if (mPackagesToBeCleaned.size() > 0) {
8540 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8541 serializer.startTag(null, "cleaning-package");
8542 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8543 serializer.endTag(null, "cleaning-package");
8544 }
8545 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008546
8547 if (mRenamedPackages.size() > 0) {
8548 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8549 serializer.startTag(null, "renamed-package");
8550 serializer.attribute(null, "new", e.getKey());
8551 serializer.attribute(null, "old", e.getValue());
8552 serializer.endTag(null, "renamed-package");
8553 }
8554 }
8555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008556 serializer.endTag(null, "packages");
8557
8558 serializer.endDocument();
8559
8560 str.flush();
8561 str.close();
8562
8563 // New settings successfully written, old ones are no longer
8564 // needed.
8565 mBackupSettingsFilename.delete();
8566 FileUtils.setPermissions(mSettingsFilename.toString(),
8567 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8568 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8569 |FileUtils.S_IROTH,
8570 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008571
8572 // Write package list file now, use a JournaledFile.
8573 //
8574 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8575 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8576
8577 str = new FileOutputStream(journal.chooseForWrite());
8578 try {
8579 StringBuilder sb = new StringBuilder();
8580 for (PackageSetting pkg : mPackages.values()) {
8581 ApplicationInfo ai = pkg.pkg.applicationInfo;
8582 String dataPath = ai.dataDir;
8583 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8584
8585 // Avoid any application that has a space in its path
8586 // or that is handled by the system.
8587 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8588 continue;
8589
8590 // we store on each line the following information for now:
8591 //
8592 // pkgName - package name
8593 // userId - application-specific user id
8594 // debugFlag - 0 or 1 if the package is debuggable.
8595 // dataPath - path to package's data path
8596 //
8597 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8598 //
8599 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8600 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8601 // system/core/run-as/run-as.c
8602 //
8603 sb.setLength(0);
8604 sb.append(ai.packageName);
8605 sb.append(" ");
8606 sb.append((int)ai.uid);
8607 sb.append(isDebug ? " 1 " : " 0 ");
8608 sb.append(dataPath);
8609 sb.append("\n");
8610 str.write(sb.toString().getBytes());
8611 }
8612 str.flush();
8613 str.close();
8614 journal.commit();
8615 }
8616 catch (Exception e) {
8617 journal.rollback();
8618 }
8619
8620 FileUtils.setPermissions(mPackageListFilename.toString(),
8621 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8622 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8623 |FileUtils.S_IROTH,
8624 -1, -1);
8625
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008626 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008627
8628 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008629 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 -08008630 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008631 Slog.w(TAG, "Unable to write package manager settings, current changes will be lost at reboot", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008632 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008633 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008634 if (mSettingsFilename.exists()) {
8635 if (!mSettingsFilename.delete()) {
8636 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8637 }
8638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639 //Debug.stopMethodTracing();
8640 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008641
8642 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008643 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008644 serializer.startTag(null, "updated-package");
8645 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008646 if (pkg.realName != null) {
8647 serializer.attribute(null, "realName", pkg.realName);
8648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008649 serializer.attribute(null, "codePath", pkg.codePathString);
8650 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008651 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008652 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8653 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8654 }
8655 if (pkg.sharedUser == null) {
8656 serializer.attribute(null, "userId",
8657 Integer.toString(pkg.userId));
8658 } else {
8659 serializer.attribute(null, "sharedUserId",
8660 Integer.toString(pkg.userId));
8661 }
8662 serializer.startTag(null, "perms");
8663 if (pkg.sharedUser == null) {
8664 // If this is a shared user, the permissions will
8665 // be written there. We still need to write an
8666 // empty permissions list so permissionsFixed will
8667 // be set.
8668 for (final String name : pkg.grantedPermissions) {
8669 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008670 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008671 // We only need to write signature or system permissions but this wont
8672 // match the semantics of grantedPermissions. So write all permissions.
8673 serializer.startTag(null, "item");
8674 serializer.attribute(null, "name", name);
8675 serializer.endTag(null, "item");
8676 }
8677 }
8678 }
8679 serializer.endTag(null, "perms");
8680 serializer.endTag(null, "updated-package");
8681 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008682
8683 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008684 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008685 serializer.startTag(null, "package");
8686 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008687 if (pkg.realName != null) {
8688 serializer.attribute(null, "realName", pkg.realName);
8689 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008690 serializer.attribute(null, "codePath", pkg.codePathString);
8691 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8692 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8693 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008694 serializer.attribute(null, "flags",
8695 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008696 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008697 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008698 if (pkg.sharedUser == null) {
8699 serializer.attribute(null, "userId",
8700 Integer.toString(pkg.userId));
8701 } else {
8702 serializer.attribute(null, "sharedUserId",
8703 Integer.toString(pkg.userId));
8704 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008705 if (pkg.uidError) {
8706 serializer.attribute(null, "uidError", "true");
8707 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008708 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8709 serializer.attribute(null, "enabled",
8710 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8711 ? "true" : "false");
8712 }
8713 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8714 serializer.attribute(null, "installStatus", "false");
8715 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008716 if (pkg.installerPackageName != null) {
8717 serializer.attribute(null, "installer", pkg.installerPackageName);
8718 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008719 if (pkg.obbPathString != null) {
8720 serializer.attribute(null, "obbPath", pkg.obbPathString);
8721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008722 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8723 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8724 serializer.startTag(null, "perms");
8725 if (pkg.sharedUser == null) {
8726 // If this is a shared user, the permissions will
8727 // be written there. We still need to write an
8728 // empty permissions list so permissionsFixed will
8729 // be set.
8730 for (final String name : pkg.grantedPermissions) {
8731 serializer.startTag(null, "item");
8732 serializer.attribute(null, "name", name);
8733 serializer.endTag(null, "item");
8734 }
8735 }
8736 serializer.endTag(null, "perms");
8737 }
8738 if (pkg.disabledComponents.size() > 0) {
8739 serializer.startTag(null, "disabled-components");
8740 for (final String name : pkg.disabledComponents) {
8741 serializer.startTag(null, "item");
8742 serializer.attribute(null, "name", name);
8743 serializer.endTag(null, "item");
8744 }
8745 serializer.endTag(null, "disabled-components");
8746 }
8747 if (pkg.enabledComponents.size() > 0) {
8748 serializer.startTag(null, "enabled-components");
8749 for (final String name : pkg.enabledComponents) {
8750 serializer.startTag(null, "item");
8751 serializer.attribute(null, "name", name);
8752 serializer.endTag(null, "item");
8753 }
8754 serializer.endTag(null, "enabled-components");
8755 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008757 serializer.endTag(null, "package");
8758 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008760 void writePermission(XmlSerializer serializer, BasePermission bp)
8761 throws XmlPullParserException, java.io.IOException {
8762 if (bp.type != BasePermission.TYPE_BUILTIN
8763 && bp.sourcePackage != null) {
8764 serializer.startTag(null, "item");
8765 serializer.attribute(null, "name", bp.name);
8766 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008767 if (bp.protectionLevel !=
8768 PermissionInfo.PROTECTION_NORMAL) {
8769 serializer.attribute(null, "protection",
8770 Integer.toString(bp.protectionLevel));
8771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772 if (DEBUG_SETTINGS) Log.v(TAG,
8773 "Writing perm: name=" + bp.name + " type=" + bp.type);
8774 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8775 PermissionInfo pi = bp.perm != null ? bp.perm.info
8776 : bp.pendingInfo;
8777 if (pi != null) {
8778 serializer.attribute(null, "type", "dynamic");
8779 if (pi.icon != 0) {
8780 serializer.attribute(null, "icon",
8781 Integer.toString(pi.icon));
8782 }
8783 if (pi.nonLocalizedLabel != null) {
8784 serializer.attribute(null, "label",
8785 pi.nonLocalizedLabel.toString());
8786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 }
8788 }
8789 serializer.endTag(null, "item");
8790 }
8791 }
8792
8793 String getReadMessagesLP() {
8794 return mReadMessages.toString();
8795 }
8796
Oscar Montemayora8529f62009-11-18 10:14:20 -08008797 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008798 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8799 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008800 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 while(its.hasNext()) {
8802 String key = its.next();
8803 PackageSetting ps = mPackages.get(key);
8804 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008805 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008806 }
8807 }
8808 return ret;
8809 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008811 boolean readLP() {
8812 FileInputStream str = null;
8813 if (mBackupSettingsFilename.exists()) {
8814 try {
8815 str = new FileInputStream(mBackupSettingsFilename);
8816 mReadMessages.append("Reading from backup settings file\n");
8817 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008818 if (mSettingsFilename.exists()) {
8819 // If both the backup and settings file exist, we
8820 // ignore the settings since it might have been
8821 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008822 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008823 mSettingsFilename.delete();
8824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008825 } catch (java.io.IOException e) {
8826 // We'll try for the normal settings file.
8827 }
8828 }
8829
8830 mPastSignatures.clear();
8831
8832 try {
8833 if (str == null) {
8834 if (!mSettingsFilename.exists()) {
8835 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008836 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008837 return false;
8838 }
8839 str = new FileInputStream(mSettingsFilename);
8840 }
8841 XmlPullParser parser = Xml.newPullParser();
8842 parser.setInput(str, null);
8843
8844 int type;
8845 while ((type=parser.next()) != XmlPullParser.START_TAG
8846 && type != XmlPullParser.END_DOCUMENT) {
8847 ;
8848 }
8849
8850 if (type != XmlPullParser.START_TAG) {
8851 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008852 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008853 return false;
8854 }
8855
8856 int outerDepth = parser.getDepth();
8857 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8858 && (type != XmlPullParser.END_TAG
8859 || parser.getDepth() > outerDepth)) {
8860 if (type == XmlPullParser.END_TAG
8861 || type == XmlPullParser.TEXT) {
8862 continue;
8863 }
8864
8865 String tagName = parser.getName();
8866 if (tagName.equals("package")) {
8867 readPackageLP(parser);
8868 } else if (tagName.equals("permissions")) {
8869 readPermissionsLP(mPermissions, parser);
8870 } else if (tagName.equals("permission-trees")) {
8871 readPermissionsLP(mPermissionTrees, parser);
8872 } else if (tagName.equals("shared-user")) {
8873 readSharedUserLP(parser);
8874 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008875 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008876 } else if (tagName.equals("preferred-activities")) {
8877 readPreferredActivitiesLP(parser);
8878 } else if(tagName.equals("updated-package")) {
8879 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008880 } else if (tagName.equals("cleaning-package")) {
8881 String name = parser.getAttributeValue(null, "name");
8882 if (name != null) {
8883 mPackagesToBeCleaned.add(name);
8884 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008885 } else if (tagName.equals("renamed-package")) {
8886 String nname = parser.getAttributeValue(null, "new");
8887 String oname = parser.getAttributeValue(null, "old");
8888 if (nname != null && oname != null) {
8889 mRenamedPackages.put(nname, oname);
8890 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008891 } else if (tagName.equals("last-platform-version")) {
8892 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8893 try {
8894 String internal = parser.getAttributeValue(null, "internal");
8895 if (internal != null) {
8896 mInternalSdkPlatform = Integer.parseInt(internal);
8897 }
8898 String external = parser.getAttributeValue(null, "external");
8899 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008900 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008901 }
8902 } catch (NumberFormatException e) {
8903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008905 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008906 + parser.getName());
8907 XmlUtils.skipCurrentTag(parser);
8908 }
8909 }
8910
8911 str.close();
8912
8913 } catch(XmlPullParserException e) {
8914 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008915 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008916
8917 } catch(java.io.IOException e) {
8918 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008919 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008920
8921 }
8922
8923 int N = mPendingPackages.size();
8924 for (int i=0; i<N; i++) {
8925 final PendingPackage pp = mPendingPackages.get(i);
8926 Object idObj = getUserIdLP(pp.sharedId);
8927 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008928 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008929 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008930 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008931 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008932 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008933 + pp.name);
8934 continue;
8935 }
8936 p.copyFrom(pp);
8937 } else if (idObj != null) {
8938 String msg = "Bad package setting: package " + pp.name
8939 + " has shared uid " + pp.sharedId
8940 + " that is not a shared uid\n";
8941 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008942 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008943 } else {
8944 String msg = "Bad package setting: package " + pp.name
8945 + " has shared uid " + pp.sharedId
8946 + " that is not defined\n";
8947 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008948 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 }
8950 }
8951 mPendingPackages.clear();
8952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008953 mReadMessages.append("Read completed successfully: "
8954 + mPackages.size() + " packages, "
8955 + mSharedUsers.size() + " shared uids\n");
8956
8957 return true;
8958 }
8959
8960 private int readInt(XmlPullParser parser, String ns, String name,
8961 int defValue) {
8962 String v = parser.getAttributeValue(ns, name);
8963 try {
8964 if (v == null) {
8965 return defValue;
8966 }
8967 return Integer.parseInt(v);
8968 } catch (NumberFormatException e) {
8969 reportSettingsProblem(Log.WARN,
8970 "Error in package manager settings: attribute " +
8971 name + " has bad integer value " + v + " at "
8972 + parser.getPositionDescription());
8973 }
8974 return defValue;
8975 }
8976
8977 private void readPermissionsLP(HashMap<String, BasePermission> out,
8978 XmlPullParser parser)
8979 throws IOException, XmlPullParserException {
8980 int outerDepth = parser.getDepth();
8981 int type;
8982 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8983 && (type != XmlPullParser.END_TAG
8984 || parser.getDepth() > outerDepth)) {
8985 if (type == XmlPullParser.END_TAG
8986 || type == XmlPullParser.TEXT) {
8987 continue;
8988 }
8989
8990 String tagName = parser.getName();
8991 if (tagName.equals("item")) {
8992 String name = parser.getAttributeValue(null, "name");
8993 String sourcePackage = parser.getAttributeValue(null, "package");
8994 String ptype = parser.getAttributeValue(null, "type");
8995 if (name != null && sourcePackage != null) {
8996 boolean dynamic = "dynamic".equals(ptype);
8997 BasePermission bp = new BasePermission(name, sourcePackage,
8998 dynamic
8999 ? BasePermission.TYPE_DYNAMIC
9000 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009001 bp.protectionLevel = readInt(parser, null, "protection",
9002 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009003 if (dynamic) {
9004 PermissionInfo pi = new PermissionInfo();
9005 pi.packageName = sourcePackage.intern();
9006 pi.name = name.intern();
9007 pi.icon = readInt(parser, null, "icon", 0);
9008 pi.nonLocalizedLabel = parser.getAttributeValue(
9009 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009010 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009011 bp.pendingInfo = pi;
9012 }
9013 out.put(bp.name, bp);
9014 } else {
9015 reportSettingsProblem(Log.WARN,
9016 "Error in package manager settings: permissions has"
9017 + " no name at " + parser.getPositionDescription());
9018 }
9019 } else {
9020 reportSettingsProblem(Log.WARN,
9021 "Unknown element reading permissions: "
9022 + parser.getName() + " at "
9023 + parser.getPositionDescription());
9024 }
9025 XmlUtils.skipCurrentTag(parser);
9026 }
9027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009029 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009030 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009031 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009032 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009033 String codePathStr = parser.getAttributeValue(null, "codePath");
9034 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009035 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009036 resourcePathStr = codePathStr;
9037 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009038 String version = parser.getAttributeValue(null, "version");
9039 int versionCode = 0;
9040 if (version != null) {
9041 try {
9042 versionCode = Integer.parseInt(version);
9043 } catch (NumberFormatException e) {
9044 }
9045 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009046
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009047 int pkgFlags = 0;
9048 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009049 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009050 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009051 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009052 String timeStampStr = parser.getAttributeValue(null, "ts");
9053 if (timeStampStr != null) {
9054 try {
9055 long timeStamp = Long.parseLong(timeStampStr);
9056 ps.setTimeStamp(timeStamp, timeStampStr);
9057 } catch (NumberFormatException e) {
9058 }
9059 }
9060 String idStr = parser.getAttributeValue(null, "userId");
9061 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
9062 if(ps.userId <= 0) {
9063 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9064 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
9065 }
9066 int outerDepth = parser.getDepth();
9067 int type;
9068 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9069 && (type != XmlPullParser.END_TAG
9070 || parser.getDepth() > outerDepth)) {
9071 if (type == XmlPullParser.END_TAG
9072 || type == XmlPullParser.TEXT) {
9073 continue;
9074 }
9075
9076 String tagName = parser.getName();
9077 if (tagName.equals("perms")) {
9078 readGrantedPermissionsLP(parser,
9079 ps.grantedPermissions);
9080 } else {
9081 reportSettingsProblem(Log.WARN,
9082 "Unknown element under <updated-package>: "
9083 + parser.getName());
9084 XmlUtils.skipCurrentTag(parser);
9085 }
9086 }
9087 mDisabledSysPackages.put(name, ps);
9088 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009090 private void readPackageLP(XmlPullParser parser)
9091 throws XmlPullParserException, IOException {
9092 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009093 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009094 String idStr = null;
9095 String sharedIdStr = null;
9096 String codePathStr = null;
9097 String resourcePathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07009098 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009099 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02009100 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009101 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009102 int pkgFlags = 0;
9103 String timeStampStr;
9104 long timeStamp = 0;
9105 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009106 String version = null;
9107 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009108 try {
9109 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009110 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009111 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009112 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009113 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
9114 codePathStr = parser.getAttributeValue(null, "codePath");
9115 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root93565c4b2010-06-18 15:46:06 -07009116 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07009117 version = parser.getAttributeValue(null, "version");
9118 if (version != null) {
9119 try {
9120 versionCode = Integer.parseInt(version);
9121 } catch (NumberFormatException e) {
9122 }
9123 }
Jacek Surazski65e13172009-04-28 15:26:38 +02009124 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009125
9126 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009127 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009128 try {
9129 pkgFlags = Integer.parseInt(systemStr);
9130 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009131 }
9132 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009133 // For backward compatibility
9134 systemStr = parser.getAttributeValue(null, "system");
9135 if (systemStr != null) {
9136 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
9137 } else {
9138 // Old settings that don't specify system... just treat
9139 // them as system, good enough.
9140 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009142 }
9143 timeStampStr = parser.getAttributeValue(null, "ts");
9144 if (timeStampStr != null) {
9145 try {
9146 timeStamp = Long.parseLong(timeStampStr);
9147 } catch (NumberFormatException e) {
9148 }
9149 }
9150 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9151 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9152 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9153 if (resourcePathStr == null) {
9154 resourcePathStr = codePathStr;
9155 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009156 if (realName != null) {
9157 realName = realName.intern();
9158 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009159 if (name == null) {
9160 reportSettingsProblem(Log.WARN,
9161 "Error in package manager settings: <package> has no name at "
9162 + parser.getPositionDescription());
9163 } else if (codePathStr == null) {
9164 reportSettingsProblem(Log.WARN,
9165 "Error in package manager settings: <package> has no codePath at "
9166 + parser.getPositionDescription());
9167 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009168 packageSetting = addPackageLP(name.intern(), realName,
9169 new File(codePathStr), new File(resourcePathStr),
9170 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009171 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9172 + ": userId=" + userId + " pkg=" + packageSetting);
9173 if (packageSetting == null) {
9174 reportSettingsProblem(Log.ERROR,
9175 "Failure adding uid " + userId
9176 + " while parsing settings at "
9177 + parser.getPositionDescription());
9178 } else {
9179 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9180 }
9181 } else if (sharedIdStr != null) {
9182 userId = sharedIdStr != null
9183 ? Integer.parseInt(sharedIdStr) : 0;
9184 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009185 packageSetting = new PendingPackage(name.intern(), realName,
9186 new File(codePathStr), new File(resourcePathStr),
9187 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009188 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9189 mPendingPackages.add((PendingPackage) packageSetting);
9190 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9191 + ": sharedUserId=" + userId + " pkg="
9192 + packageSetting);
9193 } else {
9194 reportSettingsProblem(Log.WARN,
9195 "Error in package manager settings: package "
9196 + name + " has bad sharedId " + sharedIdStr
9197 + " at " + parser.getPositionDescription());
9198 }
9199 } else {
9200 reportSettingsProblem(Log.WARN,
9201 "Error in package manager settings: package "
9202 + name + " has bad userId " + idStr + " at "
9203 + parser.getPositionDescription());
9204 }
9205 } catch (NumberFormatException e) {
9206 reportSettingsProblem(Log.WARN,
9207 "Error in package manager settings: package "
9208 + name + " has bad userId " + idStr + " at "
9209 + parser.getPositionDescription());
9210 }
9211 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009212 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009213 packageSetting.installerPackageName = installerPackageName;
Kenny Root93565c4b2010-06-18 15:46:06 -07009214 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009215 final String enabledStr = parser.getAttributeValue(null, "enabled");
9216 if (enabledStr != null) {
9217 if (enabledStr.equalsIgnoreCase("true")) {
9218 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9219 } else if (enabledStr.equalsIgnoreCase("false")) {
9220 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9221 } else if (enabledStr.equalsIgnoreCase("default")) {
9222 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9223 } else {
9224 reportSettingsProblem(Log.WARN,
9225 "Error in package manager settings: package "
9226 + name + " has bad enabled value: " + idStr
9227 + " at " + parser.getPositionDescription());
9228 }
9229 } else {
9230 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9231 }
9232 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9233 if (installStatusStr != null) {
9234 if (installStatusStr.equalsIgnoreCase("false")) {
9235 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9236 } else {
9237 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9238 }
9239 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009241 int outerDepth = parser.getDepth();
9242 int type;
9243 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9244 && (type != XmlPullParser.END_TAG
9245 || parser.getDepth() > outerDepth)) {
9246 if (type == XmlPullParser.END_TAG
9247 || type == XmlPullParser.TEXT) {
9248 continue;
9249 }
9250
9251 String tagName = parser.getName();
9252 if (tagName.equals("disabled-components")) {
9253 readDisabledComponentsLP(packageSetting, parser);
9254 } else if (tagName.equals("enabled-components")) {
9255 readEnabledComponentsLP(packageSetting, parser);
9256 } else if (tagName.equals("sigs")) {
9257 packageSetting.signatures.readXml(parser, mPastSignatures);
9258 } else if (tagName.equals("perms")) {
9259 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009260 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009261 packageSetting.permissionsFixed = true;
9262 } else {
9263 reportSettingsProblem(Log.WARN,
9264 "Unknown element under <package>: "
9265 + parser.getName());
9266 XmlUtils.skipCurrentTag(parser);
9267 }
9268 }
9269 } else {
9270 XmlUtils.skipCurrentTag(parser);
9271 }
9272 }
9273
9274 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9275 XmlPullParser parser)
9276 throws IOException, XmlPullParserException {
9277 int outerDepth = parser.getDepth();
9278 int type;
9279 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9280 && (type != XmlPullParser.END_TAG
9281 || parser.getDepth() > outerDepth)) {
9282 if (type == XmlPullParser.END_TAG
9283 || type == XmlPullParser.TEXT) {
9284 continue;
9285 }
9286
9287 String tagName = parser.getName();
9288 if (tagName.equals("item")) {
9289 String name = parser.getAttributeValue(null, "name");
9290 if (name != null) {
9291 packageSetting.disabledComponents.add(name.intern());
9292 } else {
9293 reportSettingsProblem(Log.WARN,
9294 "Error in package manager settings: <disabled-components> has"
9295 + " no name at " + parser.getPositionDescription());
9296 }
9297 } else {
9298 reportSettingsProblem(Log.WARN,
9299 "Unknown element under <disabled-components>: "
9300 + parser.getName());
9301 }
9302 XmlUtils.skipCurrentTag(parser);
9303 }
9304 }
9305
9306 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9307 XmlPullParser parser)
9308 throws IOException, XmlPullParserException {
9309 int outerDepth = parser.getDepth();
9310 int type;
9311 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9312 && (type != XmlPullParser.END_TAG
9313 || parser.getDepth() > outerDepth)) {
9314 if (type == XmlPullParser.END_TAG
9315 || type == XmlPullParser.TEXT) {
9316 continue;
9317 }
9318
9319 String tagName = parser.getName();
9320 if (tagName.equals("item")) {
9321 String name = parser.getAttributeValue(null, "name");
9322 if (name != null) {
9323 packageSetting.enabledComponents.add(name.intern());
9324 } else {
9325 reportSettingsProblem(Log.WARN,
9326 "Error in package manager settings: <enabled-components> has"
9327 + " no name at " + parser.getPositionDescription());
9328 }
9329 } else {
9330 reportSettingsProblem(Log.WARN,
9331 "Unknown element under <enabled-components>: "
9332 + parser.getName());
9333 }
9334 XmlUtils.skipCurrentTag(parser);
9335 }
9336 }
9337
9338 private void readSharedUserLP(XmlPullParser parser)
9339 throws XmlPullParserException, IOException {
9340 String name = null;
9341 String idStr = null;
9342 int pkgFlags = 0;
9343 SharedUserSetting su = null;
9344 try {
9345 name = parser.getAttributeValue(null, "name");
9346 idStr = parser.getAttributeValue(null, "userId");
9347 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9348 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9349 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9350 }
9351 if (name == null) {
9352 reportSettingsProblem(Log.WARN,
9353 "Error in package manager settings: <shared-user> has no name at "
9354 + parser.getPositionDescription());
9355 } else if (userId == 0) {
9356 reportSettingsProblem(Log.WARN,
9357 "Error in package manager settings: shared-user "
9358 + name + " has bad userId " + idStr + " at "
9359 + parser.getPositionDescription());
9360 } else {
9361 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9362 reportSettingsProblem(Log.ERROR,
9363 "Occurred while parsing settings at "
9364 + parser.getPositionDescription());
9365 }
9366 }
9367 } catch (NumberFormatException e) {
9368 reportSettingsProblem(Log.WARN,
9369 "Error in package manager settings: package "
9370 + name + " has bad userId " + idStr + " at "
9371 + parser.getPositionDescription());
9372 };
9373
9374 if (su != null) {
9375 int outerDepth = parser.getDepth();
9376 int type;
9377 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9378 && (type != XmlPullParser.END_TAG
9379 || parser.getDepth() > outerDepth)) {
9380 if (type == XmlPullParser.END_TAG
9381 || type == XmlPullParser.TEXT) {
9382 continue;
9383 }
9384
9385 String tagName = parser.getName();
9386 if (tagName.equals("sigs")) {
9387 su.signatures.readXml(parser, mPastSignatures);
9388 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009389 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009390 } else {
9391 reportSettingsProblem(Log.WARN,
9392 "Unknown element under <shared-user>: "
9393 + parser.getName());
9394 XmlUtils.skipCurrentTag(parser);
9395 }
9396 }
9397
9398 } else {
9399 XmlUtils.skipCurrentTag(parser);
9400 }
9401 }
9402
9403 private void readGrantedPermissionsLP(XmlPullParser parser,
9404 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9405 int outerDepth = parser.getDepth();
9406 int type;
9407 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9408 && (type != XmlPullParser.END_TAG
9409 || parser.getDepth() > outerDepth)) {
9410 if (type == XmlPullParser.END_TAG
9411 || type == XmlPullParser.TEXT) {
9412 continue;
9413 }
9414
9415 String tagName = parser.getName();
9416 if (tagName.equals("item")) {
9417 String name = parser.getAttributeValue(null, "name");
9418 if (name != null) {
9419 outPerms.add(name.intern());
9420 } else {
9421 reportSettingsProblem(Log.WARN,
9422 "Error in package manager settings: <perms> has"
9423 + " no name at " + parser.getPositionDescription());
9424 }
9425 } else {
9426 reportSettingsProblem(Log.WARN,
9427 "Unknown element under <perms>: "
9428 + parser.getName());
9429 }
9430 XmlUtils.skipCurrentTag(parser);
9431 }
9432 }
9433
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009434 private void readPreferredActivitiesLP(XmlPullParser parser)
9435 throws XmlPullParserException, IOException {
9436 int outerDepth = parser.getDepth();
9437 int type;
9438 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9439 && (type != XmlPullParser.END_TAG
9440 || parser.getDepth() > outerDepth)) {
9441 if (type == XmlPullParser.END_TAG
9442 || type == XmlPullParser.TEXT) {
9443 continue;
9444 }
9445
9446 String tagName = parser.getName();
9447 if (tagName.equals("item")) {
9448 PreferredActivity pa = new PreferredActivity(parser);
9449 if (pa.mParseError == null) {
9450 mPreferredActivities.addFilter(pa);
9451 } else {
9452 reportSettingsProblem(Log.WARN,
9453 "Error in package manager settings: <preferred-activity> "
9454 + pa.mParseError + " at "
9455 + parser.getPositionDescription());
9456 }
9457 } else {
9458 reportSettingsProblem(Log.WARN,
9459 "Unknown element under <preferred-activities>: "
9460 + parser.getName());
9461 XmlUtils.skipCurrentTag(parser);
9462 }
9463 }
9464 }
9465
9466 // Returns -1 if we could not find an available UserId to assign
9467 private int newUserIdLP(Object obj) {
9468 // Let's be stupidly inefficient for now...
9469 final int N = mUserIds.size();
9470 for (int i=0; i<N; i++) {
9471 if (mUserIds.get(i) == null) {
9472 mUserIds.set(i, obj);
9473 return FIRST_APPLICATION_UID + i;
9474 }
9475 }
9476
9477 // None left?
9478 if (N >= MAX_APPLICATION_UIDS) {
9479 return -1;
9480 }
9481
9482 mUserIds.add(obj);
9483 return FIRST_APPLICATION_UID + N;
9484 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009485
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009486 public PackageSetting getDisabledSystemPkg(String name) {
9487 synchronized(mPackages) {
9488 PackageSetting ps = mDisabledSysPackages.get(name);
9489 return ps;
9490 }
9491 }
9492
9493 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009494 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9495 return true;
9496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009497 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9498 if (Config.LOGV) {
9499 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9500 + " componentName = " + componentInfo.name);
9501 Log.v(TAG, "enabledComponents: "
9502 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9503 Log.v(TAG, "disabledComponents: "
9504 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9505 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009506 if (packageSettings == null) {
9507 if (false) {
9508 Log.w(TAG, "WAITING FOR DEBUGGER");
9509 Debug.waitForDebugger();
9510 Log.i(TAG, "We will crash!");
9511 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009512 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009513 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009514 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9515 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9516 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9517 return false;
9518 }
9519 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9520 return true;
9521 }
9522 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9523 return false;
9524 }
9525 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009526 }
9527 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009528
9529 // ------- apps on sdcard specific code -------
9530 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009531 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009532 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009533 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009534 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009535
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009536 private String getEncryptKey() {
9537 try {
9538 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9539 if (sdEncKey == null) {
9540 sdEncKey = SystemKeyStore.getInstance().
9541 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9542 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009543 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009544 return null;
9545 }
9546 }
9547 return sdEncKey;
9548 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009549 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009550 return null;
9551 }
9552 }
9553
Kenny Rootc78a8072010-07-27 15:18:38 -07009554 /* package */ static String getTempContainerId() {
9555 int tmpIdx = 1;
9556 String list[] = PackageHelper.getSecureContainerList();
9557 if (list != null) {
9558 for (final String name : list) {
9559 // Ignore null and non-temporary container entries
9560 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9561 continue;
9562 }
9563
9564 String subStr = name.substring(mTempContainerPrefix.length());
9565 try {
9566 int cid = Integer.parseInt(subStr);
9567 if (cid >= tmpIdx) {
9568 tmpIdx = cid + 1;
9569 }
9570 } catch (NumberFormatException e) {
9571 }
9572 }
9573 }
9574 return mTempContainerPrefix + tmpIdx;
9575 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009576
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009577 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009578 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009579 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009580 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9581 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9582 throw new SecurityException("Media status can only be updated by the system");
9583 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009584 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009585 Log.i(TAG, "Updating external media status from " +
9586 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9587 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009588 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9589 mediaStatus+", mMediaMounted=" + mMediaMounted);
9590 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009591 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9592 reportStatus ? 1 : 0, -1);
9593 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009594 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009595 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009596 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009597 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009598 // Queue up an async operation since the package installation may take a little while.
9599 mHandler.post(new Runnable() {
9600 public void run() {
9601 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009602 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009603 }
9604 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009605 }
9606
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009607 /*
9608 * Collect information of applications on external media, map them
9609 * against existing containers and update information based on current
9610 * mount status. Please note that we always have to report status
9611 * if reportStatus has been set to true especially when unloading packages.
9612 */
9613 private void updateExternalMediaStatusInner(boolean mediaStatus,
9614 boolean reportStatus) {
9615 // Collection of uids
9616 int uidArr[] = null;
9617 // Collection of stale containers
9618 HashSet<String> removeCids = new HashSet<String>();
9619 // Collection of packages on external media with valid containers.
9620 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9621 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009622 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009623 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009624 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009625 } else {
9626 // Process list of secure containers and categorize them
9627 // as active or stale based on their package internal state.
9628 int uidList[] = new int[list.length];
9629 int num = 0;
9630 synchronized (mPackages) {
9631 for (String cid : list) {
9632 SdInstallArgs args = new SdInstallArgs(cid);
9633 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009634 String pkgName = args.getPackageName();
9635 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009636 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9637 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009638 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009639 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9641 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009642 // The package status is changed only if the code path
9643 // matches between settings and the container id.
9644 if (ps != null && ps.codePathString != null &&
9645 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009646 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9647 " corresponds to pkg : " + pkgName +
9648 " at code path: " + ps.codePathString);
9649 // We do have a valid package installed on sdcard
9650 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009651 int uid = ps.userId;
9652 if (uid != -1) {
9653 uidList[num++] = uid;
9654 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009655 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009656 // Stale container on sdcard. Just delete
9657 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9658 removeCids.add(cid);
9659 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009660 }
9661 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009662
9663 if (num > 0) {
9664 // Sort uid list
9665 Arrays.sort(uidList, 0, num);
9666 // Throw away duplicates
9667 uidArr = new int[num];
9668 uidArr[0] = uidList[0];
9669 int di = 0;
9670 for (int i = 1; i < num; i++) {
9671 if (uidList[i-1] != uidList[i]) {
9672 uidArr[di++] = uidList[i];
9673 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009674 }
9675 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009676 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009677 // Process packages with valid entries.
9678 if (mediaStatus) {
9679 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009680 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009681 startCleaningPackages();
9682 } else {
9683 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009684 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009685 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009686 }
9687
9688 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009689 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009690 int size = pkgList.size();
9691 if (size > 0) {
9692 // Send broadcasts here
9693 Bundle extras = new Bundle();
9694 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9695 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009696 if (uidArr != null) {
9697 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9698 }
9699 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9700 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009701 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009702 }
9703 }
9704
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009705 /*
9706 * Look at potentially valid container ids from processCids
9707 * If package information doesn't match the one on record
9708 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009709 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009710 */
9711 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009712 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009713 ArrayList<String> pkgList = new ArrayList<String>();
9714 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009715 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009716 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009717 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009718 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9719 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009720 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009721 try {
9722 // Make sure there are no container errors first.
9723 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9724 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009725 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009726 " when installing from sdcard");
9727 continue;
9728 }
9729 // Check code path here.
9730 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009731 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009732 " does not match one in settings " + codePath);
9733 continue;
9734 }
9735 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009736 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009737 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009738 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009739 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9740 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009741 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009742 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009743 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009744 retCode = PackageManager.INSTALL_SUCCEEDED;
9745 pkgList.add(pkg.packageName);
9746 // Post process args
9747 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9748 }
9749 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009750 Slog.i(TAG, "Failed to install pkg from " +
9751 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009752 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009753 }
9754
9755 } finally {
9756 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9757 // Don't destroy container here. Wait till gc clears things up.
9758 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009759 }
9760 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009761 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009762 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009763 // If the platform SDK has changed since the last time we booted,
9764 // we need to re-grant app permission to catch any new ones that
9765 // appear. This is really a hack, and means that apps can in some
9766 // cases get permissions that the user didn't initially explicitly
9767 // allow... it would be nice to have some better way to handle
9768 // this situation.
9769 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9770 != mSdkVersion;
9771 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9772 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9773 + "; regranting permissions for external storage");
9774 mSettings.mExternalSdkPlatform = mSdkVersion;
9775
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009776 // Make sure group IDs have been assigned, and any permission
9777 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009778 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009779 // Persist settings
9780 mSettings.writeLP();
9781 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009782 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009783 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009784 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009785 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009786 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009787 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009788 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009789 }
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009790 // List stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009791 if (removeCids != null) {
9792 for (String cid : removeCids) {
Suchi Amalapurapuf654a482010-03-23 09:46:22 -07009793 Log.w(TAG, "Container " + cid + " is stale");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009794 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009795 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009796 }
9797
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009798 /*
9799 * Utility method to unload a list of specified containers
9800 */
9801 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9802 // Just unmount all valid containers.
9803 for (SdInstallArgs arg : cidArgs) {
9804 synchronized (mInstallLock) {
9805 arg.doPostDeleteLI(false);
9806 }
9807 }
9808 }
9809
9810 /*
9811 * Unload packages mounted on external media. This involves deleting
9812 * package data from internal structures, sending broadcasts about
9813 * diabled packages, gc'ing to free up references, unmounting all
9814 * secure containers corresponding to packages on external media, and
9815 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9816 * Please note that we always have to post this message if status has
9817 * been requested no matter what.
9818 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009819 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009820 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009821 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009822 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009823 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009824 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009825 for (SdInstallArgs args : keys) {
9826 String cid = args.cid;
9827 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009828 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009829 // Delete package internally
9830 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9831 synchronized (mInstallLock) {
9832 boolean res = deletePackageLI(pkgName, false,
9833 PackageManager.DONT_DELETE_DATA, outInfo);
9834 if (res) {
9835 pkgList.add(pkgName);
9836 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009837 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009838 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009839 }
9840 }
9841 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009842 // We have to absolutely send UPDATED_MEDIA_STATUS only
9843 // after confirming that all the receivers processed the ordered
9844 // broadcast when packages get disabled, force a gc to clean things up.
9845 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009846 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009847 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9848 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9849 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009850 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9851 reportStatus ? 1 : 0, 1, keys);
9852 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009853 }
9854 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009855 } else {
9856 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9857 reportStatus ? 1 : 0, -1, keys);
9858 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009859 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009860 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009861
9862 public void movePackage(final String packageName,
9863 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009864 mContext.enforceCallingOrSelfPermission(
9865 android.Manifest.permission.MOVE_PACKAGE, null);
9866 int returnCode = PackageManager.MOVE_SUCCEEDED;
9867 int currFlags = 0;
9868 int newFlags = 0;
9869 synchronized (mPackages) {
9870 PackageParser.Package pkg = mPackages.get(packageName);
9871 if (pkg == null) {
9872 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009873 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009874 // Disable moving fwd locked apps and system packages
9875 if (pkg.applicationInfo != null &&
9876 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9877 Slog.w(TAG, "Cannot move system application");
9878 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
9879 } else if (pkg.applicationInfo != null &&
9880 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0) {
9881 Slog.w(TAG, "Cannot move forward locked app.");
9882 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009883 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009884 // Find install location first
9885 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9886 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9887 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009888 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009889 } else {
9890 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9891 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9892 currFlags = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0 ?
9893 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
9894 if (newFlags == currFlags) {
9895 Slog.w(TAG, "No move required. Trying to move to same location");
9896 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9897 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009898 }
9899 }
9900 }
9901 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07009902 processPendingMove(new MoveParams(null, observer, 0, packageName), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009903 } else {
9904 Message msg = mHandler.obtainMessage(INIT_COPY);
9905 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
9906 pkg.applicationInfo.publicSourceDir);
9907 MoveParams mp = new MoveParams(srcArgs, observer, newFlags,
9908 packageName);
9909 msg.obj = mp;
9910 mHandler.sendMessage(msg);
9911 }
9912 }
9913 }
9914
9915 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9916 // Queue up an async operation since the package deletion may take a little while.
9917 mHandler.post(new Runnable() {
9918 public void run() {
9919 mHandler.removeCallbacks(this);
9920 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009921 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9922 int uidArr[] = null;
9923 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009924 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009925 PackageParser.Package pkg = mPackages.get(mp.packageName);
9926 if (pkg == null ) {
9927 Slog.w(TAG, " Package " + mp.packageName +
9928 " doesn't exist. Aborting move");
9929 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9930 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9931 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9932 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9933 " Aborting move and returning error");
9934 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9935 } else {
9936 uidArr = new int[] { pkg.applicationInfo.uid };
9937 pkgList = new ArrayList<String>();
9938 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009939 }
9940 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009941 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9942 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009943 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009944 // Update package code and resource paths
9945 synchronized (mInstallLock) {
9946 synchronized (mPackages) {
9947 PackageParser.Package pkg = mPackages.get(mp.packageName);
9948 // Recheck for package again.
9949 if (pkg == null ) {
9950 Slog.w(TAG, " Package " + mp.packageName +
9951 " doesn't exist. Aborting move");
9952 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9953 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9954 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9955 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9956 " Aborting move and returning error");
9957 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9958 } else {
9959 String oldCodePath = pkg.mPath;
9960 String newCodePath = mp.targetArgs.getCodePath();
9961 String newResPath = mp.targetArgs.getResourcePath();
9962 pkg.mPath = newCodePath;
9963 // Move dex files around
9964 if (moveDexFilesLI(pkg)
9965 != PackageManager.INSTALL_SUCCEEDED) {
9966 // Moving of dex files failed. Set
9967 // error code and abort move.
9968 pkg.mPath = pkg.mScanPath;
9969 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9970 } else {
9971 pkg.mScanPath = newCodePath;
9972 pkg.applicationInfo.sourceDir = newCodePath;
9973 pkg.applicationInfo.publicSourceDir = newResPath;
9974 PackageSetting ps = (PackageSetting) pkg.mExtras;
9975 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9976 ps.codePathString = ps.codePath.getPath();
9977 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9978 ps.resourcePathString = ps.resourcePath.getPath();
9979 // Set the application info flag correctly.
9980 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9981 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9982 } else {
9983 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9984 }
9985 ps.setFlags(pkg.applicationInfo.flags);
9986 mAppDirs.remove(oldCodePath);
9987 mAppDirs.put(newCodePath, pkg);
9988 // Persist settings
9989 mSettings.writeLP();
9990 }
9991 }
9992 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009993 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009994 // Send resources available broadcast
9995 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009996 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009997 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009998 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009999 // Clean up failed installation
10000 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -070010001 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -080010002 }
10003 } else {
10004 // Force a gc to clear things up.
10005 Runtime.getRuntime().gc();
10006 // Delete older code
10007 synchronized (mInstallLock) {
10008 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080010009 }
10010 }
10011 IPackageMoveObserver observer = mp.observer;
10012 if (observer != null) {
10013 try {
10014 observer.packageMoved(mp.packageName, returnCode);
10015 } catch (RemoteException e) {
10016 Log.i(TAG, "Observer no longer exists.");
10017 }
10018 }
10019 }
10020 });
10021 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070010022
10023 public boolean setInstallLocation(int loc) {
10024 mContext.enforceCallingOrSelfPermission(
10025 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
10026 if (getInstallLocation() == loc) {
10027 return true;
10028 }
10029 if (loc == PackageHelper.APP_INSTALL_AUTO ||
10030 loc == PackageHelper.APP_INSTALL_INTERNAL ||
10031 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
10032 android.provider.Settings.System.putInt(mContext.getContentResolver(),
10033 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
10034 return true;
10035 }
10036 return false;
10037 }
10038
10039 public int getInstallLocation() {
10040 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
10041 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
10042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080010043}