blob: abf8b7cbf998c19ecded1297c3df6eac18ae4165 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
57import android.content.pm.PackageStats;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
94import java.io.File;
95import java.io.FileDescriptor;
96import java.io.FileInputStream;
97import java.io.FileNotFoundException;
98import java.io.FileOutputStream;
99import java.io.FileReader;
100import java.io.FilenameFilter;
101import java.io.IOException;
102import java.io.InputStream;
103import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800104import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800105import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.ArrayList;
107import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700108import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Collections;
110import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800111import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import java.util.Enumeration;
113import java.util.HashMap;
114import java.util.HashSet;
115import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700116import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import java.util.List;
118import java.util.Map;
119import java.util.Set;
120import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800121import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import java.util.zip.ZipFile;
123import java.util.zip.ZipOutputStream;
124
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700125/**
126 * Keep track of all those .apks everywhere.
127 *
128 * This is very central to the platform's security; please run the unit
129 * tests whenever making modifications here:
130 *
131mmm frameworks/base/tests/AndroidTests
132adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
133adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
134 *
135 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136class PackageManagerService extends IPackageManager.Stub {
137 private static final String TAG = "PackageManager";
138 private static final boolean DEBUG_SETTINGS = false;
139 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800140 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800141 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700142 private static final boolean DEBUG_NATIVE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
145 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400146 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 private static final int FIRST_APPLICATION_UID =
148 Process.FIRST_APPLICATION_UID;
149 private static final int MAX_APPLICATION_UIDS = 1000;
150
151 private static final boolean SHOW_INFO = false;
152
153 private static final boolean GET_CERTIFICATES = true;
154
Oscar Montemayora8529f62009-11-18 10:14:20 -0800155 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private static final int REMOVE_EVENTS =
158 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
159 private static final int ADD_EVENTS =
160 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
161
162 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800163 // Suffix used during package installation when copying/moving
164 // package apks to install directory.
165 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800167 /**
168 * Indicates the state of installation. Used by PackageManager to
169 * figure out incomplete installations. Say a package is being installed
170 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
171 * the package installation is successful or unsuccesful lin which case
172 * the PackageManager will no longer maintain state information associated
173 * with the package. If some exception(like device freeze or battery being
174 * pulled out) occurs during installation of a package, the PackageManager
175 * needs this information to clean up the previously failed installation.
176 */
177 private static final int PKG_INSTALL_INCOMPLETE = 0;
178 private static final int PKG_INSTALL_COMPLETE = 1;
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final int SCAN_MONITOR = 1<<0;
181 static final int SCAN_NO_DEX = 1<<1;
182 static final int SCAN_FORCE_DEX = 1<<2;
183 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800184 static final int SCAN_NEW_INSTALL = 1<<4;
185 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700187 static final int REMOVE_CHATTY = 1<<16;
188
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800189 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
190 "com.android.defcontainer",
191 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700192
Kenny Root85387d72010-08-26 10:13:11 -0700193 private static final String LIB_DIR_NAME = "lib";
194
Kenny Rootc78a8072010-07-27 15:18:38 -0700195 static final String mTempContainerPrefix = "smdl2tmp";
196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
198 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700199 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Dianne Hackborn851a5412009-05-08 12:06:44 -0700201 final int mSdkVersion = Build.VERSION.SDK_INT;
202 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
203 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 final Context mContext;
206 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700207 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 final DisplayMetrics mMetrics;
209 final int mDefParseFlags;
210 final String[] mSeparateProcesses;
211
212 // This is where all application persistent data goes.
213 final File mAppDataDir;
214
Oscar Montemayora8529f62009-11-18 10:14:20 -0800215 // If Encrypted File System feature is enabled, all application persistent data
216 // should go here instead.
217 final File mSecureAppDataDir;
218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 // This is the object monitoring the framework dir.
220 final FileObserver mFrameworkInstallObserver;
221
222 // This is the object monitoring the system app dir.
223 final FileObserver mSystemInstallObserver;
224
225 // This is the object monitoring mAppInstallDir.
226 final FileObserver mAppInstallObserver;
227
228 // This is the object monitoring mDrmAppPrivateInstallDir.
229 final FileObserver mDrmAppInstallObserver;
230
231 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
232 // LOCK HELD. Can be called with mInstallLock held.
233 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 final File mFrameworkDir;
236 final File mSystemAppDir;
237 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700238 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
241 // apps.
242 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 // Lock for state used when installing and doing other long running
247 // operations. Methods that must be called with this lock held have
248 // the prefix "LI".
249 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // These are the directories in the 3rd party applications installed dir
252 // that we have currently loaded packages from. Keys are the application's
253 // installed zip file (absolute codePath), and values are Package.
254 final HashMap<String, PackageParser.Package> mAppDirs =
255 new HashMap<String, PackageParser.Package>();
256
257 // Information for the parser to write more useful error messages.
258 File mScanningPath;
259 int mLastScanError;
260
261 final int[] mOutPermissions = new int[3];
262
263 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 // Keys are String (package name), values are Package. This also serves
266 // as the lock for the global state. Methods that must be called with
267 // this lock held have the prefix "LP".
268 final HashMap<String, PackageParser.Package> mPackages =
269 new HashMap<String, PackageParser.Package>();
270
271 final Settings mSettings;
272 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273
274 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
275 int[] mGlobalGids;
276
277 // These are the built-in uid -> permission mappings that were read from the
278 // etc/permissions.xml file.
279 final SparseArray<HashSet<String>> mSystemPermissions =
280 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 // These are the built-in shared libraries that were read from the
283 // etc/permissions.xml file.
284 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800285
Dianne Hackborn49237342009-08-27 20:08:01 -0700286 // Temporary for building the final shared libraries for an .apk.
287 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800288
Dianne Hackborn49237342009-08-27 20:08:01 -0700289 // These are the features this devices supports that were read from the
290 // etc/permissions.xml file.
291 final HashMap<String, FeatureInfo> mAvailableFeatures =
292 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 // All available activities, for your resolving pleasure.
295 final ActivityIntentResolver mActivities =
296 new ActivityIntentResolver();
297
298 // All available receivers, for your resolving pleasure.
299 final ActivityIntentResolver mReceivers =
300 new ActivityIntentResolver();
301
302 // All available services, for your resolving pleasure.
303 final ServiceIntentResolver mServices = new ServiceIntentResolver();
304
305 // Keys are String (provider class name), values are Provider.
306 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
307 new HashMap<ComponentName, PackageParser.Provider>();
308
309 // Mapping from provider base names (first directory in content URI codePath)
310 // to the provider information.
311 final HashMap<String, PackageParser.Provider> mProviders =
312 new HashMap<String, PackageParser.Provider>();
313
314 // Mapping from instrumentation class names to info about them.
315 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
316 new HashMap<ComponentName, PackageParser.Instrumentation>();
317
318 // Mapping from permission names to info about them.
319 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
320 new HashMap<String, PackageParser.PermissionGroup>();
321
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800322 // Packages whose data we have transfered into another package, thus
323 // should no longer exist.
324 final HashSet<String> mTransferedPackages = new HashSet<String>();
325
Dianne Hackborn854060af2009-07-09 18:14:31 -0700326 // Broadcast actions that are only available to the system.
327 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 boolean mSystemReady;
330 boolean mSafeMode;
331 boolean mHasSystemUidErrors;
332
333 ApplicationInfo mAndroidApplication;
334 final ActivityInfo mResolveActivity = new ActivityInfo();
335 final ResolveInfo mResolveInfo = new ResolveInfo();
336 ComponentName mResolveComponentName;
337 PackageParser.Package mPlatformPackage;
338
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700339 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800340 final HashMap<String, ArrayList<String>> mPendingBroadcasts
341 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800342 // Service Connection to remote media container service to copy
343 // package uri's from external media onto secure containers
344 // or internal storage.
345 private IMediaContainerService mContainerService = null;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800348 static final int MCS_BOUND = 3;
349 static final int END_COPY = 4;
350 static final int INIT_COPY = 5;
351 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800352 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800353 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800354 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800355 static final int MCS_RECONNECT = 10;
356 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700357 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700358 static final int WRITE_SETTINGS = 13;
359
360 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800361
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700362 // Delay time in millisecs
363 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800364 final private DefaultContainerConnection mDefContainerConn =
365 new DefaultContainerConnection();
366 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800367 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800368 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800369 IMediaContainerService imcs =
370 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800371 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800372 }
373
374 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 }
377 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378
Christopher Tate1bb69062010-02-19 17:02:12 -0800379 // Recordkeeping of restore-after-install operations that are currently in flight
380 // between the Package Manager and the Backup Manager
381 class PostInstallData {
382 public InstallArgs args;
383 public PackageInstalledInfo res;
384
385 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
386 args = _a;
387 res = _r;
388 }
389 };
390 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
391 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
392
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700393 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800394 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800395 final ArrayList<HandlerParams> mPendingInstalls =
396 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397
398 private boolean connectToService() {
399 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
400 " DefaultContainerService");
401 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700402 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800403 if (mContext.bindService(service, mDefContainerConn,
404 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406 mBound = true;
407 return true;
408 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 return false;
411 }
412
413 private void disconnectService() {
414 mContainerService = null;
415 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700416 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800417 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800419 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800420
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 PackageHandler(Looper looper) {
422 super(looper);
423 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700424
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700425 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700426 try {
427 doHandleMessage(msg);
428 } finally {
429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
430 }
431 }
432
433 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700434 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800435 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800436 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800437 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800438 int idx = mPendingInstalls.size();
439 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
440 // If a bind was already initiated we dont really
441 // need to do anything. The pending install
442 // will be processed later on.
443 if (!mBound) {
444 // If this is the only one pending we might
445 // have to bind to the service again.
446 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800447 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800448 params.serviceError();
449 return;
450 } else {
451 // Once we bind to the service, the first
452 // pending request will be processed.
453 mPendingInstalls.add(idx, params);
454 }
455 } else {
456 mPendingInstalls.add(idx, params);
457 // Already bound to the service. Just make
458 // sure we trigger off processing the first request.
459 if (idx == 0) {
460 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800461 }
462 }
463 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800464 }
465 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800466 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800467 if (msg.obj != null) {
468 mContainerService = (IMediaContainerService) msg.obj;
469 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (mContainerService == null) {
471 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800472 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800473 for (HandlerParams params : mPendingInstalls) {
474 mPendingInstalls.remove(0);
475 // Indicate service bind error
476 params.serviceError();
477 }
478 mPendingInstalls.clear();
479 } else if (mPendingInstalls.size() > 0) {
480 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800481 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800482 params.startCopy();
483 }
484 } else {
485 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800486 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 }
488 break;
489 }
490 case MCS_RECONNECT : {
491 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
492 if (mPendingInstalls.size() > 0) {
493 if (mBound) {
494 disconnectService();
495 }
496 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800497 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800498 for (HandlerParams params : mPendingInstalls) {
499 mPendingInstalls.remove(0);
500 // Indicate service bind error
501 params.serviceError();
502 }
503 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800504 }
505 }
506 break;
507 }
508 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800509 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
510 // Delete pending install
511 if (mPendingInstalls.size() > 0) {
512 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800513 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800514 if (mPendingInstalls.size() == 0) {
515 if (mBound) {
516 disconnectService();
517 }
518 } else {
519 // There are more pending requests in queue.
520 // Just post MCS_BOUND message to trigger processing
521 // of next pending install.
522 mHandler.sendEmptyMessage(MCS_BOUND);
523 }
524 break;
525 }
526 case MCS_GIVE_UP: {
527 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
528 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800529 break;
530 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800532 String packages[];
533 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700534 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700536 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800538 if (mPendingBroadcasts == null) {
539 return;
540 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 size = mPendingBroadcasts.size();
542 if (size <= 0) {
543 // Nothing to be done. Just return
544 return;
545 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800546 packages = new String[size];
547 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700548 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800549 Iterator<HashMap.Entry<String, ArrayList<String>>>
550 it = mPendingBroadcasts.entrySet().iterator();
551 int i = 0;
552 while (it.hasNext() && i < size) {
553 HashMap.Entry<String, ArrayList<String>> ent = it.next();
554 packages[i] = ent.getKey();
555 components[i] = ent.getValue();
556 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700557 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800558 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700559 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800560 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700561 mPendingBroadcasts.clear();
562 }
563 // Send broadcasts
564 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800565 sendPackageChangedBroadcast(packages[i], true,
566 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700567 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700569 break;
570 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800571 case START_CLEANING_PACKAGE: {
572 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800574 synchronized (mPackages) {
575 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
576 mSettings.mPackagesToBeCleaned.add(packageName);
577 }
578 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800580 startCleaningPackages();
581 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800582 case POST_INSTALL: {
583 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
584 PostInstallData data = mRunningInstalls.get(msg.arg1);
585 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700586 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800587
588 if (data != null) {
589 InstallArgs args = data.args;
590 PackageInstalledInfo res = data.res;
591
592 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700593 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 Bundle extras = new Bundle(1);
595 extras.putInt(Intent.EXTRA_UID, res.uid);
596 final boolean update = res.removedInfo.removedPackage != null;
597 if (update) {
598 extras.putBoolean(Intent.EXTRA_REPLACING, true);
599 }
600 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
601 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700602 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800603 if (update) {
604 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
605 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700606 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800607 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700608 if (res.removedInfo.args != null) {
609 // Remove the replaced package's older resources safely now
610 deleteOld = true;
611 }
612 }
613 // Force a gc to clear up things
614 Runtime.getRuntime().gc();
615 // We delete after a gc for applications on sdcard.
616 if (deleteOld) {
617 synchronized (mInstallLock) {
618 res.removedInfo.args.doPostDeleteLI(true);
619 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800620 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800621 if (args.observer != null) {
622 try {
623 args.observer.packageInstalled(res.name, res.returnCode);
624 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800625 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800626 }
627 }
628 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800629 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800630 }
631 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700632 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700633 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
634 boolean reportStatus = msg.arg1 == 1;
635 boolean doGc = msg.arg2 == 1;
636 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
637 if (doGc) {
638 // Force a gc to clear up stale containers.
639 Runtime.getRuntime().gc();
640 }
641 if (msg.obj != null) {
642 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
644 // Unload containers
645 unloadAllContainers(args);
646 }
647 if (reportStatus) {
648 try {
649 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
650 PackageHelper.getMountService().finishMediaUpdate();
651 } catch (RemoteException e) {
652 Log.e(TAG, "MountService not running?");
653 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700654 }
655 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700656 case WRITE_SETTINGS: {
657 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
658 synchronized (mPackages) {
659 removeMessages(WRITE_SETTINGS);
660 mSettings.writeLP();
661 }
662 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
663 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700664 }
665 }
666 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800667
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700668 void scheduleWriteSettingsLocked() {
669 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
670 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
671 }
672 }
673
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800674 static boolean installOnSd(int flags) {
675 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700676 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800677 return false;
678 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700679 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
680 return true;
681 }
682 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800683 }
684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 public static final IPackageManager main(Context context, boolean factoryTest) {
686 PackageManagerService m = new PackageManagerService(context, factoryTest);
687 ServiceManager.addService("package", m);
688 return m;
689 }
690
691 static String[] splitString(String str, char sep) {
692 int count = 1;
693 int i = 0;
694 while ((i=str.indexOf(sep, i)) >= 0) {
695 count++;
696 i++;
697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 String[] res = new String[count];
700 i=0;
701 count = 0;
702 int lastI=0;
703 while ((i=str.indexOf(sep, i)) >= 0) {
704 res[count] = str.substring(lastI, i);
705 count++;
706 i++;
707 lastI = i;
708 }
709 res[count] = str.substring(lastI, str.length());
710 return res;
711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800718 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 mContext = context;
722 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700723 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 mMetrics = new DisplayMetrics();
725 mSettings = new Settings();
726 mSettings.addSharedUserLP("android.uid.system",
727 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
728 mSettings.addSharedUserLP("android.uid.phone",
729 MULTIPLE_APPLICATION_UIDS
730 ? RADIO_UID : FIRST_APPLICATION_UID,
731 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400732 mSettings.addSharedUserLP("android.uid.log",
733 MULTIPLE_APPLICATION_UIDS
734 ? LOG_UID : FIRST_APPLICATION_UID,
735 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736
737 String separateProcesses = SystemProperties.get("debug.separate_processes");
738 if (separateProcesses != null && separateProcesses.length() > 0) {
739 if ("*".equals(separateProcesses)) {
740 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
741 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800742 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 } else {
744 mDefParseFlags = 0;
745 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800746 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 + separateProcesses);
748 }
749 } else {
750 mDefParseFlags = 0;
751 mSeparateProcesses = null;
752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 Installer installer = new Installer();
755 // Little hacky thing to check if installd is here, to determine
756 // whether we are running on the simulator and thus need to take
757 // care of building the /data file structure ourself.
758 // (apparently the sim now has a working installer)
759 if (installer.ping() && Process.supportsProcesses()) {
760 mInstaller = installer;
761 } else {
762 mInstaller = null;
763 }
764
765 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
766 Display d = wm.getDefaultDisplay();
767 d.getMetrics(mMetrics);
768
769 synchronized (mInstallLock) {
770 synchronized (mPackages) {
771 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700772 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 File dataDir = Environment.getDataDirectory();
775 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800776 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
778
779 if (mInstaller == null) {
780 // Make sure these dirs exist, when we are running in
781 // the simulator.
782 // Make a wide-open directory for random misc stuff.
783 File miscDir = new File(dataDir, "misc");
784 miscDir.mkdirs();
785 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800786 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 mDrmAppPrivateInstallDir.mkdirs();
788 }
789
790 readPermissions();
791
792 mRestoredSettings = mSettings.readLP();
793 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800794
795 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800798 // Set flag to monitor and not change apk file paths when
799 // scanning install directories.
800 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700801 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800802 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800803 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700804 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700809 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700812 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 /**
815 * Out of paranoia, ensure that everything in the boot class
816 * path has been dexed.
817 */
818 String bootClassPath = System.getProperty("java.boot.class.path");
819 if (bootClassPath != null) {
820 String[] paths = splitString(bootClassPath, ':');
821 for (int i=0; i<paths.length; i++) {
822 try {
823 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
824 libFiles.add(paths[i]);
825 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700826 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 }
828 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800829 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800831 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833 }
834 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800835 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 /**
839 * Also ensure all external libraries have had dexopt run on them.
840 */
841 if (mSharedLibraries.size() > 0) {
842 Iterator<String> libs = mSharedLibraries.values().iterator();
843 while (libs.hasNext()) {
844 String lib = libs.next();
845 try {
846 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
847 libFiles.add(lib);
848 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700849 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
851 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800852 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800854 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 }
857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 // Gross hack for now: we know this file doesn't contain any
860 // code, so don't dexopt it to avoid the resulting log spew.
861 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 /**
864 * And there are a number of commands implemented in Java, which
865 * we currently need to do the dexopt on so that they can be
866 * run from a non-root shell.
867 */
868 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700869 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 for (int i=0; i<frameworkFiles.length; i++) {
871 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
872 String path = libPath.getPath();
873 // Skip the file if we alrady did it.
874 if (libFiles.contains(path)) {
875 continue;
876 }
877 // Skip the file if it is not a type we want to dexopt.
878 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
879 continue;
880 }
881 try {
882 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
883 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700884 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800887 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800889 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
891 }
892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700894 if (didDexOpt) {
895 // If we had to do a dexopt of one of the previous
896 // things, then something on the system has changed.
897 // Consider this significant, and wipe away all other
898 // existing dexopt files to ensure we don't leave any
899 // dangling around.
900 String[] files = mDalvikCacheDir.list();
901 if (files != null) {
902 for (int i=0; i<files.length; i++) {
903 String fn = files[i];
904 if (fn.startsWith("data@app@")
905 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800906 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700907 (new File(mDalvikCacheDir, fn)).delete();
908 }
909 }
910 }
911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800913
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800914 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 mFrameworkInstallObserver = new AppDirObserver(
916 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
917 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700918 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
919 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800920 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800921
922 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
924 mSystemInstallObserver = new AppDirObserver(
925 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
926 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700927 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
928 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800929
930 if (mInstaller != null) {
931 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
932 mInstaller.moveFiles();
933 }
934
935 // Prune any system packages that no longer exist.
936 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
937 while (psit.hasNext()) {
938 PackageSetting ps = psit.next();
939 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800940 && !mPackages.containsKey(ps.name)
941 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800942 psit.remove();
943 String msg = "System package " + ps.name
944 + " no longer exists; wiping its data";
945 reportSettingsProblem(Log.WARN, msg);
946 if (mInstaller != null) {
947 // XXX how to set useEncryptedFSDir for packages that
948 // are not encrypted?
949 mInstaller.remove(ps.name, true);
950 }
951 }
952 }
953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 mAppInstallDir = new File(dataDir, "app");
955 if (mInstaller == null) {
956 // Make sure these dirs exist, when we are running in
957 // the simulator.
958 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
959 }
960 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800961 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 //clean up list
963 for(int i = 0; i < deletePkgsList.size(); i++) {
964 //clean up here
965 cleanupInstallFailedPackage(deletePkgsList.get(i));
966 }
967 //delete tmp files
968 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800969
970 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 SystemClock.uptimeMillis());
972 mAppInstallObserver = new AppDirObserver(
973 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
974 mAppInstallObserver.startWatching();
975 scanDirLI(mAppInstallDir, 0, scanMode);
976
977 mDrmAppInstallObserver = new AppDirObserver(
978 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
979 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800980 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800984 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 + ((SystemClock.uptimeMillis()-startTime)/1000f)
986 + " seconds");
987
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700988 // If the platform SDK has changed since the last time we booted,
989 // we need to re-grant app permission to catch any new ones that
990 // appear. This is really a hack, and means that apps can in some
991 // cases get permissions that the user didn't initially explicitly
992 // allow... it would be nice to have some better way to handle
993 // this situation.
994 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
995 != mSdkVersion;
996 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
997 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
998 + "; regranting permissions for internal storage");
999 mSettings.mInternalSdkPlatform = mSdkVersion;
1000
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001001 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002
1003 mSettings.writeLP();
1004
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001005 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 // Now after opening every single application zip, make sure they
1009 // are all flushed. Not really needed, but keeps things nice and
1010 // tidy.
1011 Runtime.getRuntime().gc();
1012 } // synchronized (mPackages)
1013 } // synchronized (mInstallLock)
1014 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 @Override
1017 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1018 throws RemoteException {
1019 try {
1020 return super.onTransact(code, data, reply, flags);
1021 } catch (RuntimeException e) {
1022 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001023 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025 throw e;
1026 }
1027 }
1028
Dianne Hackborne6620b22010-01-22 14:46:21 -08001029 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001030 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001032 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1033 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001035 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001036 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038 } else {
1039 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001040 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 File dataDir = new File(pkg.applicationInfo.dataDir);
1042 dataDir.delete();
1043 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001044 if (ps.codePath != null) {
1045 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001046 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001047 }
1048 }
1049 if (ps.resourcePath != null) {
1050 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001052 }
1053 }
1054 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
1056
1057 void readPermissions() {
1058 // Read permissions from .../etc/permission directory.
1059 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1060 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001061 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 return;
1063 }
1064 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001065 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 return;
1067 }
1068
1069 // Iterate over the files in the directory and scan .xml files
1070 for (File f : libraryDir.listFiles()) {
1071 // We'll read platform.xml last
1072 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1073 continue;
1074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001077 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 continue;
1079 }
1080 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001081 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 continue;
1083 }
1084
1085 readPermissionsFromXml(f);
1086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1089 final File permFile = new File(Environment.getRootDirectory(),
1090 "etc/permissions/platform.xml");
1091 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001093 StringBuilder sb = new StringBuilder(128);
1094 sb.append("Libs:");
1095 Iterator<String> it = mSharedLibraries.keySet().iterator();
1096 while (it.hasNext()) {
1097 sb.append(' ');
1098 String name = it.next();
1099 sb.append(name);
1100 sb.append(':');
1101 sb.append(mSharedLibraries.get(name));
1102 }
1103 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001104
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001105 sb.setLength(0);
1106 sb.append("Features:");
1107 it = mAvailableFeatures.keySet().iterator();
1108 while (it.hasNext()) {
1109 sb.append(' ');
1110 sb.append(it.next());
1111 }
1112 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
1115 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 FileReader permReader = null;
1117 try {
1118 permReader = new FileReader(permFile);
1119 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001120 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 return;
1122 }
1123
1124 try {
1125 XmlPullParser parser = Xml.newPullParser();
1126 parser.setInput(permReader);
1127
1128 XmlUtils.beginDocument(parser, "permissions");
1129
1130 while (true) {
1131 XmlUtils.nextElement(parser);
1132 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1133 break;
1134 }
1135
1136 String name = parser.getName();
1137 if ("group".equals(name)) {
1138 String gidStr = parser.getAttributeValue(null, "gid");
1139 if (gidStr != null) {
1140 int gid = Integer.parseInt(gidStr);
1141 mGlobalGids = appendInt(mGlobalGids, gid);
1142 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + parser.getPositionDescription());
1145 }
1146
1147 XmlUtils.skipCurrentTag(parser);
1148 continue;
1149 } else if ("permission".equals(name)) {
1150 String perm = parser.getAttributeValue(null, "name");
1151 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 + parser.getPositionDescription());
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157 perm = perm.intern();
1158 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 } else if ("assign-permission".equals(name)) {
1161 String perm = parser.getAttributeValue(null, "name");
1162 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001163 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 + parser.getPositionDescription());
1165 XmlUtils.skipCurrentTag(parser);
1166 continue;
1167 }
1168 String uidStr = parser.getAttributeValue(null, "uid");
1169 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001170 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 + parser.getPositionDescription());
1172 XmlUtils.skipCurrentTag(parser);
1173 continue;
1174 }
1175 int uid = Process.getUidForName(uidStr);
1176 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 + uidStr + "\" at "
1179 + parser.getPositionDescription());
1180 XmlUtils.skipCurrentTag(parser);
1181 continue;
1182 }
1183 perm = perm.intern();
1184 HashSet<String> perms = mSystemPermissions.get(uid);
1185 if (perms == null) {
1186 perms = new HashSet<String>();
1187 mSystemPermissions.put(uid, perms);
1188 }
1189 perms.add(perm);
1190 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 } else if ("library".equals(name)) {
1193 String lname = parser.getAttributeValue(null, "name");
1194 String lfile = parser.getAttributeValue(null, "file");
1195 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001196 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 + parser.getPositionDescription());
1198 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 + parser.getPositionDescription());
1201 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001202 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 mSharedLibraries.put(lname, lfile);
1204 }
1205 XmlUtils.skipCurrentTag(parser);
1206 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001207
Dianne Hackborn49237342009-08-27 20:08:01 -07001208 } else if ("feature".equals(name)) {
1209 String fname = parser.getAttributeValue(null, "name");
1210 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001211 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001212 + parser.getPositionDescription());
1213 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001214 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 FeatureInfo fi = new FeatureInfo();
1216 fi.name = fname;
1217 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219 XmlUtils.skipCurrentTag(parser);
1220 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } else {
1223 XmlUtils.skipCurrentTag(parser);
1224 continue;
1225 }
1226
1227 }
1228 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001229 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001231 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
1234
1235 void readPermission(XmlPullParser parser, String name)
1236 throws IOException, XmlPullParserException {
1237
1238 name = name.intern();
1239
1240 BasePermission bp = mSettings.mPermissions.get(name);
1241 if (bp == null) {
1242 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1243 mSettings.mPermissions.put(name, bp);
1244 }
1245 int outerDepth = parser.getDepth();
1246 int type;
1247 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1248 && (type != XmlPullParser.END_TAG
1249 || parser.getDepth() > outerDepth)) {
1250 if (type == XmlPullParser.END_TAG
1251 || type == XmlPullParser.TEXT) {
1252 continue;
1253 }
1254
1255 String tagName = parser.getName();
1256 if ("group".equals(tagName)) {
1257 String gidStr = parser.getAttributeValue(null, "gid");
1258 if (gidStr != null) {
1259 int gid = Process.getGidForName(gidStr);
1260 bp.gids = appendInt(bp.gids, gid);
1261 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001262 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 + parser.getPositionDescription());
1264 }
1265 }
1266 XmlUtils.skipCurrentTag(parser);
1267 }
1268 }
1269
1270 static int[] appendInt(int[] cur, int val) {
1271 if (cur == null) {
1272 return new int[] { val };
1273 }
1274 final int N = cur.length;
1275 for (int i=0; i<N; i++) {
1276 if (cur[i] == val) {
1277 return cur;
1278 }
1279 }
1280 int[] ret = new int[N+1];
1281 System.arraycopy(cur, 0, ret, 0, N);
1282 ret[N] = val;
1283 return ret;
1284 }
1285
1286 static int[] appendInts(int[] cur, int[] add) {
1287 if (add == null) return cur;
1288 if (cur == null) return add;
1289 final int N = add.length;
1290 for (int i=0; i<N; i++) {
1291 cur = appendInt(cur, add[i]);
1292 }
1293 return cur;
1294 }
1295
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001296 static int[] removeInt(int[] cur, int val) {
1297 if (cur == null) {
1298 return null;
1299 }
1300 final int N = cur.length;
1301 for (int i=0; i<N; i++) {
1302 if (cur[i] == val) {
1303 int[] ret = new int[N-1];
1304 if (i > 0) {
1305 System.arraycopy(cur, 0, ret, 0, i);
1306 }
1307 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001308 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001309 }
1310 return ret;
1311 }
1312 }
1313 return cur;
1314 }
1315
1316 static int[] removeInts(int[] cur, int[] rem) {
1317 if (rem == null) return cur;
1318 if (cur == null) return cur;
1319 final int N = rem.length;
1320 for (int i=0; i<N; i++) {
1321 cur = removeInt(cur, rem[i]);
1322 }
1323 return cur;
1324 }
1325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001327 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1328 // The package has been uninstalled but has retained data and resources.
1329 return PackageParser.generatePackageInfo(p, null, flags);
1330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 final PackageSetting ps = (PackageSetting)p.mExtras;
1332 if (ps == null) {
1333 return null;
1334 }
1335 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1336 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1337 }
1338
1339 public PackageInfo getPackageInfo(String packageName, int flags) {
1340 synchronized (mPackages) {
1341 PackageParser.Package p = mPackages.get(packageName);
1342 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001343 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 + ": " + p);
1345 if (p != null) {
1346 return generatePackageInfo(p, flags);
1347 }
1348 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1349 return generatePackageInfoFromSettingsLP(packageName, flags);
1350 }
1351 }
1352 return null;
1353 }
1354
Dianne Hackborn47096932010-02-11 15:57:09 -08001355 public String[] currentToCanonicalPackageNames(String[] names) {
1356 String[] out = new String[names.length];
1357 synchronized (mPackages) {
1358 for (int i=names.length-1; i>=0; i--) {
1359 PackageSetting ps = mSettings.mPackages.get(names[i]);
1360 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1361 }
1362 }
1363 return out;
1364 }
1365
1366 public String[] canonicalToCurrentPackageNames(String[] names) {
1367 String[] out = new String[names.length];
1368 synchronized (mPackages) {
1369 for (int i=names.length-1; i>=0; i--) {
1370 String cur = mSettings.mRenamedPackages.get(names[i]);
1371 out[i] = cur != null ? cur : names[i];
1372 }
1373 }
1374 return out;
1375 }
1376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 public int getPackageUid(String packageName) {
1378 synchronized (mPackages) {
1379 PackageParser.Package p = mPackages.get(packageName);
1380 if(p != null) {
1381 return p.applicationInfo.uid;
1382 }
1383 PackageSetting ps = mSettings.mPackages.get(packageName);
1384 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1385 return -1;
1386 }
1387 p = ps.pkg;
1388 return p != null ? p.applicationInfo.uid : -1;
1389 }
1390 }
1391
1392 public int[] getPackageGids(String packageName) {
1393 synchronized (mPackages) {
1394 PackageParser.Package p = mPackages.get(packageName);
1395 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001396 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 + ": " + p);
1398 if (p != null) {
1399 final PackageSetting ps = (PackageSetting)p.mExtras;
1400 final SharedUserSetting suid = ps.sharedUser;
1401 return suid != null ? suid.gids : ps.gids;
1402 }
1403 }
1404 // stupid thing to indicate an error.
1405 return new int[0];
1406 }
1407
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001408 static final PermissionInfo generatePermissionInfo(
1409 BasePermission bp, int flags) {
1410 if (bp.perm != null) {
1411 return PackageParser.generatePermissionInfo(bp.perm, flags);
1412 }
1413 PermissionInfo pi = new PermissionInfo();
1414 pi.name = bp.name;
1415 pi.packageName = bp.sourcePackage;
1416 pi.nonLocalizedLabel = bp.name;
1417 pi.protectionLevel = bp.protectionLevel;
1418 return pi;
1419 }
1420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 public PermissionInfo getPermissionInfo(String name, int flags) {
1422 synchronized (mPackages) {
1423 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001424 if (p != null) {
1425 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427 return null;
1428 }
1429 }
1430
1431 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1432 synchronized (mPackages) {
1433 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1434 for (BasePermission p : mSettings.mPermissions.values()) {
1435 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001436 if (p.perm == null || p.perm.info.group == null) {
1437 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001440 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1442 }
1443 }
1444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 if (out.size() > 0) {
1447 return out;
1448 }
1449 return mPermissionGroups.containsKey(group) ? out : null;
1450 }
1451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1454 synchronized (mPackages) {
1455 return PackageParser.generatePermissionGroupInfo(
1456 mPermissionGroups.get(name), flags);
1457 }
1458 }
1459
1460 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1461 synchronized (mPackages) {
1462 final int N = mPermissionGroups.size();
1463 ArrayList<PermissionGroupInfo> out
1464 = new ArrayList<PermissionGroupInfo>(N);
1465 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1466 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1467 }
1468 return out;
1469 }
1470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1473 PackageSetting ps = mSettings.mPackages.get(packageName);
1474 if(ps != null) {
1475 if(ps.pkg == null) {
1476 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1477 if(pInfo != null) {
1478 return pInfo.applicationInfo;
1479 }
1480 return null;
1481 }
1482 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1483 }
1484 return null;
1485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1488 PackageSetting ps = mSettings.mPackages.get(packageName);
1489 if(ps != null) {
1490 if(ps.pkg == null) {
1491 ps.pkg = new PackageParser.Package(packageName);
1492 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001493 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1494 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1495 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1496 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001497 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001498 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500 return generatePackageInfo(ps.pkg, flags);
1501 }
1502 return null;
1503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1506 synchronized (mPackages) {
1507 PackageParser.Package p = mPackages.get(packageName);
1508 if (Config.LOGV) Log.v(
1509 TAG, "getApplicationInfo " + packageName
1510 + ": " + p);
1511 if (p != null) {
1512 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001513 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
1515 if ("android".equals(packageName)||"system".equals(packageName)) {
1516 return mAndroidApplication;
1517 }
1518 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1519 return generateApplicationInfoFromSettingsLP(packageName, flags);
1520 }
1521 }
1522 return null;
1523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001524
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.CLEAR_APP_CACHE, null);
1529 // Queue up an async operation since clearing cache may take a little while.
1530 mHandler.post(new Runnable() {
1531 public void run() {
1532 mHandler.removeCallbacks(this);
1533 int retCode = -1;
1534 if (mInstaller != null) {
1535 retCode = mInstaller.freeCache(freeStorageSize);
1536 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001537 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 } //end if mInstaller
1540 if (observer != null) {
1541 try {
1542 observer.onRemoveCompleted(null, (retCode >= 0));
1543 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001544 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546 }
1547 }
1548 });
1549 }
1550
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001551 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001552 mContext.enforceCallingOrSelfPermission(
1553 android.Manifest.permission.CLEAR_APP_CACHE, null);
1554 // Queue up an async operation since clearing cache may take a little while.
1555 mHandler.post(new Runnable() {
1556 public void run() {
1557 mHandler.removeCallbacks(this);
1558 int retCode = -1;
1559 if (mInstaller != null) {
1560 retCode = mInstaller.freeCache(freeStorageSize);
1561 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001562 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001563 }
1564 }
1565 if(pi != null) {
1566 try {
1567 // Callback via pending intent
1568 int code = (retCode >= 0) ? 1 : 0;
1569 pi.sendIntent(null, code, null,
1570 null, null);
1571 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001572 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001573 }
1574 }
1575 }
1576 });
1577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1580 synchronized (mPackages) {
1581 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001582
1583 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001585 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587 if (mResolveComponentName.equals(component)) {
1588 return mResolveActivity;
1589 }
1590 }
1591 return null;
1592 }
1593
1594 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1595 synchronized (mPackages) {
1596 PackageParser.Activity a = mReceivers.mActivities.get(component);
1597 if (Config.LOGV) Log.v(
1598 TAG, "getReceiverInfo " + component + ": " + a);
1599 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1600 return PackageParser.generateActivityInfo(a, flags);
1601 }
1602 }
1603 return null;
1604 }
1605
1606 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1607 synchronized (mPackages) {
1608 PackageParser.Service s = mServices.mServices.get(component);
1609 if (Config.LOGV) Log.v(
1610 TAG, "getServiceInfo " + component + ": " + s);
1611 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1612 return PackageParser.generateServiceInfo(s, flags);
1613 }
1614 }
1615 return null;
1616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001617
Dianne Hackborn361199b2010-08-30 17:42:07 -07001618 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1619 synchronized (mPackages) {
1620 PackageParser.Provider p = mProvidersByComponent.get(component);
1621 if (Config.LOGV) Log.v(
1622 TAG, "getProviderInfo " + component + ": " + p);
1623 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1624 return PackageParser.generateProviderInfo(p, flags);
1625 }
1626 }
1627 return null;
1628 }
1629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 public String[] getSystemSharedLibraryNames() {
1631 Set<String> libSet;
1632 synchronized (mPackages) {
1633 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001634 int size = libSet.size();
1635 if (size > 0) {
1636 String[] libs = new String[size];
1637 libSet.toArray(libs);
1638 return libs;
1639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001641 return null;
1642 }
1643
1644 public FeatureInfo[] getSystemAvailableFeatures() {
1645 Collection<FeatureInfo> featSet;
1646 synchronized (mPackages) {
1647 featSet = mAvailableFeatures.values();
1648 int size = featSet.size();
1649 if (size > 0) {
1650 FeatureInfo[] features = new FeatureInfo[size+1];
1651 featSet.toArray(features);
1652 FeatureInfo fi = new FeatureInfo();
1653 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1654 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1655 features[size] = fi;
1656 return features;
1657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
1659 return null;
1660 }
1661
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001662 public boolean hasSystemFeature(String name) {
1663 synchronized (mPackages) {
1664 return mAvailableFeatures.containsKey(name);
1665 }
1666 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 public int checkPermission(String permName, String pkgName) {
1669 synchronized (mPackages) {
1670 PackageParser.Package p = mPackages.get(pkgName);
1671 if (p != null && p.mExtras != null) {
1672 PackageSetting ps = (PackageSetting)p.mExtras;
1673 if (ps.sharedUser != null) {
1674 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1675 return PackageManager.PERMISSION_GRANTED;
1676 }
1677 } else if (ps.grantedPermissions.contains(permName)) {
1678 return PackageManager.PERMISSION_GRANTED;
1679 }
1680 }
1681 }
1682 return PackageManager.PERMISSION_DENIED;
1683 }
1684
1685 public int checkUidPermission(String permName, int uid) {
1686 synchronized (mPackages) {
1687 Object obj = mSettings.getUserIdLP(uid);
1688 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001689 GrantedPermissions gp = (GrantedPermissions)obj;
1690 if (gp.grantedPermissions.contains(permName)) {
1691 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693 } else {
1694 HashSet<String> perms = mSystemPermissions.get(uid);
1695 if (perms != null && perms.contains(permName)) {
1696 return PackageManager.PERMISSION_GRANTED;
1697 }
1698 }
1699 }
1700 return PackageManager.PERMISSION_DENIED;
1701 }
1702
1703 private BasePermission findPermissionTreeLP(String permName) {
1704 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1705 if (permName.startsWith(bp.name) &&
1706 permName.length() > bp.name.length() &&
1707 permName.charAt(bp.name.length()) == '.') {
1708 return bp;
1709 }
1710 }
1711 return null;
1712 }
1713
1714 private BasePermission checkPermissionTreeLP(String permName) {
1715 if (permName != null) {
1716 BasePermission bp = findPermissionTreeLP(permName);
1717 if (bp != null) {
1718 if (bp.uid == Binder.getCallingUid()) {
1719 return bp;
1720 }
1721 throw new SecurityException("Calling uid "
1722 + Binder.getCallingUid()
1723 + " is not allowed to add to permission tree "
1724 + bp.name + " owned by uid " + bp.uid);
1725 }
1726 }
1727 throw new SecurityException("No permission tree found for " + permName);
1728 }
1729
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001730 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1731 if (s1 == null) {
1732 return s2 == null;
1733 }
1734 if (s2 == null) {
1735 return false;
1736 }
1737 if (s1.getClass() != s2.getClass()) {
1738 return false;
1739 }
1740 return s1.equals(s2);
1741 }
1742
1743 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1744 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001745 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001746 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1747 if (!compareStrings(pi1.name, pi2.name)) return false;
1748 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1749 // We'll take care of setting this one.
1750 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1751 // These are not currently stored in settings.
1752 //if (!compareStrings(pi1.group, pi2.group)) return false;
1753 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1754 //if (pi1.labelRes != pi2.labelRes) return false;
1755 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1756 return true;
1757 }
1758
1759 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1760 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1761 throw new SecurityException("Label must be specified in permission");
1762 }
1763 BasePermission tree = checkPermissionTreeLP(info.name);
1764 BasePermission bp = mSettings.mPermissions.get(info.name);
1765 boolean added = bp == null;
1766 boolean changed = true;
1767 if (added) {
1768 bp = new BasePermission(info.name, tree.sourcePackage,
1769 BasePermission.TYPE_DYNAMIC);
1770 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1771 throw new SecurityException(
1772 "Not allowed to modify non-dynamic permission "
1773 + info.name);
1774 } else {
1775 if (bp.protectionLevel == info.protectionLevel
1776 && bp.perm.owner.equals(tree.perm.owner)
1777 && bp.uid == tree.uid
1778 && comparePermissionInfos(bp.perm.info, info)) {
1779 changed = false;
1780 }
1781 }
1782 bp.protectionLevel = info.protectionLevel;
1783 bp.perm = new PackageParser.Permission(tree.perm.owner,
1784 new PermissionInfo(info));
1785 bp.perm.info.packageName = tree.perm.info.packageName;
1786 bp.uid = tree.uid;
1787 if (added) {
1788 mSettings.mPermissions.put(info.name, bp);
1789 }
1790 if (changed) {
1791 if (!async) {
1792 mSettings.writeLP();
1793 } else {
1794 scheduleWriteSettingsLocked();
1795 }
1796 }
1797 return added;
1798 }
1799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 public boolean addPermission(PermissionInfo info) {
1801 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001802 return addPermissionLocked(info, false);
1803 }
1804 }
1805
1806 public boolean addPermissionAsync(PermissionInfo info) {
1807 synchronized (mPackages) {
1808 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
1811
1812 public void removePermission(String name) {
1813 synchronized (mPackages) {
1814 checkPermissionTreeLP(name);
1815 BasePermission bp = mSettings.mPermissions.get(name);
1816 if (bp != null) {
1817 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1818 throw new SecurityException(
1819 "Not allowed to modify non-dynamic permission "
1820 + name);
1821 }
1822 mSettings.mPermissions.remove(name);
1823 mSettings.writeLP();
1824 }
1825 }
1826 }
1827
Dianne Hackborn854060af2009-07-09 18:14:31 -07001828 public boolean isProtectedBroadcast(String actionName) {
1829 synchronized (mPackages) {
1830 return mProtectedBroadcasts.contains(actionName);
1831 }
1832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 public int checkSignatures(String pkg1, String pkg2) {
1835 synchronized (mPackages) {
1836 PackageParser.Package p1 = mPackages.get(pkg1);
1837 PackageParser.Package p2 = mPackages.get(pkg2);
1838 if (p1 == null || p1.mExtras == null
1839 || p2 == null || p2.mExtras == null) {
1840 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1841 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001842 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844 }
1845
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001846 public int checkUidSignatures(int uid1, int uid2) {
1847 synchronized (mPackages) {
1848 Signature[] s1;
1849 Signature[] s2;
1850 Object obj = mSettings.getUserIdLP(uid1);
1851 if (obj != null) {
1852 if (obj instanceof SharedUserSetting) {
1853 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1854 } else if (obj instanceof PackageSetting) {
1855 s1 = ((PackageSetting)obj).signatures.mSignatures;
1856 } else {
1857 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1858 }
1859 } else {
1860 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1861 }
1862 obj = mSettings.getUserIdLP(uid2);
1863 if (obj != null) {
1864 if (obj instanceof SharedUserSetting) {
1865 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1866 } else if (obj instanceof PackageSetting) {
1867 s2 = ((PackageSetting)obj).signatures.mSignatures;
1868 } else {
1869 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1870 }
1871 } else {
1872 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1873 }
1874 return checkSignaturesLP(s1, s2);
1875 }
1876 }
1877
1878 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1879 if (s1 == null) {
1880 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1882 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1883 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001884 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1886 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001887 HashSet<Signature> set1 = new HashSet<Signature>();
1888 for (Signature sig : s1) {
1889 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001891 HashSet<Signature> set2 = new HashSet<Signature>();
1892 for (Signature sig : s2) {
1893 set2.add(sig);
1894 }
1895 // Make sure s2 contains all signatures in s1.
1896 if (set1.equals(set2)) {
1897 return PackageManager.SIGNATURE_MATCH;
1898 }
1899 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
1901
1902 public String[] getPackagesForUid(int uid) {
1903 synchronized (mPackages) {
1904 Object obj = mSettings.getUserIdLP(uid);
1905 if (obj instanceof SharedUserSetting) {
1906 SharedUserSetting sus = (SharedUserSetting)obj;
1907 final int N = sus.packages.size();
1908 String[] res = new String[N];
1909 Iterator<PackageSetting> it = sus.packages.iterator();
1910 int i=0;
1911 while (it.hasNext()) {
1912 res[i++] = it.next().name;
1913 }
1914 return res;
1915 } else if (obj instanceof PackageSetting) {
1916 PackageSetting ps = (PackageSetting)obj;
1917 return new String[] { ps.name };
1918 }
1919 }
1920 return null;
1921 }
1922
1923 public String getNameForUid(int uid) {
1924 synchronized (mPackages) {
1925 Object obj = mSettings.getUserIdLP(uid);
1926 if (obj instanceof SharedUserSetting) {
1927 SharedUserSetting sus = (SharedUserSetting)obj;
1928 return sus.name + ":" + sus.userId;
1929 } else if (obj instanceof PackageSetting) {
1930 PackageSetting ps = (PackageSetting)obj;
1931 return ps.name;
1932 }
1933 }
1934 return null;
1935 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 public int getUidForSharedUser(String sharedUserName) {
1938 if(sharedUserName == null) {
1939 return -1;
1940 }
1941 synchronized (mPackages) {
1942 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1943 if(suid == null) {
1944 return -1;
1945 }
1946 return suid.userId;
1947 }
1948 }
1949
1950 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1951 int flags) {
1952 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001953 return chooseBestActivity(intent, resolvedType, flags, query);
1954 }
1955
Mihai Predaeae850c2009-05-13 10:13:48 +02001956 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1957 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 if (query != null) {
1959 final int N = query.size();
1960 if (N == 1) {
1961 return query.get(0);
1962 } else if (N > 1) {
1963 // If there is more than one activity with the same priority,
1964 // then let the user decide between them.
1965 ResolveInfo r0 = query.get(0);
1966 ResolveInfo r1 = query.get(1);
1967 if (false) {
1968 System.out.println(r0.activityInfo.name +
1969 "=" + r0.priority + " vs " +
1970 r1.activityInfo.name +
1971 "=" + r1.priority);
1972 }
1973 // If the first activity has a higher priority, or a different
1974 // default, then it is always desireable to pick it.
1975 if (r0.priority != r1.priority
1976 || r0.preferredOrder != r1.preferredOrder
1977 || r0.isDefault != r1.isDefault) {
1978 return query.get(0);
1979 }
1980 // If we have saved a preference for a preferred activity for
1981 // this Intent, use that.
1982 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1983 flags, query, r0.priority);
1984 if (ri != null) {
1985 return ri;
1986 }
1987 return mResolveInfo;
1988 }
1989 }
1990 return null;
1991 }
1992
1993 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1994 int flags, List<ResolveInfo> query, int priority) {
1995 synchronized (mPackages) {
1996 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1997 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001998 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2000 if (prefs != null && prefs.size() > 0) {
2001 // First figure out how good the original match set is.
2002 // We will only allow preferred activities that came
2003 // from the same match quality.
2004 int match = 0;
2005 final int N = query.size();
2006 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2007 for (int j=0; j<N; j++) {
2008 ResolveInfo ri = query.get(j);
2009 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2010 + ": 0x" + Integer.toHexString(match));
2011 if (ri.match > match) match = ri.match;
2012 }
2013 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2014 + Integer.toHexString(match));
2015 match &= IntentFilter.MATCH_CATEGORY_MASK;
2016 final int M = prefs.size();
2017 for (int i=0; i<M; i++) {
2018 PreferredActivity pa = prefs.get(i);
2019 if (pa.mMatch != match) {
2020 continue;
2021 }
2022 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2023 if (DEBUG_PREFERRED) {
2024 Log.v(TAG, "Got preferred activity:");
2025 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2026 }
2027 if (ai != null) {
2028 for (int j=0; j<N; j++) {
2029 ResolveInfo ri = query.get(j);
2030 if (!ri.activityInfo.applicationInfo.packageName
2031 .equals(ai.applicationInfo.packageName)) {
2032 continue;
2033 }
2034 if (!ri.activityInfo.name.equals(ai.name)) {
2035 continue;
2036 }
2037
2038 // Okay we found a previously set preferred app.
2039 // If the result set is different from when this
2040 // was created, we need to clear it and re-ask the
2041 // user their preference.
2042 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002043 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 + intent + " type " + resolvedType);
2045 mSettings.mPreferredActivities.removeFilter(pa);
2046 return null;
2047 }
2048
2049 // Yay!
2050 return ri;
2051 }
2052 }
2053 }
2054 }
2055 }
2056 return null;
2057 }
2058
2059 public List<ResolveInfo> queryIntentActivities(Intent intent,
2060 String resolvedType, int flags) {
2061 ComponentName comp = intent.getComponent();
2062 if (comp != null) {
2063 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2064 ActivityInfo ai = getActivityInfo(comp, flags);
2065 if (ai != null) {
2066 ResolveInfo ri = new ResolveInfo();
2067 ri.activityInfo = ai;
2068 list.add(ri);
2069 }
2070 return list;
2071 }
2072
2073 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002074 String pkgName = intent.getPackage();
2075 if (pkgName == null) {
2076 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2077 resolvedType, flags);
2078 }
2079 PackageParser.Package pkg = mPackages.get(pkgName);
2080 if (pkg != null) {
2081 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2082 resolvedType, flags, pkg.activities);
2083 }
2084 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 }
2086 }
2087
2088 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2089 Intent[] specifics, String[] specificTypes, Intent intent,
2090 String resolvedType, int flags) {
2091 final String resultsAction = intent.getAction();
2092
2093 List<ResolveInfo> results = queryIntentActivities(
2094 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2095 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2096
2097 int specificsPos = 0;
2098 int N;
2099
2100 // todo: note that the algorithm used here is O(N^2). This
2101 // isn't a problem in our current environment, but if we start running
2102 // into situations where we have more than 5 or 10 matches then this
2103 // should probably be changed to something smarter...
2104
2105 // First we go through and resolve each of the specific items
2106 // that were supplied, taking care of removing any corresponding
2107 // duplicate items in the generic resolve list.
2108 if (specifics != null) {
2109 for (int i=0; i<specifics.length; i++) {
2110 final Intent sintent = specifics[i];
2111 if (sintent == null) {
2112 continue;
2113 }
2114
2115 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2116 String action = sintent.getAction();
2117 if (resultsAction != null && resultsAction.equals(action)) {
2118 // If this action was explicitly requested, then don't
2119 // remove things that have it.
2120 action = null;
2121 }
2122 ComponentName comp = sintent.getComponent();
2123 ResolveInfo ri = null;
2124 ActivityInfo ai = null;
2125 if (comp == null) {
2126 ri = resolveIntent(
2127 sintent,
2128 specificTypes != null ? specificTypes[i] : null,
2129 flags);
2130 if (ri == null) {
2131 continue;
2132 }
2133 if (ri == mResolveInfo) {
2134 // ACK! Must do something better with this.
2135 }
2136 ai = ri.activityInfo;
2137 comp = new ComponentName(ai.applicationInfo.packageName,
2138 ai.name);
2139 } else {
2140 ai = getActivityInfo(comp, flags);
2141 if (ai == null) {
2142 continue;
2143 }
2144 }
2145
2146 // Look for any generic query activities that are duplicates
2147 // of this specific one, and remove them from the results.
2148 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2149 N = results.size();
2150 int j;
2151 for (j=specificsPos; j<N; j++) {
2152 ResolveInfo sri = results.get(j);
2153 if ((sri.activityInfo.name.equals(comp.getClassName())
2154 && sri.activityInfo.applicationInfo.packageName.equals(
2155 comp.getPackageName()))
2156 || (action != null && sri.filter.matchAction(action))) {
2157 results.remove(j);
2158 if (Config.LOGV) Log.v(
2159 TAG, "Removing duplicate item from " + j
2160 + " due to specific " + specificsPos);
2161 if (ri == null) {
2162 ri = sri;
2163 }
2164 j--;
2165 N--;
2166 }
2167 }
2168
2169 // Add this specific item to its proper place.
2170 if (ri == null) {
2171 ri = new ResolveInfo();
2172 ri.activityInfo = ai;
2173 }
2174 results.add(specificsPos, ri);
2175 ri.specificIndex = i;
2176 specificsPos++;
2177 }
2178 }
2179
2180 // Now we go through the remaining generic results and remove any
2181 // duplicate actions that are found here.
2182 N = results.size();
2183 for (int i=specificsPos; i<N-1; i++) {
2184 final ResolveInfo rii = results.get(i);
2185 if (rii.filter == null) {
2186 continue;
2187 }
2188
2189 // Iterate over all of the actions of this result's intent
2190 // filter... typically this should be just one.
2191 final Iterator<String> it = rii.filter.actionsIterator();
2192 if (it == null) {
2193 continue;
2194 }
2195 while (it.hasNext()) {
2196 final String action = it.next();
2197 if (resultsAction != null && resultsAction.equals(action)) {
2198 // If this action was explicitly requested, then don't
2199 // remove things that have it.
2200 continue;
2201 }
2202 for (int j=i+1; j<N; j++) {
2203 final ResolveInfo rij = results.get(j);
2204 if (rij.filter != null && rij.filter.hasAction(action)) {
2205 results.remove(j);
2206 if (Config.LOGV) Log.v(
2207 TAG, "Removing duplicate item from " + j
2208 + " due to action " + action + " at " + i);
2209 j--;
2210 N--;
2211 }
2212 }
2213 }
2214
2215 // If the caller didn't request filter information, drop it now
2216 // so we don't have to marshall/unmarshall it.
2217 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2218 rii.filter = null;
2219 }
2220 }
2221
2222 // Filter out the caller activity if so requested.
2223 if (caller != null) {
2224 N = results.size();
2225 for (int i=0; i<N; i++) {
2226 ActivityInfo ainfo = results.get(i).activityInfo;
2227 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2228 && caller.getClassName().equals(ainfo.name)) {
2229 results.remove(i);
2230 break;
2231 }
2232 }
2233 }
2234
2235 // If the caller didn't request filter information,
2236 // drop them now so we don't have to
2237 // marshall/unmarshall it.
2238 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2239 N = results.size();
2240 for (int i=0; i<N; i++) {
2241 results.get(i).filter = null;
2242 }
2243 }
2244
2245 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2246 return results;
2247 }
2248
2249 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2250 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002251 ComponentName comp = intent.getComponent();
2252 if (comp != null) {
2253 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2254 ActivityInfo ai = getReceiverInfo(comp, flags);
2255 if (ai != null) {
2256 ResolveInfo ri = new ResolveInfo();
2257 ri.activityInfo = ai;
2258 list.add(ri);
2259 }
2260 return list;
2261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002264 String pkgName = intent.getPackage();
2265 if (pkgName == null) {
2266 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2267 resolvedType, flags);
2268 }
2269 PackageParser.Package pkg = mPackages.get(pkgName);
2270 if (pkg != null) {
2271 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2272 resolvedType, flags, pkg.receivers);
2273 }
2274 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 }
2276 }
2277
2278 public ResolveInfo resolveService(Intent intent, String resolvedType,
2279 int flags) {
2280 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2281 flags);
2282 if (query != null) {
2283 if (query.size() >= 1) {
2284 // If there is more than one service with the same priority,
2285 // just arbitrarily pick the first one.
2286 return query.get(0);
2287 }
2288 }
2289 return null;
2290 }
2291
2292 public List<ResolveInfo> queryIntentServices(Intent intent,
2293 String resolvedType, int flags) {
2294 ComponentName comp = intent.getComponent();
2295 if (comp != null) {
2296 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2297 ServiceInfo si = getServiceInfo(comp, flags);
2298 if (si != null) {
2299 ResolveInfo ri = new ResolveInfo();
2300 ri.serviceInfo = si;
2301 list.add(ri);
2302 }
2303 return list;
2304 }
2305
2306 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002307 String pkgName = intent.getPackage();
2308 if (pkgName == null) {
2309 return (List<ResolveInfo>)mServices.queryIntent(intent,
2310 resolvedType, flags);
2311 }
2312 PackageParser.Package pkg = mPackages.get(pkgName);
2313 if (pkg != null) {
2314 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2315 resolvedType, flags, pkg.services);
2316 }
2317 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
2319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 public List<PackageInfo> getInstalledPackages(int flags) {
2322 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2323
2324 synchronized (mPackages) {
2325 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2326 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2327 while (i.hasNext()) {
2328 final PackageSetting ps = i.next();
2329 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2330 if(psPkg != null) {
2331 finalList.add(psPkg);
2332 }
2333 }
2334 }
2335 else {
2336 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2337 while (i.hasNext()) {
2338 final PackageParser.Package p = i.next();
2339 if (p.applicationInfo != null) {
2340 PackageInfo pi = generatePackageInfo(p, flags);
2341 if(pi != null) {
2342 finalList.add(pi);
2343 }
2344 }
2345 }
2346 }
2347 }
2348 return finalList;
2349 }
2350
2351 public List<ApplicationInfo> getInstalledApplications(int flags) {
2352 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2353 synchronized(mPackages) {
2354 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2355 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2356 while (i.hasNext()) {
2357 final PackageSetting ps = i.next();
2358 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2359 if(ai != null) {
2360 finalList.add(ai);
2361 }
2362 }
2363 }
2364 else {
2365 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2366 while (i.hasNext()) {
2367 final PackageParser.Package p = i.next();
2368 if (p.applicationInfo != null) {
2369 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2370 if(ai != null) {
2371 finalList.add(ai);
2372 }
2373 }
2374 }
2375 }
2376 }
2377 return finalList;
2378 }
2379
2380 public List<ApplicationInfo> getPersistentApplications(int flags) {
2381 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2382
2383 synchronized (mPackages) {
2384 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2385 while (i.hasNext()) {
2386 PackageParser.Package p = i.next();
2387 if (p.applicationInfo != null
2388 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002389 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002390 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 }
2392 }
2393 }
2394
2395 return finalList;
2396 }
2397
2398 public ProviderInfo resolveContentProvider(String name, int flags) {
2399 synchronized (mPackages) {
2400 final PackageParser.Provider provider = mProviders.get(name);
2401 return provider != null
2402 && mSettings.isEnabledLP(provider.info, flags)
2403 && (!mSafeMode || (provider.info.applicationInfo.flags
2404 &ApplicationInfo.FLAG_SYSTEM) != 0)
2405 ? PackageParser.generateProviderInfo(provider, flags)
2406 : null;
2407 }
2408 }
2409
Fred Quintana718d8a22009-04-29 17:53:20 -07002410 /**
2411 * @deprecated
2412 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 public void querySyncProviders(List outNames, List outInfo) {
2414 synchronized (mPackages) {
2415 Iterator<Map.Entry<String, PackageParser.Provider>> i
2416 = mProviders.entrySet().iterator();
2417
2418 while (i.hasNext()) {
2419 Map.Entry<String, PackageParser.Provider> entry = i.next();
2420 PackageParser.Provider p = entry.getValue();
2421
2422 if (p.syncable
2423 && (!mSafeMode || (p.info.applicationInfo.flags
2424 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2425 outNames.add(entry.getKey());
2426 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2427 }
2428 }
2429 }
2430 }
2431
2432 public List<ProviderInfo> queryContentProviders(String processName,
2433 int uid, int flags) {
2434 ArrayList<ProviderInfo> finalList = null;
2435
2436 synchronized (mPackages) {
2437 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2438 while (i.hasNext()) {
2439 PackageParser.Provider p = i.next();
2440 if (p.info.authority != null
2441 && (processName == null ||
2442 (p.info.processName.equals(processName)
2443 && p.info.applicationInfo.uid == uid))
2444 && mSettings.isEnabledLP(p.info, flags)
2445 && (!mSafeMode || (p.info.applicationInfo.flags
2446 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2447 if (finalList == null) {
2448 finalList = new ArrayList<ProviderInfo>(3);
2449 }
2450 finalList.add(PackageParser.generateProviderInfo(p,
2451 flags));
2452 }
2453 }
2454 }
2455
2456 if (finalList != null) {
2457 Collections.sort(finalList, mProviderInitOrderSorter);
2458 }
2459
2460 return finalList;
2461 }
2462
2463 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2464 int flags) {
2465 synchronized (mPackages) {
2466 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2467 return PackageParser.generateInstrumentationInfo(i, flags);
2468 }
2469 }
2470
2471 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2472 int flags) {
2473 ArrayList<InstrumentationInfo> finalList =
2474 new ArrayList<InstrumentationInfo>();
2475
2476 synchronized (mPackages) {
2477 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2478 while (i.hasNext()) {
2479 PackageParser.Instrumentation p = i.next();
2480 if (targetPackage == null
2481 || targetPackage.equals(p.info.targetPackage)) {
2482 finalList.add(PackageParser.generateInstrumentationInfo(p,
2483 flags));
2484 }
2485 }
2486 }
2487
2488 return finalList;
2489 }
2490
2491 private void scanDirLI(File dir, int flags, int scanMode) {
2492 Log.d(TAG, "Scanning app dir " + dir);
2493
2494 String[] files = dir.list();
2495
2496 int i;
2497 for (i=0; i<files.length; i++) {
2498 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002499 if (!isPackageFilename(files[i])) {
2500 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002501 continue;
2502 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002503 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002505 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002506 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2507 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002508 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002509 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002510 file.delete();
2511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 }
2513 }
2514
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002515 private static File getSettingsProblemFile() {
2516 File dataDir = Environment.getDataDirectory();
2517 File systemDir = new File(dataDir, "system");
2518 File fname = new File(systemDir, "uiderrors.txt");
2519 return fname;
2520 }
2521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 private static void reportSettingsProblem(int priority, String msg) {
2523 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002524 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 FileOutputStream out = new FileOutputStream(fname, true);
2526 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002527 SimpleDateFormat formatter = new SimpleDateFormat();
2528 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2529 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 pw.close();
2531 FileUtils.setPermissions(
2532 fname.toString(),
2533 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2534 -1, -1);
2535 } catch (java.io.IOException e) {
2536 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002537 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 }
2539
2540 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2541 PackageParser.Package pkg, File srcFile, int parseFlags) {
2542 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002543 if (ps != null
2544 && ps.codePath.equals(srcFile)
2545 && ps.getTimeStamp() == srcFile.lastModified()) {
2546 if (ps.signatures.mSignatures != null
2547 && ps.signatures.mSignatures.length != 0) {
2548 // Optimization: reuse the existing cached certificates
2549 // if the package appears to be unchanged.
2550 pkg.mSignatures = ps.signatures.mSignatures;
2551 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 }
Jeff Browne7600722010-04-07 18:28:23 -07002553
2554 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002555 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002556 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2557 }
2558
2559 if (!pp.collectCertificates(pkg, parseFlags)) {
2560 mLastScanError = pp.getParseError();
2561 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 }
2563 }
2564 return true;
2565 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 /*
2568 * Scan a package and return the newly parsed package.
2569 * Returns null in case of errors and the error code is stored in mLastScanError
2570 */
2571 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002572 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002574 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002576 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002579 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 if (pkg == null) {
2581 mLastScanError = pp.getParseError();
2582 return null;
2583 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002584 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 PackageSetting updatedPkg;
2586 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002587 // Look to see if we already know about this package.
2588 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002589 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002590 // This package has been renamed to its original name. Let's
2591 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002592 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002593 }
2594 // If there was no original package, see one for the real package name.
2595 if (ps == null) {
2596 ps = mSettings.peekPackageLP(pkg.packageName);
2597 }
2598 // Check to see if this package could be hiding/updating a system
2599 // package. Must look for it either under the original or real
2600 // package name depending on our state.
2601 updatedPkg = mSettings.mDisabledSysPackages.get(
2602 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002604 // First check if this is a system package that may involve an update
2605 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2606 if (!ps.codePath.equals(scanFile)) {
2607 // The path has changed from what was last scanned... check the
2608 // version of the new path against what we have stored to determine
2609 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002610 if (pkg.mVersionCode < ps.versionCode) {
2611 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002612 // Ignore entry. Skip it.
2613 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2614 + "ignored: updated version " + ps.versionCode
2615 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002616 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2617 return null;
2618 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 // The current app on the system partion is better than
2620 // what we have updated to on the data partition; switch
2621 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002622 // At this point, its safely assumed that package installation for
2623 // apps in system partition will go through. If not there won't be a working
2624 // version of the app
2625 synchronized (mPackages) {
2626 // Just remove the loaded entries from package lists.
2627 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002628 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002629 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002630 + "reverting from " + ps.codePathString
2631 + ": new version " + pkg.mVersionCode
2632 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002633 InstallArgs args = new FileInstallArgs(ps.codePathString,
2634 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002635 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002636 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 }
2639 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002640 if (updatedPkg != null) {
2641 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2642 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2643 }
2644 // Verify certificates against what was last scanned
2645 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002646 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002647 return null;
2648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 // The apk is forward locked (not public) if its code and resources
2650 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002651 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002653 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002654 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002655
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002656 String codePath = null;
2657 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002658 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2659 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002660 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002661 } else {
2662 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002663 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002664 }
2665 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002666 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002667 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002668 codePath = pkg.mScanPath;
2669 // Set application objects path explicitly.
2670 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002672 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 }
2674
Kenny Root85387d72010-08-26 10:13:11 -07002675 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2676 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002677 pkg.mPath = pkg.mScanPath = destCodePath;
2678 pkg.applicationInfo.sourceDir = destCodePath;
2679 pkg.applicationInfo.publicSourceDir = destResPath;
2680 }
2681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 private static String fixProcessName(String defProcessName,
2683 String processName, int uid) {
2684 if (processName == null) {
2685 return defProcessName;
2686 }
2687 return processName;
2688 }
2689
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002690 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002691 PackageParser.Package pkg) {
2692 if (pkgSetting.signatures.mSignatures != null) {
2693 // Already existing package. Make sure signatures match
2694 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2695 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002696 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002697 + " signatures do not match the previously installed version; ignoring!");
2698 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 return false;
2700 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002701 }
2702 // Check for shared user signatures
2703 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2704 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2705 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2706 Slog.e(TAG, "Package " + pkg.packageName
2707 + " has no signatures that match those in shared user "
2708 + pkgSetting.sharedUser.name + "; ignoring!");
2709 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2710 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 }
2713 return true;
2714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002715
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002716 public boolean performDexOpt(String packageName) {
2717 if (!mNoDexOpt) {
2718 return false;
2719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002720
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002721 PackageParser.Package p;
2722 synchronized (mPackages) {
2723 p = mPackages.get(packageName);
2724 if (p == null || p.mDidDexOpt) {
2725 return false;
2726 }
2727 }
2728 synchronized (mInstallLock) {
2729 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2730 }
2731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002733 static final int DEX_OPT_SKIPPED = 0;
2734 static final int DEX_OPT_PERFORMED = 1;
2735 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2738 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002739 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002740 String path = pkg.mScanPath;
2741 int ret = 0;
2742 try {
2743 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002744 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002745 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002746 pkg.mDidDexOpt = true;
2747 performed = true;
2748 }
2749 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002750 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002751 ret = -1;
2752 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002753 Slog.w(TAG, "IOException reading apk: " + path, e);
2754 ret = -1;
2755 } catch (dalvik.system.StaleDexCacheError e) {
2756 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2757 ret = -1;
2758 } catch (Exception e) {
2759 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002760 ret = -1;
2761 }
2762 if (ret < 0) {
2763 //error from installer
2764 return DEX_OPT_FAILED;
2765 }
2766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002767
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002768 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2769 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002770
2771 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2772 return Environment.isEncryptedFilesystemEnabled() &&
2773 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2774 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002775
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002776 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2777 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002778 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002779 + " to " + newPkg.packageName
2780 + ": old package not in system partition");
2781 return false;
2782 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002783 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002784 + " to " + newPkg.packageName
2785 + ": old package still exists");
2786 return false;
2787 }
2788 return true;
2789 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002790
2791 private File getDataPathForPackage(PackageParser.Package pkg) {
2792 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2793 File dataPath;
2794 if (useEncryptedFSDir) {
2795 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2796 } else {
2797 dataPath = new File(mAppDataDir, pkg.packageName);
2798 }
2799 return dataPath;
2800 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002801
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002802 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2803 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002804 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002805 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2806 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002807 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002808 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002809 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2810 return null;
2811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 mScanningPath = scanFile;
2813 if (pkg == null) {
2814 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2815 return null;
2816 }
2817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2819 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2820 }
2821
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002822 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 synchronized (mPackages) {
2824 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002825 Slog.w(TAG, "*************************************************");
2826 Slog.w(TAG, "Core android package being redefined. Skipping.");
2827 Slog.w(TAG, " file=" + mScanningPath);
2828 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2830 return null;
2831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 // Set up information for our fall-back user intent resolution
2834 // activity.
2835 mPlatformPackage = pkg;
2836 pkg.mVersionCode = mSdkVersion;
2837 mAndroidApplication = pkg.applicationInfo;
2838 mResolveActivity.applicationInfo = mAndroidApplication;
2839 mResolveActivity.name = ResolverActivity.class.getName();
2840 mResolveActivity.packageName = mAndroidApplication.packageName;
2841 mResolveActivity.processName = mAndroidApplication.processName;
2842 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2843 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2844 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2845 mResolveActivity.exported = true;
2846 mResolveActivity.enabled = true;
2847 mResolveInfo.activityInfo = mResolveActivity;
2848 mResolveInfo.priority = 0;
2849 mResolveInfo.preferredOrder = 0;
2850 mResolveInfo.match = 0;
2851 mResolveComponentName = new ComponentName(
2852 mAndroidApplication.packageName, mResolveActivity.name);
2853 }
2854 }
2855
2856 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002857 TAG, "Scanning package " + pkg.packageName);
2858 if (mPackages.containsKey(pkg.packageName)
2859 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002860 Slog.w(TAG, "*************************************************");
2861 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002863 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2865 return null;
2866 }
2867
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002868 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002869 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2870 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 SharedUserSetting suid = null;
2873 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002874
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002875 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2876 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002877 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002878 pkg.mRealPackage = null;
2879 pkg.mAdoptPermissions = null;
2880 }
2881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 synchronized (mPackages) {
2883 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002884 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2885 if (mTmpSharedLibraries == null ||
2886 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2887 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2888 }
2889 int num = 0;
2890 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2891 for (int i=0; i<N; i++) {
2892 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002894 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002896 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2898 return null;
2899 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002900 mTmpSharedLibraries[num] = file;
2901 num++;
2902 }
2903 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2904 for (int i=0; i<N; i++) {
2905 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2906 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002907 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002908 + " desires unavailable shared library "
2909 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2910 } else {
2911 mTmpSharedLibraries[num] = file;
2912 num++;
2913 }
2914 }
2915 if (num > 0) {
2916 pkg.usesLibraryFiles = new String[num];
2917 System.arraycopy(mTmpSharedLibraries, 0,
2918 pkg.usesLibraryFiles, 0, num);
2919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002920
Dianne Hackborn49237342009-08-27 20:08:01 -07002921 if (pkg.reqFeatures != null) {
2922 N = pkg.reqFeatures.size();
2923 for (int i=0; i<N; i++) {
2924 FeatureInfo fi = pkg.reqFeatures.get(i);
2925 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2926 // Don't care.
2927 continue;
2928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002929
Dianne Hackborn49237342009-08-27 20:08:01 -07002930 if (fi.name != null) {
2931 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002932 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002933 + " requires unavailable feature "
2934 + fi.name + "; failing!");
2935 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2936 return null;
2937 }
2938 }
2939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 if (pkg.mSharedUserId != null) {
2944 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2945 pkg.applicationInfo.flags, true);
2946 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002947 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 + " for shared user failed");
2949 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2950 return null;
2951 }
2952 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2953 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2954 + suid.userId + "): packages=" + suid.packages);
2955 }
2956 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002957
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002958 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002959 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 Log.w(TAG, "WAITING FOR DEBUGGER");
2961 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002962 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2963 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002964 }
2965 }
2966
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002967 // Check if we are renaming from an original package name.
2968 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002969 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002970 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002971 // This package may need to be renamed to a previously
2972 // installed name. Let's check on that...
2973 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002974 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 // This package had originally been installed as the
2976 // original name, and we have already taken care of
2977 // transitioning to the new one. Just update the new
2978 // one to continue using the old name.
2979 realName = pkg.mRealPackage;
2980 if (!pkg.packageName.equals(renamed)) {
2981 // Callers into this function may have already taken
2982 // care of renaming the package; only do it here if
2983 // it is not already done.
2984 pkg.setPackageName(renamed);
2985 }
2986
Dianne Hackbornc1552392010-03-03 16:19:01 -08002987 } else {
2988 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2989 if ((origPackage=mSettings.peekPackageLP(
2990 pkg.mOriginalPackages.get(i))) != null) {
2991 // We do have the package already installed under its
2992 // original name... should we use it?
2993 if (!verifyPackageUpdate(origPackage, pkg)) {
2994 // New package is not compatible with original.
2995 origPackage = null;
2996 continue;
2997 } else if (origPackage.sharedUser != null) {
2998 // Make sure uid is compatible between packages.
2999 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003000 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003001 + " to " + pkg.packageName + ": old uid "
3002 + origPackage.sharedUser.name
3003 + " differs from " + pkg.mSharedUserId);
3004 origPackage = null;
3005 continue;
3006 }
3007 } else {
3008 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3009 + pkg.packageName + " to old name " + origPackage.name);
3010 }
3011 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003012 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003013 }
3014 }
3015 }
3016
3017 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003018 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003019 + " was transferred to another, but its .apk remains");
3020 }
3021
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003022 // Just create the setting, don't add it yet. For already existing packages
3023 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003024 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 destResourceFile, pkg.applicationInfo.flags, true, false);
3026 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003027 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3029 return null;
3030 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003031
3032 if (pkgSetting.origPackage != null) {
3033 // If we are first transitioning from an original package,
3034 // fix up the new package's name now. We need to do this after
3035 // looking up the package under its new name, so getPackageLP
3036 // can take care of fiddling things correctly.
3037 pkg.setPackageName(origPackage.name);
3038
3039 // File a report about this.
3040 String msg = "New package " + pkgSetting.realName
3041 + " renamed to replace old package " + pkgSetting.name;
3042 reportSettingsProblem(Log.WARN, msg);
3043
3044 // Make a note of it.
3045 mTransferedPackages.add(origPackage.name);
3046
3047 // No longer need to retain this.
3048 pkgSetting.origPackage = null;
3049 }
3050
3051 if (realName != null) {
3052 // Make a note of it.
3053 mTransferedPackages.add(pkg.packageName);
3054 }
3055
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003056 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3058 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 pkg.applicationInfo.uid = pkgSetting.userId;
3061 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003062
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003063 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003064 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 return null;
3066 }
3067 // The signature has changed, but this package is in the system
3068 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003069 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 // However... if this package is part of a shared user, but it
3071 // doesn't match the signature of the shared user, let's fail.
3072 // What this means is that you can't change the signatures
3073 // associated with an overall shared user, which doesn't seem all
3074 // that unreasonable.
3075 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003076 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3077 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3078 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3080 return null;
3081 }
3082 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003083 // File a report about this.
3084 String msg = "System package " + pkg.packageName
3085 + " signature changed; retaining data.";
3086 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003088
The Android Open Source Project10592532009-03-18 17:39:46 -07003089 // Verify that this new package doesn't have any content providers
3090 // that conflict with existing packages. Only do this if the
3091 // package isn't already installed, since we don't want to break
3092 // things that are installed.
3093 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3094 int N = pkg.providers.size();
3095 int i;
3096 for (i=0; i<N; i++) {
3097 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003098 if (p.info.authority != null) {
3099 String names[] = p.info.authority.split(";");
3100 for (int j = 0; j < names.length; j++) {
3101 if (mProviders.containsKey(names[j])) {
3102 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003103 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003104 " (in package " + pkg.applicationInfo.packageName +
3105 ") is already used by "
3106 + ((other != null && other.getComponentName() != null)
3107 ? other.getComponentName().getPackageName() : "?"));
3108 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3109 return null;
3110 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003111 }
3112 }
3113 }
3114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 }
3116
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003117 final String pkgName = pkg.packageName;
3118
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003119 if (pkg.mAdoptPermissions != null) {
3120 // This package wants to adopt ownership of permissions from
3121 // another package.
3122 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3123 String origName = pkg.mAdoptPermissions.get(i);
3124 PackageSetting orig = mSettings.peekPackageLP(origName);
3125 if (orig != null) {
3126 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003127 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003128 + origName + " to " + pkg.packageName);
3129 mSettings.transferPermissions(origName, pkg.packageName);
3130 }
3131 }
3132 }
3133 }
3134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 long scanFileTime = scanFile.lastModified();
3136 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3137 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3138 pkg.applicationInfo.processName = fixProcessName(
3139 pkg.applicationInfo.packageName,
3140 pkg.applicationInfo.processName,
3141 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142
3143 File dataPath;
3144 if (mPlatformPackage == pkg) {
3145 // The system package is special.
3146 dataPath = new File (Environment.getDataDirectory(), "system");
3147 pkg.applicationInfo.dataDir = dataPath.getPath();
3148 } else {
3149 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003150 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003151 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003152
3153 boolean uidError = false;
3154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 if (dataPath.exists()) {
3156 mOutPermissions[1] = 0;
3157 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003158
3159 // If we have mismatched owners for the data path, we have a
3160 // problem (unless we're running in the simulator.)
3161 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 boolean recovered = false;
3163 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3164 // If this is a system app, we can at least delete its
3165 // current data so the application will still work.
3166 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003167 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003168 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 // Old data gone!
3170 String msg = "System package " + pkg.packageName
3171 + " has changed from uid: "
3172 + mOutPermissions[1] + " to "
3173 + pkg.applicationInfo.uid + "; old data erased";
3174 reportSettingsProblem(Log.WARN, msg);
3175 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003178 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 pkg.applicationInfo.uid);
3180 if (ret == -1) {
3181 // Ack should not happen!
3182 msg = "System package " + pkg.packageName
3183 + " could not have data directory re-created after delete.";
3184 reportSettingsProblem(Log.WARN, msg);
3185 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3186 return null;
3187 }
3188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 if (!recovered) {
3191 mHasSystemUidErrors = true;
3192 }
3193 }
3194 if (!recovered) {
3195 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3196 + pkg.applicationInfo.uid + "/fs_"
3197 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003198 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 String msg = "Package " + pkg.packageName
3200 + " has mismatched uid: "
3201 + mOutPermissions[1] + " on disk, "
3202 + pkg.applicationInfo.uid + " in settings";
3203 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003204 mSettings.mReadMessages.append(msg);
3205 mSettings.mReadMessages.append('\n');
3206 uidError = true;
3207 if (!pkgSetting.uidError) {
3208 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 }
3211 }
3212 }
3213 pkg.applicationInfo.dataDir = dataPath.getPath();
3214 } else {
3215 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3216 Log.v(TAG, "Want this data dir: " + dataPath);
3217 //invoke installer to do the actual installation
3218 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003219 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 pkg.applicationInfo.uid);
3221 if(ret < 0) {
3222 // Error from installer
3223 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3224 return null;
3225 }
3226 } else {
3227 dataPath.mkdirs();
3228 if (dataPath.exists()) {
3229 FileUtils.setPermissions(
3230 dataPath.toString(),
3231 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3232 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3233 }
3234 }
3235 if (dataPath.exists()) {
3236 pkg.applicationInfo.dataDir = dataPath.getPath();
3237 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003238 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 pkg.applicationInfo.dataDir = null;
3240 }
3241 }
Kenny Root85387d72010-08-26 10:13:11 -07003242
3243 /*
3244 * Set the data dir to the default "/data/data/<package name>/lib"
3245 * if we got here without anyone telling us different (e.g., apps
3246 * stored on SD card have their native libraries stored in the ASEC
3247 * container with the APK).
3248 */
3249 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3250 pkg.applicationInfo.nativeLibraryDir = new File(dataPath, LIB_DIR_NAME).getPath();
3251 }
3252
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003253 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 }
3255
Kenny Root85387d72010-08-26 10:13:11 -07003256 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 if (mInstaller != null) {
3258 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003259 /* Note: We don't want to unpack the native binaries for
3260 * system applications, unless they have been updated
3261 * (the binaries are already under /system/lib).
3262 * Also, don't unpack libs for apps on the external card
3263 * since they should have their libraries in the ASEC
3264 * container already.
3265 *
3266 * In other words, we're going to unpack the binaries
3267 * only for non-system apps and system app upgrades.
3268 */
3269 if ((!isSystemApp(pkg) || isUpdatedSystemApp(pkg)) && !isExternal(pkg)) {
3270 Log.i(TAG, path + " changed; unpacking");
3271 File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3272 sharedLibraryDir.mkdir();
3273 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003275 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003276
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003277 if ((scanMode&SCAN_NO_DEX) == 0) {
3278 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3280 return null;
3281 }
3282 }
3283 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 if (mFactoryTest && pkg.requestedPermissions.contains(
3286 android.Manifest.permission.FACTORY_TEST)) {
3287 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3288 }
3289
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003290 // Request the ActivityManager to kill the process(only for existing packages)
3291 // so that we do not end up in a confused state while the user is still using the older
3292 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003293 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003294 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003295 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003296 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003299 // We don't expect installation to fail beyond this point,
3300 if ((scanMode&SCAN_MONITOR) != 0) {
3301 mAppDirs.put(pkg.mPath, pkg);
3302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003304 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003306 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003307 // Make sure we don't accidentally delete its data.
3308 mSettings.mPackagesToBeCleaned.remove(pkgName);
3309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 int N = pkg.providers.size();
3311 StringBuilder r = null;
3312 int i;
3313 for (i=0; i<N; i++) {
3314 PackageParser.Provider p = pkg.providers.get(i);
3315 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3316 p.info.processName, pkg.applicationInfo.uid);
3317 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3318 p.info.name), p);
3319 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003320 if (p.info.authority != null) {
3321 String names[] = p.info.authority.split(";");
3322 p.info.authority = null;
3323 for (int j = 0; j < names.length; j++) {
3324 if (j == 1 && p.syncable) {
3325 // We only want the first authority for a provider to possibly be
3326 // syncable, so if we already added this provider using a different
3327 // authority clear the syncable flag. We copy the provider before
3328 // changing it because the mProviders object contains a reference
3329 // to a provider that we don't want to change.
3330 // Only do this for the second authority since the resulting provider
3331 // object can be the same for all future authorities for this provider.
3332 p = new PackageParser.Provider(p);
3333 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003335 if (!mProviders.containsKey(names[j])) {
3336 mProviders.put(names[j], p);
3337 if (p.info.authority == null) {
3338 p.info.authority = names[j];
3339 } else {
3340 p.info.authority = p.info.authority + ";" + names[j];
3341 }
3342 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3343 Log.d(TAG, "Registered content provider: " + names[j] +
3344 ", className = " + p.info.name +
3345 ", isSyncable = " + p.info.isSyncable);
3346 } else {
3347 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003348 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003349 " (in package " + pkg.applicationInfo.packageName +
3350 "): name already used by "
3351 + ((other != null && other.getComponentName() != null)
3352 ? other.getComponentName().getPackageName() : "?"));
3353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 }
3355 }
3356 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3357 if (r == null) {
3358 r = new StringBuilder(256);
3359 } else {
3360 r.append(' ');
3361 }
3362 r.append(p.info.name);
3363 }
3364 }
3365 if (r != null) {
3366 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3367 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 N = pkg.services.size();
3370 r = null;
3371 for (i=0; i<N; i++) {
3372 PackageParser.Service s = pkg.services.get(i);
3373 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3374 s.info.processName, pkg.applicationInfo.uid);
3375 mServices.addService(s);
3376 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3377 if (r == null) {
3378 r = new StringBuilder(256);
3379 } else {
3380 r.append(' ');
3381 }
3382 r.append(s.info.name);
3383 }
3384 }
3385 if (r != null) {
3386 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3387 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 N = pkg.receivers.size();
3390 r = null;
3391 for (i=0; i<N; i++) {
3392 PackageParser.Activity a = pkg.receivers.get(i);
3393 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3394 a.info.processName, pkg.applicationInfo.uid);
3395 mReceivers.addActivity(a, "receiver");
3396 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3397 if (r == null) {
3398 r = new StringBuilder(256);
3399 } else {
3400 r.append(' ');
3401 }
3402 r.append(a.info.name);
3403 }
3404 }
3405 if (r != null) {
3406 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3407 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 N = pkg.activities.size();
3410 r = null;
3411 for (i=0; i<N; i++) {
3412 PackageParser.Activity a = pkg.activities.get(i);
3413 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3414 a.info.processName, pkg.applicationInfo.uid);
3415 mActivities.addActivity(a, "activity");
3416 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3417 if (r == null) {
3418 r = new StringBuilder(256);
3419 } else {
3420 r.append(' ');
3421 }
3422 r.append(a.info.name);
3423 }
3424 }
3425 if (r != null) {
3426 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3427 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 N = pkg.permissionGroups.size();
3430 r = null;
3431 for (i=0; i<N; i++) {
3432 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3433 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3434 if (cur == null) {
3435 mPermissionGroups.put(pg.info.name, pg);
3436 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3437 if (r == null) {
3438 r = new StringBuilder(256);
3439 } else {
3440 r.append(' ');
3441 }
3442 r.append(pg.info.name);
3443 }
3444 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003445 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 + pg.info.packageName + " ignored: original from "
3447 + cur.info.packageName);
3448 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3449 if (r == null) {
3450 r = new StringBuilder(256);
3451 } else {
3452 r.append(' ');
3453 }
3454 r.append("DUP:");
3455 r.append(pg.info.name);
3456 }
3457 }
3458 }
3459 if (r != null) {
3460 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3461 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 N = pkg.permissions.size();
3464 r = null;
3465 for (i=0; i<N; i++) {
3466 PackageParser.Permission p = pkg.permissions.get(i);
3467 HashMap<String, BasePermission> permissionMap =
3468 p.tree ? mSettings.mPermissionTrees
3469 : mSettings.mPermissions;
3470 p.group = mPermissionGroups.get(p.info.group);
3471 if (p.info.group == null || p.group != null) {
3472 BasePermission bp = permissionMap.get(p.info.name);
3473 if (bp == null) {
3474 bp = new BasePermission(p.info.name, p.info.packageName,
3475 BasePermission.TYPE_NORMAL);
3476 permissionMap.put(p.info.name, bp);
3477 }
3478 if (bp.perm == null) {
3479 if (bp.sourcePackage == null
3480 || bp.sourcePackage.equals(p.info.packageName)) {
3481 BasePermission tree = findPermissionTreeLP(p.info.name);
3482 if (tree == null
3483 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003484 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 bp.perm = p;
3486 bp.uid = pkg.applicationInfo.uid;
3487 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3488 if (r == null) {
3489 r = new StringBuilder(256);
3490 } else {
3491 r.append(' ');
3492 }
3493 r.append(p.info.name);
3494 }
3495 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003496 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 + p.info.packageName + " ignored: base tree "
3498 + tree.name + " is from package "
3499 + tree.sourcePackage);
3500 }
3501 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003502 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 + p.info.packageName + " ignored: original from "
3504 + bp.sourcePackage);
3505 }
3506 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3507 if (r == null) {
3508 r = new StringBuilder(256);
3509 } else {
3510 r.append(' ');
3511 }
3512 r.append("DUP:");
3513 r.append(p.info.name);
3514 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003515 if (bp.perm == p) {
3516 bp.protectionLevel = p.info.protectionLevel;
3517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003519 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 + p.info.packageName + " ignored: no group "
3521 + p.group);
3522 }
3523 }
3524 if (r != null) {
3525 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 N = pkg.instrumentation.size();
3529 r = null;
3530 for (i=0; i<N; i++) {
3531 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3532 a.info.packageName = pkg.applicationInfo.packageName;
3533 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3534 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3535 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003536 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003537 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3539 if (r == null) {
3540 r = new StringBuilder(256);
3541 } else {
3542 r.append(' ');
3543 }
3544 r.append(a.info.name);
3545 }
3546 }
3547 if (r != null) {
3548 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003550
Dianne Hackborn854060af2009-07-09 18:14:31 -07003551 if (pkg.protectedBroadcasts != null) {
3552 N = pkg.protectedBroadcasts.size();
3553 for (i=0; i<N; i++) {
3554 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3555 }
3556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 pkgSetting.setTimeStamp(scanFileTime);
3559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 return pkg;
3562 }
3563
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003564 private void killApplication(String pkgName, int uid) {
3565 // Request the ActivityManager to kill the process(only for existing packages)
3566 // so that we do not end up in a confused state while the user is still using the older
3567 // version of the application while the new one gets installed.
3568 IActivityManager am = ActivityManagerNative.getDefault();
3569 if (am != null) {
3570 try {
3571 am.killApplicationWithUid(pkgName, uid);
3572 } catch (RemoteException e) {
3573 }
3574 }
3575 }
3576
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003577 // Return the path of the directory that will contain the native binaries
3578 // of a given installed package. This is relative to the data path.
3579 //
Kenny Root85387d72010-08-26 10:13:11 -07003580 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3581 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3582 if (nativeLibraryDir != null) {
3583 return new File(nativeLibraryDir);
3584 } else {
3585 // Fall back for old packages
3586 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3587 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003588 }
3589
Kenny Root85387d72010-08-26 10:13:11 -07003590 // Convenience call for removeNativeBinariesLI(File)
3591 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3592 File nativeLibraryDir = getNativeBinaryDirForPackage(pkg);
3593 removeNativeBinariesLI(nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 }
3595
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003596 // Remove the native binaries of a given package. This simply
3597 // gets rid of the files in the 'lib' sub-directory.
Kenny Root85387d72010-08-26 10:13:11 -07003598 public void removeNativeBinariesLI(File binaryDir) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003599 if (DEBUG_NATIVE) {
Kenny Root85387d72010-08-26 10:13:11 -07003600 Slog.w(TAG, "Deleting native binaries from: " + binaryDir.getPath());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003601 }
3602
3603 // Just remove any file in the directory. Since the directory
3604 // is owned by the 'system' UID, the application is not supposed
3605 // to have written anything there.
3606 //
3607 if (binaryDir.exists()) {
Kenny Root85387d72010-08-26 10:13:11 -07003608 File[] binaries = binaryDir.listFiles();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003609 if (binaries != null) {
Kenny Root85387d72010-08-26 10:13:11 -07003610 for (int nn = 0; nn < binaries.length; nn++) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003611 if (DEBUG_NATIVE) {
Kenny Root85387d72010-08-26 10:13:11 -07003612 Slog.d(TAG, " Deleting " + binaries[nn].getName());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003613 }
3614 if (!binaries[nn].delete()) {
Kenny Root85387d72010-08-26 10:13:11 -07003615 Slog.w(TAG, "Could not delete native binary: " + binaries[nn].getPath());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003616 }
3617 }
3618 }
3619 // Do not delete 'lib' directory itself, or this will prevent
3620 // installation of future updates.
3621 }
3622 }
3623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3625 if (chatty && Config.LOGD) Log.d(
3626 TAG, "Removing package " + pkg.applicationInfo.packageName );
3627
3628 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 mPackages.remove(pkg.applicationInfo.packageName);
3632 if (pkg.mPath != null) {
3633 mAppDirs.remove(pkg.mPath);
3634 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 PackageSetting ps = (PackageSetting)pkg.mExtras;
3637 if (ps != null && ps.sharedUser != null) {
3638 // XXX don't do this until the data is removed.
3639 if (false) {
3640 ps.sharedUser.packages.remove(ps);
3641 if (ps.sharedUser.packages.size() == 0) {
3642 // Remove.
3643 }
3644 }
3645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 int N = pkg.providers.size();
3648 StringBuilder r = null;
3649 int i;
3650 for (i=0; i<N; i++) {
3651 PackageParser.Provider p = pkg.providers.get(i);
3652 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3653 p.info.name));
3654 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 /* The is another ContentProvider with this authority when
3657 * this app was installed so this authority is null,
3658 * Ignore it as we don't have to unregister the provider.
3659 */
3660 continue;
3661 }
3662 String names[] = p.info.authority.split(";");
3663 for (int j = 0; j < names.length; j++) {
3664 if (mProviders.get(names[j]) == p) {
3665 mProviders.remove(names[j]);
3666 if (chatty && Config.LOGD) Log.d(
3667 TAG, "Unregistered content provider: " + names[j] +
3668 ", className = " + p.info.name +
3669 ", isSyncable = " + p.info.isSyncable);
3670 }
3671 }
3672 if (chatty) {
3673 if (r == null) {
3674 r = new StringBuilder(256);
3675 } else {
3676 r.append(' ');
3677 }
3678 r.append(p.info.name);
3679 }
3680 }
3681 if (r != null) {
3682 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3683 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 N = pkg.services.size();
3686 r = null;
3687 for (i=0; i<N; i++) {
3688 PackageParser.Service s = pkg.services.get(i);
3689 mServices.removeService(s);
3690 if (chatty) {
3691 if (r == null) {
3692 r = new StringBuilder(256);
3693 } else {
3694 r.append(' ');
3695 }
3696 r.append(s.info.name);
3697 }
3698 }
3699 if (r != null) {
3700 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3701 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 N = pkg.receivers.size();
3704 r = null;
3705 for (i=0; i<N; i++) {
3706 PackageParser.Activity a = pkg.receivers.get(i);
3707 mReceivers.removeActivity(a, "receiver");
3708 if (chatty) {
3709 if (r == null) {
3710 r = new StringBuilder(256);
3711 } else {
3712 r.append(' ');
3713 }
3714 r.append(a.info.name);
3715 }
3716 }
3717 if (r != null) {
3718 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 N = pkg.activities.size();
3722 r = null;
3723 for (i=0; i<N; i++) {
3724 PackageParser.Activity a = pkg.activities.get(i);
3725 mActivities.removeActivity(a, "activity");
3726 if (chatty) {
3727 if (r == null) {
3728 r = new StringBuilder(256);
3729 } else {
3730 r.append(' ');
3731 }
3732 r.append(a.info.name);
3733 }
3734 }
3735 if (r != null) {
3736 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3737 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 N = pkg.permissions.size();
3740 r = null;
3741 for (i=0; i<N; i++) {
3742 PackageParser.Permission p = pkg.permissions.get(i);
3743 boolean tree = false;
3744 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3745 if (bp == null) {
3746 tree = true;
3747 bp = mSettings.mPermissionTrees.get(p.info.name);
3748 }
3749 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003750 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 if (chatty) {
3752 if (r == null) {
3753 r = new StringBuilder(256);
3754 } else {
3755 r.append(' ');
3756 }
3757 r.append(p.info.name);
3758 }
3759 }
3760 }
3761 if (r != null) {
3762 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3763 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 N = pkg.instrumentation.size();
3766 r = null;
3767 for (i=0; i<N; i++) {
3768 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003769 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 if (chatty) {
3771 if (r == null) {
3772 r = new StringBuilder(256);
3773 } else {
3774 r.append(' ');
3775 }
3776 r.append(a.info.name);
3777 }
3778 }
3779 if (r != null) {
3780 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3781 }
3782 }
3783 }
3784
3785 private static final boolean isPackageFilename(String name) {
3786 return name != null && name.endsWith(".apk");
3787 }
3788
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003789 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3790 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3791 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3792 return true;
3793 }
3794 }
3795 return false;
3796 }
3797
3798 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003799 PackageParser.Package pkgInfo, boolean grantPermissions,
3800 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 // Make sure there are no dangling permission trees.
3802 Iterator<BasePermission> it = mSettings.mPermissionTrees
3803 .values().iterator();
3804 while (it.hasNext()) {
3805 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003806 if (bp.packageSetting == null) {
3807 // We may not yet have parsed the package, so just see if
3808 // we still know about its settings.
3809 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3810 }
3811 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003812 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 + " from package " + bp.sourcePackage);
3814 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003815 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3816 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3817 Slog.i(TAG, "Removing old permission tree: " + bp.name
3818 + " from package " + bp.sourcePackage);
3819 grantPermissions = true;
3820 it.remove();
3821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 }
3823 }
3824
3825 // Make sure all dynamic permissions have been assigned to a package,
3826 // and make sure there are no dangling permissions.
3827 it = mSettings.mPermissions.values().iterator();
3828 while (it.hasNext()) {
3829 BasePermission bp = it.next();
3830 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3831 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3832 + bp.name + " pkg=" + bp.sourcePackage
3833 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003834 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 BasePermission tree = findPermissionTreeLP(bp.name);
3836 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003837 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 bp.perm = new PackageParser.Permission(tree.perm.owner,
3839 new PermissionInfo(bp.pendingInfo));
3840 bp.perm.info.packageName = tree.perm.info.packageName;
3841 bp.perm.info.name = bp.name;
3842 bp.uid = tree.uid;
3843 }
3844 }
3845 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003846 if (bp.packageSetting == null) {
3847 // We may not yet have parsed the package, so just see if
3848 // we still know about its settings.
3849 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3850 }
3851 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003852 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 + " from package " + bp.sourcePackage);
3854 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003855 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3856 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3857 Slog.i(TAG, "Removing old permission: " + bp.name
3858 + " from package " + bp.sourcePackage);
3859 grantPermissions = true;
3860 it.remove();
3861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 }
3863 }
3864
3865 // Now update the permissions for all packages, in particular
3866 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003867 if (grantPermissions) {
3868 for (PackageParser.Package pkg : mPackages.values()) {
3869 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003870 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003871 }
3872 }
3873 }
3874
3875 if (pkgInfo != null) {
3876 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 }
3878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3881 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3882 if (ps == null) {
3883 return;
3884 }
3885 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003886 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 if (replace) {
3889 ps.permissionsFixed = false;
3890 if (gp == ps) {
3891 gp.grantedPermissions.clear();
3892 gp.gids = mGlobalGids;
3893 }
3894 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 if (gp.gids == null) {
3897 gp.gids = mGlobalGids;
3898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 final int N = pkg.requestedPermissions.size();
3901 for (int i=0; i<N; i++) {
3902 String name = pkg.requestedPermissions.get(i);
3903 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 if (false) {
3905 if (gp != ps) {
3906 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003907 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003910 if (bp != null && bp.packageSetting != null) {
3911 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003913 boolean allowedSig = false;
3914 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3915 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003917 } else if (bp.packageSetting == null) {
3918 // This permission is invalid; skip it.
3919 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003920 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3921 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3922 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003924 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003926 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003927 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 // For updated system applications, the signatureOrSystem permission
3929 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003930 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3932 if(sysPs.grantedPermissions.contains(perm)) {
3933 allowed = true;
3934 } else {
3935 allowed = false;
3936 }
3937 } else {
3938 allowed = true;
3939 }
3940 }
3941 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003942 if (allowed) {
3943 allowedSig = true;
3944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 } else {
3946 allowed = false;
3947 }
3948 if (false) {
3949 if (gp != ps) {
3950 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3951 }
3952 }
3953 if (allowed) {
3954 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3955 && ps.permissionsFixed) {
3956 // If this is an existing, non-system package, then
3957 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003958 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003960 // Except... if this is a permission that was added
3961 // to the platform (note: need to only do this when
3962 // updating the platform).
3963 final int NP = PackageParser.NEW_PERMISSIONS.length;
3964 for (int ip=0; ip<NP; ip++) {
3965 final PackageParser.NewPermissionInfo npi
3966 = PackageParser.NEW_PERMISSIONS[ip];
3967 if (npi.name.equals(perm)
3968 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3969 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003970 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003971 + pkg.packageName);
3972 break;
3973 }
3974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 }
3976 }
3977 if (allowed) {
3978 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003979 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 gp.grantedPermissions.add(perm);
3981 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003982 } else if (!ps.haveGids) {
3983 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 }
3985 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003986 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 + " to package " + pkg.packageName
3988 + " because it was previously installed without");
3989 }
3990 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003991 if (gp.grantedPermissions.remove(perm)) {
3992 changedPermission = true;
3993 gp.gids = removeInts(gp.gids, bp.gids);
3994 Slog.i(TAG, "Un-granting permission " + perm
3995 + " from package " + pkg.packageName
3996 + " (protectionLevel=" + bp.protectionLevel
3997 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3998 + ")");
3999 } else {
4000 Slog.w(TAG, "Not granting permission " + perm
4001 + " to package " + pkg.packageName
4002 + " (protectionLevel=" + bp.protectionLevel
4003 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4004 + ")");
4005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 }
4007 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004008 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 + " in package " + pkg.packageName);
4010 }
4011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004012
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004013 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004014 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4015 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 // This is the first that we have heard about this package, so the
4017 // permissions we have now selected are fixed until explicitly
4018 // changed.
4019 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004021 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 private final class ActivityIntentResolver
4025 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004026 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004028 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 }
4030
Mihai Preda074edef2009-05-18 17:13:31 +02004031 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004033 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4035 }
4036
Mihai Predaeae850c2009-05-13 10:13:48 +02004037 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4038 ArrayList<PackageParser.Activity> packageActivities) {
4039 if (packageActivities == null) {
4040 return null;
4041 }
4042 mFlags = flags;
4043 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4044 int N = packageActivities.size();
4045 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4046 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004047
4048 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004049 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004050 intentFilters = packageActivities.get(i).intents;
4051 if (intentFilters != null && intentFilters.size() > 0) {
4052 listCut.add(intentFilters);
4053 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004054 }
4055 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4056 }
4057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004059 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 if (SHOW_INFO || Config.LOGV) Log.v(
4061 TAG, " " + type + " " +
4062 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4063 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4064 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004065 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4067 if (SHOW_INFO || Config.LOGV) {
4068 Log.v(TAG, " IntentFilter:");
4069 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4070 }
4071 if (!intent.debugCheck()) {
4072 Log.w(TAG, "==> For Activity " + a.info.name);
4073 }
4074 addFilter(intent);
4075 }
4076 }
4077
4078 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004079 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 if (SHOW_INFO || Config.LOGV) Log.v(
4081 TAG, " " + type + " " +
4082 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4083 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4084 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004085 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4087 if (SHOW_INFO || Config.LOGV) {
4088 Log.v(TAG, " IntentFilter:");
4089 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4090 }
4091 removeFilter(intent);
4092 }
4093 }
4094
4095 @Override
4096 protected boolean allowFilterResult(
4097 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4098 ActivityInfo filterAi = filter.activity.info;
4099 for (int i=dest.size()-1; i>=0; i--) {
4100 ActivityInfo destAi = dest.get(i).activityInfo;
4101 if (destAi.name == filterAi.name
4102 && destAi.packageName == filterAi.packageName) {
4103 return false;
4104 }
4105 }
4106 return true;
4107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004110 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4111 return info.activity.owner.packageName;
4112 }
4113
4114 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4116 int match) {
4117 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4118 return null;
4119 }
4120 final PackageParser.Activity activity = info.activity;
4121 if (mSafeMode && (activity.info.applicationInfo.flags
4122 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4123 return null;
4124 }
4125 final ResolveInfo res = new ResolveInfo();
4126 res.activityInfo = PackageParser.generateActivityInfo(activity,
4127 mFlags);
4128 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4129 res.filter = info;
4130 }
4131 res.priority = info.getPriority();
4132 res.preferredOrder = activity.owner.mPreferredOrder;
4133 //System.out.println("Result: " + res.activityInfo.className +
4134 // " = " + res.priority);
4135 res.match = match;
4136 res.isDefault = info.hasDefault;
4137 res.labelRes = info.labelRes;
4138 res.nonLocalizedLabel = info.nonLocalizedLabel;
4139 res.icon = info.icon;
4140 return res;
4141 }
4142
4143 @Override
4144 protected void sortResults(List<ResolveInfo> results) {
4145 Collections.sort(results, mResolvePrioritySorter);
4146 }
4147
4148 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004149 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004151 out.print(prefix); out.print(
4152 Integer.toHexString(System.identityHashCode(filter.activity)));
4153 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004154 out.print(filter.activity.getComponentShortName());
4155 out.print(" filter ");
4156 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 }
4158
4159// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4160// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4161// final List<ResolveInfo> retList = Lists.newArrayList();
4162// while (i.hasNext()) {
4163// final ResolveInfo resolveInfo = i.next();
4164// if (isEnabledLP(resolveInfo.activityInfo)) {
4165// retList.add(resolveInfo);
4166// }
4167// }
4168// return retList;
4169// }
4170
4171 // Keys are String (activity class name), values are Activity.
4172 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4173 = new HashMap<ComponentName, PackageParser.Activity>();
4174 private int mFlags;
4175 }
4176
4177 private final class ServiceIntentResolver
4178 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004179 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004181 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 }
4183
Mihai Preda074edef2009-05-18 17:13:31 +02004184 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004186 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4188 }
4189
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004190 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4191 ArrayList<PackageParser.Service> packageServices) {
4192 if (packageServices == null) {
4193 return null;
4194 }
4195 mFlags = flags;
4196 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4197 int N = packageServices.size();
4198 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4199 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4200
4201 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4202 for (int i = 0; i < N; ++i) {
4203 intentFilters = packageServices.get(i).intents;
4204 if (intentFilters != null && intentFilters.size() > 0) {
4205 listCut.add(intentFilters);
4206 }
4207 }
4208 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4209 }
4210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004212 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 if (SHOW_INFO || Config.LOGV) Log.v(
4214 TAG, " " + (s.info.nonLocalizedLabel != null
4215 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4216 if (SHOW_INFO || Config.LOGV) Log.v(
4217 TAG, " Class=" + s.info.name);
4218 int NI = s.intents.size();
4219 int j;
4220 for (j=0; j<NI; j++) {
4221 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4222 if (SHOW_INFO || Config.LOGV) {
4223 Log.v(TAG, " IntentFilter:");
4224 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4225 }
4226 if (!intent.debugCheck()) {
4227 Log.w(TAG, "==> For Service " + s.info.name);
4228 }
4229 addFilter(intent);
4230 }
4231 }
4232
4233 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004234 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 if (SHOW_INFO || Config.LOGV) Log.v(
4236 TAG, " " + (s.info.nonLocalizedLabel != null
4237 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4238 if (SHOW_INFO || Config.LOGV) Log.v(
4239 TAG, " Class=" + s.info.name);
4240 int NI = s.intents.size();
4241 int j;
4242 for (j=0; j<NI; j++) {
4243 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4244 if (SHOW_INFO || Config.LOGV) {
4245 Log.v(TAG, " IntentFilter:");
4246 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4247 }
4248 removeFilter(intent);
4249 }
4250 }
4251
4252 @Override
4253 protected boolean allowFilterResult(
4254 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4255 ServiceInfo filterSi = filter.service.info;
4256 for (int i=dest.size()-1; i>=0; i--) {
4257 ServiceInfo destAi = dest.get(i).serviceInfo;
4258 if (destAi.name == filterSi.name
4259 && destAi.packageName == filterSi.packageName) {
4260 return false;
4261 }
4262 }
4263 return true;
4264 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004267 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4268 return info.service.owner.packageName;
4269 }
4270
4271 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4273 int match) {
4274 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4275 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4276 return null;
4277 }
4278 final PackageParser.Service service = info.service;
4279 if (mSafeMode && (service.info.applicationInfo.flags
4280 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4281 return null;
4282 }
4283 final ResolveInfo res = new ResolveInfo();
4284 res.serviceInfo = PackageParser.generateServiceInfo(service,
4285 mFlags);
4286 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4287 res.filter = filter;
4288 }
4289 res.priority = info.getPriority();
4290 res.preferredOrder = service.owner.mPreferredOrder;
4291 //System.out.println("Result: " + res.activityInfo.className +
4292 // " = " + res.priority);
4293 res.match = match;
4294 res.isDefault = info.hasDefault;
4295 res.labelRes = info.labelRes;
4296 res.nonLocalizedLabel = info.nonLocalizedLabel;
4297 res.icon = info.icon;
4298 return res;
4299 }
4300
4301 @Override
4302 protected void sortResults(List<ResolveInfo> results) {
4303 Collections.sort(results, mResolvePrioritySorter);
4304 }
4305
4306 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004307 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004309 out.print(prefix); out.print(
4310 Integer.toHexString(System.identityHashCode(filter.service)));
4311 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004312 out.print(filter.service.getComponentShortName());
4313 out.print(" filter ");
4314 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 }
4316
4317// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4318// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4319// final List<ResolveInfo> retList = Lists.newArrayList();
4320// while (i.hasNext()) {
4321// final ResolveInfo resolveInfo = (ResolveInfo) i;
4322// if (isEnabledLP(resolveInfo.serviceInfo)) {
4323// retList.add(resolveInfo);
4324// }
4325// }
4326// return retList;
4327// }
4328
4329 // Keys are String (activity class name), values are Activity.
4330 private final HashMap<ComponentName, PackageParser.Service> mServices
4331 = new HashMap<ComponentName, PackageParser.Service>();
4332 private int mFlags;
4333 };
4334
4335 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4336 new Comparator<ResolveInfo>() {
4337 public int compare(ResolveInfo r1, ResolveInfo r2) {
4338 int v1 = r1.priority;
4339 int v2 = r2.priority;
4340 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4341 if (v1 != v2) {
4342 return (v1 > v2) ? -1 : 1;
4343 }
4344 v1 = r1.preferredOrder;
4345 v2 = r2.preferredOrder;
4346 if (v1 != v2) {
4347 return (v1 > v2) ? -1 : 1;
4348 }
4349 if (r1.isDefault != r2.isDefault) {
4350 return r1.isDefault ? -1 : 1;
4351 }
4352 v1 = r1.match;
4353 v2 = r2.match;
4354 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4355 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4356 }
4357 };
4358
4359 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4360 new Comparator<ProviderInfo>() {
4361 public int compare(ProviderInfo p1, ProviderInfo p2) {
4362 final int v1 = p1.initOrder;
4363 final int v2 = p2.initOrder;
4364 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4365 }
4366 };
4367
Kenny Root93565c4b2010-06-18 15:46:06 -07004368 private static final boolean DEBUG_OBB = false;
4369
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004370 private static final void sendPackageBroadcast(String action, String pkg,
4371 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 IActivityManager am = ActivityManagerNative.getDefault();
4373 if (am != null) {
4374 try {
4375 final Intent intent = new Intent(action,
4376 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4377 if (extras != null) {
4378 intent.putExtras(extras);
4379 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004380 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004381 am.broadcastIntent(null, intent, null, finishedReceiver,
4382 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 } catch (RemoteException ex) {
4384 }
4385 }
4386 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004387
4388 public String nextPackageToClean(String lastPackage) {
4389 synchronized (mPackages) {
4390 if (!mMediaMounted) {
4391 // If the external storage is no longer mounted at this point,
4392 // the caller may not have been able to delete all of this
4393 // packages files and can not delete any more. Bail.
4394 return null;
4395 }
4396 if (lastPackage != null) {
4397 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4398 }
4399 return mSettings.mPackagesToBeCleaned.size() > 0
4400 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4401 }
4402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004404 void schedulePackageCleaning(String packageName) {
4405 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4406 }
4407
4408 void startCleaningPackages() {
4409 synchronized (mPackages) {
4410 if (!mMediaMounted) {
4411 return;
4412 }
4413 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4414 return;
4415 }
4416 }
4417 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4418 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4419 IActivityManager am = ActivityManagerNative.getDefault();
4420 if (am != null) {
4421 try {
4422 am.startService(null, intent, null);
4423 } catch (RemoteException e) {
4424 }
4425 }
4426 }
4427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 private final class AppDirObserver extends FileObserver {
4429 public AppDirObserver(String path, int mask, boolean isrom) {
4430 super(path, mask);
4431 mRootDir = path;
4432 mIsRom = isrom;
4433 }
4434
4435 public void onEvent(int event, String path) {
4436 String removedPackage = null;
4437 int removedUid = -1;
4438 String addedPackage = null;
4439 int addedUid = -1;
4440
4441 synchronized (mInstallLock) {
4442 String fullPathStr = null;
4443 File fullPath = null;
4444 if (path != null) {
4445 fullPath = new File(mRootDir, path);
4446 fullPathStr = fullPath.getPath();
4447 }
4448
4449 if (Config.LOGV) Log.v(
4450 TAG, "File " + fullPathStr + " changed: "
4451 + Integer.toHexString(event));
4452
4453 if (!isPackageFilename(path)) {
4454 if (Config.LOGV) Log.v(
4455 TAG, "Ignoring change of non-package file: " + fullPathStr);
4456 return;
4457 }
4458
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004459 // Ignore packages that are being installed or
4460 // have just been installed.
4461 if (ignoreCodePath(fullPathStr)) {
4462 return;
4463 }
4464 PackageParser.Package p = null;
4465 synchronized (mPackages) {
4466 p = mAppDirs.get(fullPathStr);
4467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004469 if (p != null) {
4470 removePackageLI(p, true);
4471 removedPackage = p.applicationInfo.packageName;
4472 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473 }
4474 }
4475
4476 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004478 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004479 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4480 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 PackageParser.PARSE_CHATTY |
4482 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004483 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 if (p != null) {
4485 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004486 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004487 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 }
4489 addedPackage = p.applicationInfo.packageName;
4490 addedUid = p.applicationInfo.uid;
4491 }
4492 }
4493 }
4494
4495 synchronized (mPackages) {
4496 mSettings.writeLP();
4497 }
4498 }
4499
4500 if (removedPackage != null) {
4501 Bundle extras = new Bundle(1);
4502 extras.putInt(Intent.EXTRA_UID, removedUid);
4503 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004504 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4505 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
4507 if (addedPackage != null) {
4508 Bundle extras = new Bundle(1);
4509 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004510 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4511 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 }
4513 }
4514
4515 private final String mRootDir;
4516 private final boolean mIsRom;
4517 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 /* Called when a downloaded package installation has been confirmed by the user */
4520 public void installPackage(
4521 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004522 installPackage(packageURI, observer, flags, null);
4523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004524
Jacek Surazski65e13172009-04-28 15:26:38 +02004525 /* Called when a downloaded package installation has been confirmed by the user */
4526 public void installPackage(
4527 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4528 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 mContext.enforceCallingOrSelfPermission(
4530 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004531
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004532 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004533 msg.obj = new InstallParams(packageURI, observer, flags,
4534 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004535 mHandler.sendMessage(msg);
4536 }
4537
Christopher Tate1bb69062010-02-19 17:02:12 -08004538 public void finishPackageInstall(int token) {
4539 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4540 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4541 mHandler.sendMessage(msg);
4542 }
4543
Kenny Root93565c4b2010-06-18 15:46:06 -07004544 public void setPackageObbPath(String packageName, String path) {
4545 if (DEBUG_OBB)
4546 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4547 PackageSetting pkgSetting;
4548 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004549 final int permission = mContext.checkCallingPermission(
4550 android.Manifest.permission.INSTALL_PACKAGES);
4551 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004552 synchronized (mPackages) {
4553 pkgSetting = mSettings.mPackages.get(packageName);
4554 if (pkgSetting == null) {
4555 throw new IllegalArgumentException("Unknown package: " + packageName);
4556 }
4557 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4558 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4559 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4560 + pkgSetting.userId);
4561 }
4562 pkgSetting.obbPathString = path;
4563 mSettings.writeLP();
4564 }
4565 }
4566
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004567 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 // Queue up an async operation since the package installation may take a little while.
4569 mHandler.post(new Runnable() {
4570 public void run() {
4571 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004572 // Result object to be returned
4573 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004574 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004575 res.uid = -1;
4576 res.pkg = null;
4577 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004578 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004579 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004580 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004581 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004582 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004583 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004585
4586 // A restore should be performed at this point if (a) the install
4587 // succeeded, (b) the operation is not an update, and (c) the new
4588 // package has a backupAgent defined.
4589 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004590 boolean doRestore = (!update
4591 && res.pkg != null
4592 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004593
4594 // Set up the post-install work request bookkeeping. This will be used
4595 // and cleaned up by the post-install event handling regardless of whether
4596 // there's a restore pass performed. Token values are >= 1.
4597 int token;
4598 if (mNextInstallToken < 0) mNextInstallToken = 1;
4599 token = mNextInstallToken++;
4600
4601 PostInstallData data = new PostInstallData(args, res);
4602 mRunningInstalls.put(token, data);
4603 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4604
4605 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4606 // Pass responsibility to the Backup Manager. It will perform a
4607 // restore if appropriate, then pass responsibility back to the
4608 // Package Manager to run the post-install observer callbacks
4609 // and broadcasts.
4610 IBackupManager bm = IBackupManager.Stub.asInterface(
4611 ServiceManager.getService(Context.BACKUP_SERVICE));
4612 if (bm != null) {
4613 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4614 + " to BM for possible restore");
4615 try {
4616 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4617 } catch (RemoteException e) {
4618 // can't happen; the backup manager is local
4619 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004620 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004621 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004622 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004623 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004624 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004625 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004627 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004628
4629 if (!doRestore) {
4630 // No restore possible, or the Backup Manager was mysteriously not
4631 // available -- just fire the post-install work request directly.
4632 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4633 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4634 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004636 }
4637 });
4638 }
4639
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004640 abstract class HandlerParams {
4641 final static int MAX_RETRIES = 4;
4642 int retry = 0;
4643 final void startCopy() {
4644 try {
4645 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4646 retry++;
4647 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004648 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004649 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4650 handleServiceError();
4651 return;
4652 } else {
4653 handleStartCopy();
4654 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4655 mHandler.sendEmptyMessage(MCS_UNBIND);
4656 }
4657 } catch (RemoteException e) {
4658 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4659 mHandler.sendEmptyMessage(MCS_RECONNECT);
4660 }
4661 handleReturnCode();
4662 }
4663
4664 final void serviceError() {
4665 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4666 handleServiceError();
4667 handleReturnCode();
4668 }
4669 abstract void handleStartCopy() throws RemoteException;
4670 abstract void handleServiceError();
4671 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004672 }
4673
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004674 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004675 final IPackageInstallObserver observer;
4676 int flags;
4677 final Uri packageURI;
4678 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004679 private InstallArgs mArgs;
4680 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004681 InstallParams(Uri packageURI,
4682 IPackageInstallObserver observer, int flags,
4683 String installerPackageName) {
4684 this.packageURI = packageURI;
4685 this.flags = flags;
4686 this.observer = observer;
4687 this.installerPackageName = installerPackageName;
4688 }
4689
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004690 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4691 String packageName = pkgLite.packageName;
4692 int installLocation = pkgLite.installLocation;
4693 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4694 synchronized (mPackages) {
4695 PackageParser.Package pkg = mPackages.get(packageName);
4696 if (pkg != null) {
4697 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4698 // Check for updated system application.
4699 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4700 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004701 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004702 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4703 }
4704 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4705 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004706 if (onSd) {
4707 // Install flag overrides everything.
4708 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4709 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004710 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004711 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4712 // Application explicitly specified internal.
4713 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4714 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4715 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004716 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004717 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004718 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004719 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4720 }
4721 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004722 }
4723 }
4724 } else {
4725 // Invalid install. Return error code
4726 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4727 }
4728 }
4729 }
4730 // All the special cases have been taken care of.
4731 // Return result based on recommended install location.
4732 if (onSd) {
4733 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4734 }
4735 return pkgLite.recommendedInstallLocation;
4736 }
4737
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004738 /*
4739 * Invoke remote method to get package information and install
4740 * location values. Override install location based on default
4741 * policy if needed and then create install arguments based
4742 * on the install location.
4743 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004744 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004745 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004746 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4747 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004748 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4749 if (onInt && onSd) {
4750 // Check if both bits are set.
4751 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4752 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4753 } else if (fwdLocked && onSd) {
4754 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004755 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004756 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004757 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004758 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004759 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004760 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004761 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4762 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4763 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4764 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4765 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004766 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4767 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4768 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004769 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4770 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004771 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004772 // Override with defaults if needed.
4773 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004774 if (!onSd && !onInt) {
4775 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004776 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4777 // Set the flag to install on external media.
4778 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004779 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004780 } else {
4781 // Make sure the flag for installing on external
4782 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004783 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004784 flags &= ~PackageManager.INSTALL_EXTERNAL;
4785 }
4786 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004787 }
4788 }
4789 // Create the file args now.
4790 mArgs = createInstallArgs(this);
4791 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4792 // Create copy only if we are not in an erroneous state.
4793 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004794 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004795 }
4796 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004797 }
4798
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004799 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004800 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004801 // If mArgs is null, then MCS couldn't be reached. When it
4802 // reconnects, it will try again to install. At that point, this
4803 // will succeed.
4804 if (mArgs != null) {
4805 processPendingInstall(mArgs, mRet);
4806 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004807 }
4808
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004809 @Override
4810 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004811 mArgs = createInstallArgs(this);
4812 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004813 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004814 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004815
4816 /*
4817 * Utility class used in movePackage api.
4818 * srcArgs and targetArgs are not set for invalid flags and make
4819 * sure to do null checks when invoking methods on them.
4820 * We probably want to return ErrorPrams for both failed installs
4821 * and moves.
4822 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004823 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004824 final IPackageMoveObserver observer;
4825 final int flags;
4826 final String packageName;
4827 final InstallArgs srcArgs;
4828 final InstallArgs targetArgs;
4829 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004830
4831 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4832 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004833 this.srcArgs = srcArgs;
4834 this.observer = observer;
4835 this.flags = flags;
4836 this.packageName = packageName;
4837 if (srcArgs != null) {
4838 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004839 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004840 } else {
4841 targetArgs = null;
4842 }
4843 }
4844
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004845 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004846 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4847 // Check for storage space on target medium
4848 if (!targetArgs.checkFreeStorage(mContainerService)) {
4849 Log.w(TAG, "Insufficient storage to install");
4850 return;
4851 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004852 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004853 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004854 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004855 if (DEBUG_SD_INSTALL) {
4856 StringBuilder builder = new StringBuilder();
4857 if (srcArgs != null) {
4858 builder.append("src: ");
4859 builder.append(srcArgs.getCodePath());
4860 }
4861 if (targetArgs != null) {
4862 builder.append(" target : ");
4863 builder.append(targetArgs.getCodePath());
4864 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004865 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004866 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004867 }
4868
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004869 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004870 void handleReturnCode() {
4871 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004872 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4873 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4874 currentStatus = PackageManager.MOVE_SUCCEEDED;
4875 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4876 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4877 }
4878 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004879 }
4880
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004881 @Override
4882 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004883 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004884 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004885 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004886
4887 private InstallArgs createInstallArgs(InstallParams params) {
4888 if (installOnSd(params.flags)) {
4889 return new SdInstallArgs(params);
4890 } else {
4891 return new FileInstallArgs(params);
4892 }
4893 }
4894
Kenny Root85387d72010-08-26 10:13:11 -07004895 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4896 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004897 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004898 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004899 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004900 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004901 }
4902 }
4903
Kenny Root85387d72010-08-26 10:13:11 -07004904 // Used by package mover
4905 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004906 if (installOnSd(flags)) {
4907 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4908 return new SdInstallArgs(packageURI, cid);
4909 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004910 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004911 }
4912 }
4913
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004914 static abstract class InstallArgs {
4915 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004916 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004917 final int flags;
4918 final Uri packageURI;
4919 final String installerPackageName;
4920
4921 InstallArgs(Uri packageURI,
4922 IPackageInstallObserver observer, int flags,
4923 String installerPackageName) {
4924 this.packageURI = packageURI;
4925 this.flags = flags;
4926 this.observer = observer;
4927 this.installerPackageName = installerPackageName;
4928 }
4929
4930 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004931 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004932 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004933 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004934 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004935 abstract String getCodePath();
4936 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004937 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004938 // Need installer lock especially for dex file removal.
4939 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004940 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004941 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004942 }
4943
4944 class FileInstallArgs extends InstallArgs {
4945 File installDir;
4946 String codeFileName;
4947 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004948 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004949 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004950
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004951 FileInstallArgs(InstallParams params) {
4952 super(params.packageURI, params.observer,
4953 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004954 }
4955
Kenny Root85387d72010-08-26 10:13:11 -07004956 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004957 super(null, null, 0, null);
4958 File codeFile = new File(fullCodePath);
4959 installDir = codeFile.getParentFile();
4960 codeFileName = fullCodePath;
4961 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004962 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004963 }
4964
Kenny Root85387d72010-08-26 10:13:11 -07004965 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004966 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004967 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004968 String apkName = getNextCodePath(null, pkgName, ".apk");
4969 codeFileName = new File(installDir, apkName + ".apk").getPath();
4970 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004971 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004972 }
4973
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004974 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4975 return imcs.checkFreeStorage(false, packageURI);
4976 }
4977
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004978 String getCodePath() {
4979 return codeFileName;
4980 }
4981
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004982 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004983 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004984 codeFileName = createTempPackageFile(installDir).getPath();
4985 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004986 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004987 }
4988
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004989 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 if (temp) {
4991 // Generate temp file name
4992 createCopyFile();
4993 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004994 // Get a ParcelFileDescriptor to write to the output file
4995 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004996 if (!created) {
4997 try {
4998 codeFile.createNewFile();
4999 // Set permissions
5000 if (!setPermissions()) {
5001 // Failed setting permissions.
5002 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5003 }
5004 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005005 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005006 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5007 }
5008 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005009 ParcelFileDescriptor out = null;
5010 try {
Kenny Root85387d72010-08-26 10:13:11 -07005011 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005012 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005013 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005014 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5015 }
5016 // Copy the resource now
5017 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5018 try {
5019 if (imcs.copyResource(packageURI, out)) {
5020 ret = PackageManager.INSTALL_SUCCEEDED;
5021 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005022 } finally {
5023 try { if (out != null) out.close(); } catch (IOException e) {}
5024 }
Kenny Root85387d72010-08-26 10:13:11 -07005025
5026 if (!temp) {
5027 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5028 }
5029
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005030 return ret;
5031 }
5032
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005033 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005034 if (status != PackageManager.INSTALL_SUCCEEDED) {
5035 cleanUp();
5036 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005037 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005038 }
5039
5040 boolean doRename(int status, final String pkgName, String oldCodePath) {
5041 if (status != PackageManager.INSTALL_SUCCEEDED) {
5042 cleanUp();
5043 return false;
5044 } else {
5045 // Rename based on packageName
5046 File codeFile = new File(getCodePath());
5047 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5048 File desFile = new File(installDir, apkName + ".apk");
5049 if (!codeFile.renameTo(desFile)) {
5050 return false;
5051 }
5052 // Reset paths since the file has been renamed.
5053 codeFileName = desFile.getPath();
5054 resourceFileName = getResourcePathFromCodePath();
5055 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005056 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005057 // Failed setting permissions.
5058 return false;
5059 }
5060 return true;
5061 }
5062 }
5063
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005064 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005065 if (status != PackageManager.INSTALL_SUCCEEDED) {
5066 cleanUp();
5067 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005068 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005069 }
5070
5071 String getResourcePath() {
5072 return resourceFileName;
5073 }
5074
5075 String getResourcePathFromCodePath() {
5076 String codePath = getCodePath();
5077 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5078 String apkNameOnly = getApkName(codePath);
5079 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5080 } else {
5081 return codePath;
5082 }
5083 }
5084
Kenny Root85387d72010-08-26 10:13:11 -07005085 @Override
5086 String getNativeLibraryPath() {
5087 return libraryPath;
5088 }
5089
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005090 private boolean cleanUp() {
5091 boolean ret = true;
5092 String sourceDir = getCodePath();
5093 String publicSourceDir = getResourcePath();
5094 if (sourceDir != null) {
5095 File sourceFile = new File(sourceDir);
5096 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005097 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005098 ret = false;
5099 }
5100 // Delete application's code and resources
5101 sourceFile.delete();
5102 }
5103 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5104 final File publicSourceFile = new File(publicSourceDir);
5105 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005106 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 }
5108 if (publicSourceFile.exists()) {
5109 publicSourceFile.delete();
5110 }
5111 }
5112 return ret;
5113 }
5114
5115 void cleanUpResourcesLI() {
5116 String sourceDir = getCodePath();
5117 if (cleanUp() && mInstaller != null) {
5118 int retCode = mInstaller.rmdex(sourceDir);
5119 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005120 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005121 + " at location "
5122 + sourceDir + ", retcode=" + retCode);
5123 // we don't consider this to be a failure of the core package deletion
5124 }
5125 }
Kenny Root85387d72010-08-26 10:13:11 -07005126 if (libraryPath != null) {
5127 removeNativeBinariesLI(new File(libraryPath));
5128 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005129 }
5130
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005131 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005132 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005133 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005134 final int filePermissions =
5135 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5136 |FileUtils.S_IROTH;
5137 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5138 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005139 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005140 getCodePath()
5141 + ". The return code was: " + retCode);
5142 // TODO Define new internal error
5143 return false;
5144 }
5145 return true;
5146 }
5147 return true;
5148 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005149
5150 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005151 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005152 cleanUpResourcesLI();
5153 return true;
5154 }
Kenny Root85387d72010-08-26 10:13:11 -07005155
5156 private boolean isFwdLocked() {
5157 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5158 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005159 }
5160
5161 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005162 static final String RES_FILE_NAME = "pkg.apk";
5163
Kenny Root85387d72010-08-26 10:13:11 -07005164 String cid;
5165 String packagePath;
5166 String libraryPath;
5167
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005168 SdInstallArgs(InstallParams params) {
5169 super(params.packageURI, params.observer,
5170 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005171 }
5172
Kenny Root85387d72010-08-26 10:13:11 -07005173 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005174 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005175 // Extract cid from fullCodePath
5176 int eidx = fullCodePath.lastIndexOf("/");
5177 String subStr1 = fullCodePath.substring(0, eidx);
5178 int sidx = subStr1.lastIndexOf("/");
5179 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005180 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005181 }
5182
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005183 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005184 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5185 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005186 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005187 }
5188
5189 SdInstallArgs(Uri packageURI, String cid) {
5190 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005191 this.cid = cid;
5192 }
5193
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005194 void createCopyFile() {
5195 cid = getTempContainerId();
5196 }
5197
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005198 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5199 return imcs.checkFreeStorage(true, packageURI);
5200 }
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 createCopyFile();
5205 }
Kenny Root85387d72010-08-26 10:13:11 -07005206 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005207 packageURI, cid,
5208 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005209 if (newCachePath != null) {
5210 setCachePath(newCachePath);
5211 return PackageManager.INSTALL_SUCCEEDED;
5212 } else {
5213 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5214 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005215 }
5216
5217 @Override
5218 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005219 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005220 }
5221
5222 @Override
5223 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005224 return packagePath;
5225 }
5226
5227 @Override
5228 String getNativeLibraryPath() {
5229 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005230 }
5231
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005232 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005233 if (status != PackageManager.INSTALL_SUCCEEDED) {
5234 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005235 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005236 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005237 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005238 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005239 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5240 Process.SYSTEM_UID);
5241 if (newCachePath != null) {
5242 setCachePath(newCachePath);
5243 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005244 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5245 }
5246 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005247 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005248 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005249 }
5250
5251 boolean doRename(int status, final String pkgName,
5252 String oldCodePath) {
5253 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005254 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005255 if (PackageHelper.isContainerMounted(cid)) {
5256 // Unmount the container
5257 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005258 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005259 return false;
5260 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005261 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005262 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005263 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5264 " which might be stale. Will try to clean up.");
5265 // Clean up the stale container and proceed to recreate.
5266 if (!PackageHelper.destroySdDir(newCacheId)) {
5267 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5268 return false;
5269 }
5270 // Successfully cleaned up stale container. Try to rename again.
5271 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5272 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5273 + " inspite of cleaning it up.");
5274 return false;
5275 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005276 }
5277 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005278 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005279 newCachePath = PackageHelper.mountSdDir(newCacheId,
5280 getEncryptKey(), Process.SYSTEM_UID);
5281 } else {
5282 newCachePath = PackageHelper.getSdDir(newCacheId);
5283 }
5284 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005285 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005286 return false;
5287 }
5288 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005289 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005290 " at new path: " + newCachePath);
5291 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005292 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005293 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005294 }
5295
Kenny Root85387d72010-08-26 10:13:11 -07005296 private void setCachePath(String newCachePath) {
5297 File cachePath = new File(newCachePath);
5298 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5299 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5300 }
5301
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005302 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005303 if (status != PackageManager.INSTALL_SUCCEEDED) {
5304 cleanUp();
5305 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005306 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005307 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005308 PackageHelper.mountSdDir(cid,
5309 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005310 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005312 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005313 }
5314
5315 private void cleanUp() {
5316 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005317 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005318 }
5319
5320 void cleanUpResourcesLI() {
5321 String sourceFile = getCodePath();
5322 // Remove dex file
5323 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005324 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005325 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005326 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005327 + " at location "
5328 + sourceFile.toString() + ", retcode=" + retCode);
5329 // we don't consider this to be a failure of the core package deletion
5330 }
5331 }
5332 cleanUp();
5333 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005334
5335 boolean matchContainer(String app) {
5336 if (cid.startsWith(app)) {
5337 return true;
5338 }
5339 return false;
5340 }
5341
5342 String getPackageName() {
5343 int idx = cid.lastIndexOf("-");
5344 if (idx == -1) {
5345 return cid;
5346 }
5347 return cid.substring(0, idx);
5348 }
5349
5350 boolean doPostDeleteLI(boolean delete) {
5351 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005352 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005353 if (mounted) {
5354 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005355 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005356 }
5357 if (ret && delete) {
5358 cleanUpResourcesLI();
5359 }
5360 return ret;
5361 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005362 };
5363
5364 // Utility method used to create code paths based on package name and available index.
5365 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5366 String idxStr = "";
5367 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005368 // Fall back to default value of idx=1 if prefix is not
5369 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005370 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005371 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005372 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005373 if (subStr.endsWith(suffix)) {
5374 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005375 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005376 // If oldCodePath already contains prefix find out the
5377 // ending index to either increment or decrement.
5378 int sidx = subStr.lastIndexOf(prefix);
5379 if (sidx != -1) {
5380 subStr = subStr.substring(sidx + prefix.length());
5381 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005382 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5383 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005384 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005385 try {
5386 idx = Integer.parseInt(subStr);
5387 if (idx <= 1) {
5388 idx++;
5389 } else {
5390 idx--;
5391 }
5392 } catch(NumberFormatException e) {
5393 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005394 }
5395 }
5396 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005397 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005398 return prefix + idxStr;
5399 }
5400
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005401 // Utility method used to ignore ADD/REMOVE events
5402 // by directory observer.
5403 private static boolean ignoreCodePath(String fullPathStr) {
5404 String apkName = getApkName(fullPathStr);
5405 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5406 if (idx != -1 && ((idx+1) < apkName.length())) {
5407 // Make sure the package ends with a numeral
5408 String version = apkName.substring(idx+1);
5409 try {
5410 Integer.parseInt(version);
5411 return true;
5412 } catch (NumberFormatException e) {}
5413 }
5414 return false;
5415 }
5416
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005417 // Utility method that returns the relative package path with respect
5418 // to the installation directory. Like say for /data/data/com.test-1.apk
5419 // string com.test-1 is returned.
5420 static String getApkName(String codePath) {
5421 if (codePath == null) {
5422 return null;
5423 }
5424 int sidx = codePath.lastIndexOf("/");
5425 int eidx = codePath.lastIndexOf(".");
5426 if (eidx == -1) {
5427 eidx = codePath.length();
5428 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005429 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005430 return null;
5431 }
5432 return codePath.substring(sidx+1, eidx);
5433 }
5434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 class PackageInstalledInfo {
5436 String name;
5437 int uid;
5438 PackageParser.Package pkg;
5439 int returnCode;
5440 PackageRemovedInfo removedInfo;
5441 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 /*
5444 * Install a non-existing package.
5445 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005446 private void installNewPackageLI(PackageParser.Package pkg,
5447 int parseFlags,
5448 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005449 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005451 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005452
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005453 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 res.name = pkgName;
5455 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005456 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5457 // A package with the same name is already installed, though
5458 // it has been renamed to an older name. The package we
5459 // are trying to install should be installed as an update to
5460 // the existing one, but that has not been requested, so bail.
5461 Slog.w(TAG, "Attempt to re-install " + pkgName
5462 + " without first uninstalling package running as "
5463 + mSettings.mRenamedPackages.get(pkgName));
5464 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5465 return;
5466 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005467 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005469 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 + " without first uninstalling.");
5471 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5472 return;
5473 }
5474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005476 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005478 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5480 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5481 }
5482 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005483 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005484 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 res);
5486 // delete the partially installed application. the data directory will have to be
5487 // restored if it was already existing
5488 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5489 // remove package from internal structures. Note that we want deletePackageX to
5490 // delete the package data and cache directories that it created in
5491 // scanPackageLocked, unless those directories existed before we even tried to
5492 // install.
5493 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005494 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5496 res.removedInfo);
5497 }
5498 }
5499 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005500
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005501 private void replacePackageLI(PackageParser.Package pkg,
5502 int parseFlags,
5503 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005504 String installerPackageName, PackageInstalledInfo res) {
5505
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005506 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005507 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 // First find the old package info and check signatures
5509 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005510 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005511 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005512 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005513 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5514 return;
5515 }
5516 }
Kenny Root85387d72010-08-26 10:13:11 -07005517 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005518 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005519 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005521 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 }
5523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005526 PackageParser.Package pkg,
5527 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005528 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 PackageParser.Package newPackage = null;
5530 String pkgName = deletedPackage.packageName;
5531 boolean deletedPkg = true;
5532 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005533
Jacek Surazski65e13172009-04-28 15:26:38 +02005534 String oldInstallerPackageName = null;
5535 synchronized (mPackages) {
5536 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005540 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 res.removedInfo)) {
5542 // If the existing package was'nt successfully deleted
5543 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5544 deletedPkg = false;
5545 } else {
5546 // Successfully deleted the old package. Now proceed with re-installation
5547 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005548 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005550 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5552 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005553 }
5554 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005555 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005556 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 res);
5558 updatedSettings = true;
5559 }
5560 }
5561
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005562 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563 // remove package from internal structures. Note that we want deletePackageX to
5564 // delete the package data and cache directories that it created in
5565 // scanPackageLocked, unless those directories existed before we even tried to
5566 // install.
5567 if(updatedSettings) {
5568 deletePackageLI(
5569 pkgName, true,
5570 PackageManager.DONT_DELETE_DATA,
5571 res.removedInfo);
5572 }
5573 // Since we failed to install the new package we need to restore the old
5574 // package that we deleted.
5575 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005576 File restoreFile = new File(deletedPackage.mPath);
5577 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005578 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005579 return;
5580 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005581 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005582 boolean oldOnSd = isExternal(deletedPackage);
5583 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5584 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5585 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5586 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5587 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5588 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5589 return;
5590 }
5591 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005592 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005593 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005594 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005595 mSettings.writeLP();
5596 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005597 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598 }
5599 }
5600 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005603 PackageParser.Package pkg,
5604 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005605 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 PackageParser.Package newPackage = null;
5607 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005608 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 PackageParser.PARSE_IS_SYSTEM;
5610 String packageName = deletedPackage.packageName;
5611 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5612 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005613 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 return;
5615 }
5616 PackageParser.Package oldPkg;
5617 PackageSetting oldPkgSetting;
5618 synchronized (mPackages) {
5619 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005620 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5622 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005623 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 return;
5625 }
5626 }
5627 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5628 res.removedInfo.removedPackage = packageName;
5629 // Remove existing system package
5630 removePackageLI(oldPkg, true);
5631 synchronized (mPackages) {
5632 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5633 }
5634
5635 // Successfully disabled the old package. Now proceed with re-installation
5636 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5637 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005638 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005640 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5642 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5643 }
5644 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005645 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 updatedSettings = true;
5647 }
5648
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005649 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 // Re installation failed. Restore old information
5651 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005652 if (newPackage != null) {
5653 removePackageLI(newPackage, true);
5654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005656 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005658 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 // Restore the old system information in Settings
5660 synchronized(mPackages) {
5661 if(updatedSettings) {
5662 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005663 mSettings.setInstallerPackageName(packageName,
5664 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 }
5666 mSettings.writeLP();
5667 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005668 } else {
5669 // If this is an update to an existing update, setup
5670 // to remove the existing update.
5671 synchronized (mPackages) {
5672 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5673 if (ps != null && ps.codePathString != null &&
5674 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5675 int installFlags = 0;
5676 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005677 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005678 }
5679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 }
5681 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005682
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005683 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005684 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005685 int retCode;
5686 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5687 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5688 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005689 if (mNoDexOpt) {
5690 /*
5691 * If we're in an engineering build, programs are lazily run
5692 * through dexopt. If the .dex file doesn't exist yet, it
5693 * will be created when the program is run next.
5694 */
5695 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5696 } else {
5697 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5698 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5699 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005700 }
5701 }
5702 return PackageManager.INSTALL_SUCCEEDED;
5703 }
5704
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005705 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005706 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005707 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 synchronized (mPackages) {
5709 //write settings. the installStatus will be incomplete at this stage.
5710 //note that the new package setting would have already been
5711 //added to mPackages. It hasn't been persisted yet.
5712 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5713 mSettings.writeLP();
5714 }
5715
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005716 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005717 != PackageManager.INSTALL_SUCCEEDED) {
5718 // Discontinue if moving dex files failed.
5719 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005721 if((res.returnCode = setPermissionsLI(newPackage))
5722 != PackageManager.INSTALL_SUCCEEDED) {
5723 if (mInstaller != null) {
5724 mInstaller.rmdex(newPackage.mScanPath);
5725 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005726 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005728 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005731 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005732 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 res.name = pkgName;
5734 res.uid = newPackage.applicationInfo.uid;
5735 res.pkg = newPackage;
5736 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005737 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5739 //to update install status
5740 mSettings.writeLP();
5741 }
5742 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005743
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005744 private void installPackageLI(InstallArgs args,
5745 boolean newInstall, PackageInstalledInfo res) {
5746 int pFlags = args.flags;
5747 String installerPackageName = args.installerPackageName;
5748 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005749 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005750 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005751 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005752 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005753 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005754 // Result object to be returned
5755 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5756
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005757 // Retrieve PackageSettings and parse package
5758 int parseFlags = PackageParser.PARSE_CHATTY |
5759 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5760 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5761 parseFlags |= mDefParseFlags;
5762 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5763 pp.setSeparateProcesses(mSeparateProcesses);
5764 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5765 null, mMetrics, parseFlags);
5766 if (pkg == null) {
5767 res.returnCode = pp.getParseError();
5768 return;
5769 }
5770 String pkgName = res.name = pkg.packageName;
5771 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5772 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5773 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5774 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005776 }
5777 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5778 res.returnCode = pp.getParseError();
5779 return;
5780 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005781 // Get rid of all references to package scan path via parser.
5782 pp = null;
5783 String oldCodePath = null;
5784 boolean systemApp = false;
5785 synchronized (mPackages) {
5786 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005787 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5788 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005789 if (pkg.mOriginalPackages != null
5790 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005791 && mPackages.containsKey(oldName)) {
5792 // This package is derived from an original package,
5793 // and this device has been updating from that original
5794 // name. We must continue using the original name, so
5795 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005796 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005797 pkgName = pkg.packageName;
5798 replace = true;
5799 } else if (mPackages.containsKey(pkgName)) {
5800 // This package, under its official name, already exists
5801 // on the device; we should replace it.
5802 replace = true;
5803 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005804 }
5805 PackageSetting ps = mSettings.mPackages.get(pkgName);
5806 if (ps != null) {
5807 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5808 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5809 systemApp = (ps.pkg.applicationInfo.flags &
5810 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005811 }
5812 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005814
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005815 if (systemApp && onSd) {
5816 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005817 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005818 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5819 return;
5820 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005821
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005822 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5823 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5824 return;
5825 }
5826 // Set application objects path explicitly after the rename
5827 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005828 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005829 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005830 replacePackageLI(pkg, parseFlags, scanMode,
5831 installerPackageName, res);
5832 } else {
5833 installNewPackageLI(pkg, parseFlags, scanMode,
5834 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 }
5836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005837
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005838 private int setPermissionsLI(PackageParser.Package newPackage) {
5839 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005840 int retCode = 0;
5841 // TODO Gross hack but fix later. Ideally move this to be a post installation
5842 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005843 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005844 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 try {
5846 extractPublicFiles(newPackage, destResourceFile);
5847 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005848 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 -08005849 " forward-locked app.");
5850 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5851 } finally {
5852 //TODO clean up the extracted public files
5853 }
5854 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005855 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 newPackage.applicationInfo.uid);
5857 } else {
5858 final int filePermissions =
5859 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005860 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 newPackage.applicationInfo.uid);
5862 }
5863 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005864 // The permissions on the resource file was set when it was copied for
5865 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005869 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005870 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005872 // TODO Define new internal error
5873 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 }
5875 return PackageManager.INSTALL_SUCCEEDED;
5876 }
5877
Kenny Root85387d72010-08-26 10:13:11 -07005878 private static boolean isForwardLocked(PackageParser.Package pkg) {
5879 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 }
5881
Kenny Root85387d72010-08-26 10:13:11 -07005882 private static boolean isExternal(PackageParser.Package pkg) {
5883 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5884 }
5885
5886 private static boolean isSystemApp(PackageParser.Package pkg) {
5887 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5888 }
5889
5890 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5891 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005892 }
5893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 private void extractPublicFiles(PackageParser.Package newPackage,
5895 File publicZipFile) throws IOException {
5896 final ZipOutputStream publicZipOutStream =
5897 new ZipOutputStream(new FileOutputStream(publicZipFile));
5898 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5899
5900 // Copy manifest, resources.arsc and res directory to public zip
5901
5902 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5903 while (privateZipEntries.hasMoreElements()) {
5904 final ZipEntry zipEntry = privateZipEntries.nextElement();
5905 final String zipEntryName = zipEntry.getName();
5906 if ("AndroidManifest.xml".equals(zipEntryName)
5907 || "resources.arsc".equals(zipEntryName)
5908 || zipEntryName.startsWith("res/")) {
5909 try {
5910 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5911 } catch (IOException e) {
5912 try {
5913 publicZipOutStream.close();
5914 throw e;
5915 } finally {
5916 publicZipFile.delete();
5917 }
5918 }
5919 }
5920 }
5921
5922 publicZipOutStream.close();
5923 FileUtils.setPermissions(
5924 publicZipFile.getAbsolutePath(),
5925 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5926 -1, -1);
5927 }
5928
5929 private static void copyZipEntry(ZipEntry zipEntry,
5930 ZipFile inZipFile,
5931 ZipOutputStream outZipStream) throws IOException {
5932 byte[] buffer = new byte[4096];
5933 int num;
5934
5935 ZipEntry newEntry;
5936 if (zipEntry.getMethod() == ZipEntry.STORED) {
5937 // Preserve the STORED method of the input entry.
5938 newEntry = new ZipEntry(zipEntry);
5939 } else {
5940 // Create a new entry so that the compressed len is recomputed.
5941 newEntry = new ZipEntry(zipEntry.getName());
5942 }
5943 outZipStream.putNextEntry(newEntry);
5944
5945 InputStream data = inZipFile.getInputStream(zipEntry);
5946 while ((num = data.read(buffer)) > 0) {
5947 outZipStream.write(buffer, 0, num);
5948 }
5949 outZipStream.flush();
5950 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 private void deleteTempPackageFiles() {
5953 FilenameFilter filter = new FilenameFilter() {
5954 public boolean accept(File dir, String name) {
5955 return name.startsWith("vmdl") && name.endsWith(".tmp");
5956 }
5957 };
5958 String tmpFilesList[] = mAppInstallDir.list(filter);
5959 if(tmpFilesList == null) {
5960 return;
5961 }
5962 for(int i = 0; i < tmpFilesList.length; i++) {
5963 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5964 tmpFile.delete();
5965 }
5966 }
5967
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005968 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 File tmpPackageFile;
5970 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005971 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005973 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 return null;
5975 }
5976 try {
5977 FileUtils.setPermissions(
5978 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5979 -1, -1);
5980 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005981 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 return null;
5983 }
5984 return tmpPackageFile;
5985 }
5986
5987 public void deletePackage(final String packageName,
5988 final IPackageDeleteObserver observer,
5989 final int flags) {
5990 mContext.enforceCallingOrSelfPermission(
5991 android.Manifest.permission.DELETE_PACKAGES, null);
5992 // Queue up an async operation since the package deletion may take a little while.
5993 mHandler.post(new Runnable() {
5994 public void run() {
5995 mHandler.removeCallbacks(this);
5996 final boolean succeded = deletePackageX(packageName, true, true, flags);
5997 if (observer != null) {
5998 try {
5999 observer.packageDeleted(succeded);
6000 } catch (RemoteException e) {
6001 Log.i(TAG, "Observer no longer exists.");
6002 } //end catch
6003 } //end if
6004 } //end run
6005 });
6006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 /**
6009 * This method is an internal method that could be get invoked either
6010 * to delete an installed package or to clean up a failed installation.
6011 * After deleting an installed package, a broadcast is sent to notify any
6012 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006013 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 * installation wouldn't have sent the initial broadcast either
6015 * The key steps in deleting a package are
6016 * deleting the package information in internal structures like mPackages,
6017 * deleting the packages base directories through installd
6018 * updating mSettings to reflect current status
6019 * persisting settings for later use
6020 * sending a broadcast if necessary
6021 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6023 boolean deleteCodeAndResources, int flags) {
6024 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006025 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006027 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6028 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6029 try {
6030 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006031 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006032 return false;
6033 }
6034 } catch (RemoteException e) {
6035 }
6036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006038 res = deletePackageLI(packageName, deleteCodeAndResources,
6039 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006043 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006044 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006045
6046 // If the removed package was a system update, the old system packaged
6047 // was re-enabled; we need to broadcast this information
6048 if (systemUpdate) {
6049 Bundle extras = new Bundle(1);
6050 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6051 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6052
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006053 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6054 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006057 // Force a gc here.
6058 Runtime.getRuntime().gc();
6059 // Delete the resources here after sending the broadcast to let
6060 // other processes clean up before deleting resources.
6061 if (info.args != null) {
6062 synchronized (mInstallLock) {
6063 info.args.doPostDeleteLI(deleteCodeAndResources);
6064 }
6065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 return res;
6067 }
6068
6069 static class PackageRemovedInfo {
6070 String removedPackage;
6071 int uid = -1;
6072 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006073 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006074 // Clean up resources deleted packages.
6075 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006076
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006077 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 Bundle extras = new Bundle(1);
6079 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6080 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6081 if (replacing) {
6082 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6083 }
6084 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006085 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 }
6087 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006088 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 }
6090 }
6091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 /*
6094 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6095 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006096 * 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 -08006097 * delete a partially installed application.
6098 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006099 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 int flags) {
6101 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006102 if (outInfo != null) {
6103 outInfo.removedPackage = packageName;
6104 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006105 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 // Retrieve object to delete permissions for shared user later on
6107 PackageSetting deletedPs;
6108 synchronized (mPackages) {
6109 deletedPs = mSettings.mPackages.get(packageName);
6110 }
6111 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006112 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006114 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006116 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 + packageName + ", retcode=" + retCode);
6118 // we don't consider this to be a failure of the core package deletion
6119 }
6120 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006121 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 PackageParser.Package pkg = mPackages.get(packageName);
6123 File dataDir = new File(pkg.applicationInfo.dataDir);
6124 dataDir.delete();
6125 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006126 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 }
6128 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006129 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006130 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6131 if (outInfo != null) {
6132 outInfo.removedUid = mSettings.removePackageLP(packageName);
6133 }
6134 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006135 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006136 if (deletedPs.sharedUser != null) {
6137 // remove permissions associated with package
6138 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6139 }
6140 }
6141 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006142 // remove from preferred activities.
6143 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6144 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6145 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6146 removed.add(pa);
6147 }
6148 }
6149 for (PreferredActivity pa : removed) {
6150 mSettings.mPreferredActivities.removeFilter(pa);
6151 }
6152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006154 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 }
6156 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 /*
6159 * Tries to delete system package.
6160 */
6161 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006162 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 ApplicationInfo applicationInfo = p.applicationInfo;
6164 //applicable for non-partially installed applications only
6165 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006166 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 return false;
6168 }
6169 PackageSetting ps = null;
6170 // Confirm if the system package has been updated
6171 // An updated system app can be deleted. This will also have to restore
6172 // the system pkg from system partition
6173 synchronized (mPackages) {
6174 ps = mSettings.getDisabledSystemPkg(p.packageName);
6175 }
6176 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006177 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 return false;
6179 } else {
6180 Log.i(TAG, "Deleting system pkg from data partition");
6181 }
6182 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006183 outInfo.isRemovedPackageSystemUpdate = true;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006184 boolean deleteCodeAndResources = false;
6185 if (ps.versionCode < p.mVersionCode) {
6186 // Delete code and resources for downgrades
6187 deleteCodeAndResources = true;
6188 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6189 flags &= ~PackageManager.DONT_DELETE_DATA;
6190 }
6191 } else {
6192 // Preserve data by setting flag
6193 if ((flags & PackageManager.DONT_DELETE_DATA) == 0) {
6194 flags |= PackageManager.DONT_DELETE_DATA;
6195 }
6196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6198 if (!ret) {
6199 return false;
6200 }
6201 synchronized (mPackages) {
6202 // Reinstate the old system package
6203 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07006204 // Remove any native libraries. XXX needed?
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006205 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 }
6207 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006208 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006210 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006212 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006213 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006214 return false;
6215 }
6216 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006217 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 mSettings.writeLP();
6219 }
6220 return true;
6221 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006222
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006223 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6224 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6225 ApplicationInfo applicationInfo = p.applicationInfo;
6226 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006227 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006228 return false;
6229 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006230 if (outInfo != null) {
6231 outInfo.uid = applicationInfo.uid;
6232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006233
6234 // Delete package data from internal structures and also remove data if flag is set
6235 removePackageDataLI(p, outInfo, flags);
6236
6237 // Delete application code and resources
6238 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006239 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006240 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6241 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6242 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6243 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006244 }
6245 return true;
6246 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 /*
6249 * This method handles package deletion in general
6250 */
6251 private boolean deletePackageLI(String packageName,
6252 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6253 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006254 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006255 return false;
6256 }
6257 PackageParser.Package p;
6258 boolean dataOnly = false;
6259 synchronized (mPackages) {
6260 p = mPackages.get(packageName);
6261 if (p == null) {
6262 //this retrieves partially installed apps
6263 dataOnly = true;
6264 PackageSetting ps = mSettings.mPackages.get(packageName);
6265 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006266 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006267 return false;
6268 }
6269 p = ps.pkg;
6270 }
6271 }
6272 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006273 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 return false;
6275 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006277 if (dataOnly) {
6278 // Delete application data first
6279 removePackageDataLI(p, outInfo, flags);
6280 return true;
6281 }
6282 // At this point the package should have ApplicationInfo associated with it
6283 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006284 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006285 return false;
6286 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006287 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006288 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006289 Log.i(TAG, "Removing system package:"+p.packageName);
6290 // When an updated system application is deleted we delete the existing resources as well and
6291 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006292 ret = deleteSystemPackageLI(p, flags, outInfo);
6293 } else {
6294 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006295 // Kill application pre-emptively especially for apps on sd.
6296 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006297 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006298 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006299 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006300 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006302 public void clearApplicationUserData(final String packageName,
6303 final IPackageDataObserver observer) {
6304 mContext.enforceCallingOrSelfPermission(
6305 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6306 // Queue up an async operation since the package deletion may take a little while.
6307 mHandler.post(new Runnable() {
6308 public void run() {
6309 mHandler.removeCallbacks(this);
6310 final boolean succeeded;
6311 synchronized (mInstallLock) {
6312 succeeded = clearApplicationUserDataLI(packageName);
6313 }
6314 if (succeeded) {
6315 // invoke DeviceStorageMonitor's update method to clear any notifications
6316 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6317 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6318 if (dsm != null) {
6319 dsm.updateMemory();
6320 }
6321 }
6322 if(observer != null) {
6323 try {
6324 observer.onRemoveCompleted(packageName, succeeded);
6325 } catch (RemoteException e) {
6326 Log.i(TAG, "Observer no longer exists.");
6327 }
6328 } //end if observer
6329 } //end run
6330 });
6331 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 private boolean clearApplicationUserDataLI(String packageName) {
6334 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006335 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006336 return false;
6337 }
6338 PackageParser.Package p;
6339 boolean dataOnly = false;
6340 synchronized (mPackages) {
6341 p = mPackages.get(packageName);
6342 if(p == null) {
6343 dataOnly = true;
6344 PackageSetting ps = mSettings.mPackages.get(packageName);
6345 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006346 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006347 return false;
6348 }
6349 p = ps.pkg;
6350 }
6351 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006352 boolean useEncryptedFSDir = false;
6353
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006354 if(!dataOnly) {
6355 //need to check this only for fully installed applications
6356 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006357 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006358 return false;
6359 }
6360 final ApplicationInfo applicationInfo = p.applicationInfo;
6361 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006362 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 return false;
6364 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006365 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 }
6367 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006368 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006369 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006370 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006371 + packageName);
6372 return false;
6373 }
6374 }
6375 return true;
6376 }
6377
6378 public void deleteApplicationCacheFiles(final String packageName,
6379 final IPackageDataObserver observer) {
6380 mContext.enforceCallingOrSelfPermission(
6381 android.Manifest.permission.DELETE_CACHE_FILES, null);
6382 // Queue up an async operation since the package deletion may take a little while.
6383 mHandler.post(new Runnable() {
6384 public void run() {
6385 mHandler.removeCallbacks(this);
6386 final boolean succeded;
6387 synchronized (mInstallLock) {
6388 succeded = deleteApplicationCacheFilesLI(packageName);
6389 }
6390 if(observer != null) {
6391 try {
6392 observer.onRemoveCompleted(packageName, succeded);
6393 } catch (RemoteException e) {
6394 Log.i(TAG, "Observer no longer exists.");
6395 }
6396 } //end if observer
6397 } //end run
6398 });
6399 }
6400
6401 private boolean deleteApplicationCacheFilesLI(String packageName) {
6402 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006403 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006404 return false;
6405 }
6406 PackageParser.Package p;
6407 synchronized (mPackages) {
6408 p = mPackages.get(packageName);
6409 }
6410 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006411 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006412 return false;
6413 }
6414 final ApplicationInfo applicationInfo = p.applicationInfo;
6415 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006416 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 return false;
6418 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006419 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006420 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006421 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006422 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006423 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006424 + packageName);
6425 return false;
6426 }
6427 }
6428 return true;
6429 }
6430
6431 public void getPackageSizeInfo(final String packageName,
6432 final IPackageStatsObserver observer) {
6433 mContext.enforceCallingOrSelfPermission(
6434 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6435 // Queue up an async operation since the package deletion may take a little while.
6436 mHandler.post(new Runnable() {
6437 public void run() {
6438 mHandler.removeCallbacks(this);
6439 PackageStats lStats = new PackageStats(packageName);
6440 final boolean succeded;
6441 synchronized (mInstallLock) {
6442 succeded = getPackageSizeInfoLI(packageName, lStats);
6443 }
6444 if(observer != null) {
6445 try {
6446 observer.onGetStatsCompleted(lStats, succeded);
6447 } catch (RemoteException e) {
6448 Log.i(TAG, "Observer no longer exists.");
6449 }
6450 } //end if observer
6451 } //end run
6452 });
6453 }
6454
6455 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6456 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006457 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 return false;
6459 }
6460 PackageParser.Package p;
6461 boolean dataOnly = false;
6462 synchronized (mPackages) {
6463 p = mPackages.get(packageName);
6464 if(p == null) {
6465 dataOnly = true;
6466 PackageSetting ps = mSettings.mPackages.get(packageName);
6467 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006468 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006469 return false;
6470 }
6471 p = ps.pkg;
6472 }
6473 }
6474 String publicSrcDir = null;
6475 if(!dataOnly) {
6476 final ApplicationInfo applicationInfo = p.applicationInfo;
6477 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006478 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006479 return false;
6480 }
6481 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6482 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006483 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 if (mInstaller != null) {
6485 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006486 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006487 if (res < 0) {
6488 return false;
6489 } else {
6490 return true;
6491 }
6492 }
6493 return true;
6494 }
6495
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006496
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006497 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006498 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006499 }
6500
6501 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006502 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006503 }
6504
6505 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006506 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006507 }
6508
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006509 int getUidTargetSdkVersionLockedLP(int uid) {
6510 Object obj = mSettings.getUserIdLP(uid);
6511 if (obj instanceof SharedUserSetting) {
6512 SharedUserSetting sus = (SharedUserSetting)obj;
6513 final int N = sus.packages.size();
6514 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6515 Iterator<PackageSetting> it = sus.packages.iterator();
6516 int i=0;
6517 while (it.hasNext()) {
6518 PackageSetting ps = it.next();
6519 if (ps.pkg != null) {
6520 int v = ps.pkg.applicationInfo.targetSdkVersion;
6521 if (v < vers) vers = v;
6522 }
6523 }
6524 return vers;
6525 } else if (obj instanceof PackageSetting) {
6526 PackageSetting ps = (PackageSetting)obj;
6527 if (ps.pkg != null) {
6528 return ps.pkg.applicationInfo.targetSdkVersion;
6529 }
6530 }
6531 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6532 }
6533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006534 public void addPreferredActivity(IntentFilter filter, int match,
6535 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006536 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006537 if (mContext.checkCallingOrSelfPermission(
6538 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6539 != PackageManager.PERMISSION_GRANTED) {
6540 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6541 < Build.VERSION_CODES.FROYO) {
6542 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6543 + Binder.getCallingUid());
6544 return;
6545 }
6546 mContext.enforceCallingOrSelfPermission(
6547 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6548 }
6549
6550 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006551 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6552 mSettings.mPreferredActivities.addFilter(
6553 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006554 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006555 }
6556 }
6557
Satish Sampath8dbe6122009-06-02 23:35:54 +01006558 public void replacePreferredActivity(IntentFilter filter, int match,
6559 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006560 if (filter.countActions() != 1) {
6561 throw new IllegalArgumentException(
6562 "replacePreferredActivity expects filter to have only 1 action.");
6563 }
6564 if (filter.countCategories() != 1) {
6565 throw new IllegalArgumentException(
6566 "replacePreferredActivity expects filter to have only 1 category.");
6567 }
6568 if (filter.countDataAuthorities() != 0
6569 || filter.countDataPaths() != 0
6570 || filter.countDataSchemes() != 0
6571 || filter.countDataTypes() != 0) {
6572 throw new IllegalArgumentException(
6573 "replacePreferredActivity expects filter to have no data authorities, " +
6574 "paths, schemes or types.");
6575 }
6576 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006577 if (mContext.checkCallingOrSelfPermission(
6578 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6579 != PackageManager.PERMISSION_GRANTED) {
6580 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6581 < Build.VERSION_CODES.FROYO) {
6582 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6583 + Binder.getCallingUid());
6584 return;
6585 }
6586 mContext.enforceCallingOrSelfPermission(
6587 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6588 }
6589
Satish Sampath8dbe6122009-06-02 23:35:54 +01006590 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6591 String action = filter.getAction(0);
6592 String category = filter.getCategory(0);
6593 while (it.hasNext()) {
6594 PreferredActivity pa = it.next();
6595 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6596 it.remove();
6597 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6598 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6599 }
6600 }
6601 addPreferredActivity(filter, match, set, activity);
6602 }
6603 }
6604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006605 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006607 int uid = Binder.getCallingUid();
6608 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006609 if (pkg == null || pkg.applicationInfo.uid != uid) {
6610 if (mContext.checkCallingOrSelfPermission(
6611 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6612 != PackageManager.PERMISSION_GRANTED) {
6613 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6614 < Build.VERSION_CODES.FROYO) {
6615 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6616 + Binder.getCallingUid());
6617 return;
6618 }
6619 mContext.enforceCallingOrSelfPermission(
6620 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6621 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006622 }
6623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006624 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006625 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006626 }
6627 }
6628 }
6629
6630 boolean clearPackagePreferredActivitiesLP(String packageName) {
6631 boolean changed = false;
6632 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6633 while (it.hasNext()) {
6634 PreferredActivity pa = it.next();
6635 if (pa.mActivity.getPackageName().equals(packageName)) {
6636 it.remove();
6637 changed = true;
6638 }
6639 }
6640 return changed;
6641 }
6642
6643 public int getPreferredActivities(List<IntentFilter> outFilters,
6644 List<ComponentName> outActivities, String packageName) {
6645
6646 int num = 0;
6647 synchronized (mPackages) {
6648 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6649 while (it.hasNext()) {
6650 PreferredActivity pa = it.next();
6651 if (packageName == null
6652 || pa.mActivity.getPackageName().equals(packageName)) {
6653 if (outFilters != null) {
6654 outFilters.add(new IntentFilter(pa));
6655 }
6656 if (outActivities != null) {
6657 outActivities.add(pa.mActivity);
6658 }
6659 }
6660 }
6661 }
6662
6663 return num;
6664 }
6665
6666 public void setApplicationEnabledSetting(String appPackageName,
6667 int newState, int flags) {
6668 setEnabledSetting(appPackageName, null, newState, flags);
6669 }
6670
6671 public void setComponentEnabledSetting(ComponentName componentName,
6672 int newState, int flags) {
6673 setEnabledSetting(componentName.getPackageName(),
6674 componentName.getClassName(), newState, flags);
6675 }
6676
6677 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006678 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6680 || newState == COMPONENT_ENABLED_STATE_ENABLED
6681 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6682 throw new IllegalArgumentException("Invalid new component state: "
6683 + newState);
6684 }
6685 PackageSetting pkgSetting;
6686 final int uid = Binder.getCallingUid();
6687 final int permission = mContext.checkCallingPermission(
6688 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6689 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006690 boolean sendNow = false;
6691 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006692 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006693 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006694 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006695 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006696 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006697 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006698 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006699 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006700 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 }
6702 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006703 "Unknown component: " + packageName
6704 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006705 }
6706 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6707 throw new SecurityException(
6708 "Permission Denial: attempt to change component state from pid="
6709 + Binder.getCallingPid()
6710 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6711 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006712 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006713 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006714 if (pkgSetting.enabled == newState) {
6715 // Nothing to do
6716 return;
6717 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006718 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006719 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006720 } else {
6721 // We're dealing with a component level state change
6722 switch (newState) {
6723 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006724 if (!pkgSetting.enableComponentLP(className)) {
6725 return;
6726 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006727 break;
6728 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006729 if (!pkgSetting.disableComponentLP(className)) {
6730 return;
6731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006732 break;
6733 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006734 if (!pkgSetting.restoreComponentLP(className)) {
6735 return;
6736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006737 break;
6738 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006739 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006740 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 }
6742 }
6743 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006744 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006745 components = mPendingBroadcasts.get(packageName);
6746 boolean newPackage = components == null;
6747 if (newPackage) {
6748 components = new ArrayList<String>();
6749 }
6750 if (!components.contains(componentName)) {
6751 components.add(componentName);
6752 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006753 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6754 sendNow = true;
6755 // Purge entry from pending broadcast list if another one exists already
6756 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006757 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006758 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006759 if (newPackage) {
6760 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006761 }
6762 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6763 // Schedule a message
6764 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6765 }
6766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006767 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006769 long callingId = Binder.clearCallingIdentity();
6770 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006771 if (sendNow) {
6772 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006773 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006774 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006775 } finally {
6776 Binder.restoreCallingIdentity(callingId);
6777 }
6778 }
6779
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006780 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006781 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6782 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6783 + " components=" + componentNames);
6784 Bundle extras = new Bundle(4);
6785 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6786 String nameList[] = new String[componentNames.size()];
6787 componentNames.toArray(nameList);
6788 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006789 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6790 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006791 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006792 }
6793
Jacek Surazski65e13172009-04-28 15:26:38 +02006794 public String getInstallerPackageName(String packageName) {
6795 synchronized (mPackages) {
6796 PackageSetting pkg = mSettings.mPackages.get(packageName);
6797 if (pkg == null) {
6798 throw new IllegalArgumentException("Unknown package: " + packageName);
6799 }
6800 return pkg.installerPackageName;
6801 }
6802 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006804 public int getApplicationEnabledSetting(String appPackageName) {
6805 synchronized (mPackages) {
6806 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6807 if (pkg == null) {
6808 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6809 }
6810 return pkg.enabled;
6811 }
6812 }
6813
6814 public int getComponentEnabledSetting(ComponentName componentName) {
6815 synchronized (mPackages) {
6816 final String packageNameStr = componentName.getPackageName();
6817 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6818 if (pkg == null) {
6819 throw new IllegalArgumentException("Unknown component: " + componentName);
6820 }
6821 final String classNameStr = componentName.getClassName();
6822 return pkg.currentEnabledStateLP(classNameStr);
6823 }
6824 }
6825
6826 public void enterSafeMode() {
6827 if (!mSystemReady) {
6828 mSafeMode = true;
6829 }
6830 }
6831
6832 public void systemReady() {
6833 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006834
6835 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006836 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006837 mContext.getContentResolver(),
6838 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006839 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006840 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006841 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006842 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006843 }
6844
6845 public boolean isSafeMode() {
6846 return mSafeMode;
6847 }
6848
6849 public boolean hasSystemUidErrors() {
6850 return mHasSystemUidErrors;
6851 }
6852
6853 static String arrayToString(int[] array) {
6854 StringBuffer buf = new StringBuffer(128);
6855 buf.append('[');
6856 if (array != null) {
6857 for (int i=0; i<array.length; i++) {
6858 if (i > 0) buf.append(", ");
6859 buf.append(array[i]);
6860 }
6861 }
6862 buf.append(']');
6863 return buf.toString();
6864 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006866 @Override
6867 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6868 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6869 != PackageManager.PERMISSION_GRANTED) {
6870 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6871 + Binder.getCallingPid()
6872 + ", uid=" + Binder.getCallingUid()
6873 + " without permission "
6874 + android.Manifest.permission.DUMP);
6875 return;
6876 }
6877
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006878 String packageName = null;
6879
6880 int opti = 0;
6881 while (opti < args.length) {
6882 String opt = args[opti];
6883 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6884 break;
6885 }
6886 opti++;
6887 if ("-a".equals(opt)) {
6888 // Right now we only know how to print all.
6889 } else if ("-h".equals(opt)) {
6890 pw.println("Package manager dump options:");
6891 pw.println(" [-h] [cmd] ...");
6892 pw.println(" cmd may be one of:");
6893 pw.println(" [package.name]: info about given package");
6894 return;
6895 } else {
6896 pw.println("Unknown argument: " + opt + "; use -h for help");
6897 }
6898 }
6899
6900 // Is the caller requesting to dump a particular piece of data?
6901 if (opti < args.length) {
6902 String cmd = args[opti];
6903 opti++;
6904 // Is this a package name?
6905 if ("android".equals(cmd) || cmd.contains(".")) {
6906 packageName = cmd;
6907 }
6908 }
6909
6910 boolean printedTitle = false;
6911
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006912 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006913 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6914 printedTitle = true;
6915 }
6916 if (mReceivers.dump(pw, printedTitle
6917 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6918 " ", packageName)) {
6919 printedTitle = true;
6920 }
6921 if (mServices.dump(pw, printedTitle
6922 ? "\nService Resolver Table:" : "Service Resolver Table:",
6923 " ", packageName)) {
6924 printedTitle = true;
6925 }
6926 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6927 ? "\nPreferred Activities:" : "Preferred Activities:",
6928 " ", packageName)) {
6929 printedTitle = true;
6930 }
6931 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006932 {
6933 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006934 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6935 continue;
6936 }
6937 if (!printedSomething) {
6938 if (printedTitle) pw.println(" ");
6939 pw.println("Permissions:");
6940 printedSomething = true;
6941 printedTitle = true;
6942 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006943 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6944 pw.print(Integer.toHexString(System.identityHashCode(p)));
6945 pw.println("):");
6946 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6947 pw.print(" uid="); pw.print(p.uid);
6948 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006949 pw.print(" type="); pw.print(p.type);
6950 pw.print(" prot="); pw.println(p.protectionLevel);
6951 if (p.packageSetting != null) {
6952 pw.print(" packageSetting="); pw.println(p.packageSetting);
6953 }
6954 if (p.perm != null) {
6955 pw.print(" perm="); pw.println(p.perm);
6956 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006957 }
6958 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006959 printedSomething = false;
6960 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006961 {
6962 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006963 if (packageName != null && !packageName.equals(ps.realName)
6964 && !packageName.equals(ps.name)) {
6965 continue;
6966 }
6967 if (!printedSomething) {
6968 if (printedTitle) pw.println(" ");
6969 pw.println("Packages:");
6970 printedSomething = true;
6971 printedTitle = true;
6972 }
6973 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006974 pw.print(" Package [");
6975 pw.print(ps.realName != null ? ps.realName : ps.name);
6976 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006977 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6978 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006979 if (ps.realName != null) {
6980 pw.print(" compat name="); pw.println(ps.name);
6981 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006982 pw.print(" userId="); pw.print(ps.userId);
6983 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6984 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6985 pw.print(" pkg="); pw.println(ps.pkg);
6986 pw.print(" codePath="); pw.println(ps.codePathString);
6987 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07006988 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07006989 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006990 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006991 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006992 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07006993 if (ps.pkg.mOperationPending) {
6994 pw.println(" mOperationPending=true");
6995 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006996 pw.print(" supportsScreens=[");
6997 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006998 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07006999 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7000 if (!first) pw.print(", ");
7001 first = false;
7002 pw.print("small");
7003 }
7004 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007005 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007006 if (!first) pw.print(", ");
7007 first = false;
7008 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007009 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007010 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007011 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007012 if (!first) pw.print(", ");
7013 first = false;
7014 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007016 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007017 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007018 if (!first) pw.print(", ");
7019 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007020 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007021 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007022 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007023 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007024 if (!first) pw.print(", ");
7025 first = false;
7026 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007027 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007028 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007029 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7030 if (!first) pw.print(", ");
7031 first = false;
7032 pw.print("anyDensity");
7033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007035 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007036 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7037 pw.print(" signatures="); pw.println(ps.signatures);
7038 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007039 pw.print(" haveGids="); pw.println(ps.haveGids);
7040 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007041 pw.print(" installStatus="); pw.print(ps.installStatus);
7042 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007043 if (ps.disabledComponents.size() > 0) {
7044 pw.println(" disabledComponents:");
7045 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007046 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007047 }
7048 }
7049 if (ps.enabledComponents.size() > 0) {
7050 pw.println(" enabledComponents:");
7051 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007052 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007053 }
7054 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007055 if (ps.grantedPermissions.size() > 0) {
7056 pw.println(" grantedPermissions:");
7057 for (String s : ps.grantedPermissions) {
7058 pw.print(" "); pw.println(s);
7059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 }
7062 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007063 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007064 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007065 for (HashMap.Entry<String, String> e
7066 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007067 if (packageName != null && !packageName.equals(e.getKey())
7068 && !packageName.equals(e.getValue())) {
7069 continue;
7070 }
7071 if (!printedSomething) {
7072 if (printedTitle) pw.println(" ");
7073 pw.println("Renamed packages:");
7074 printedSomething = true;
7075 printedTitle = true;
7076 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007077 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7078 pw.println(e.getValue());
7079 }
7080 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007081 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007082 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007083 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007084 if (packageName != null && !packageName.equals(ps.realName)
7085 && !packageName.equals(ps.name)) {
7086 continue;
7087 }
7088 if (!printedSomething) {
7089 if (printedTitle) pw.println(" ");
7090 pw.println("Hidden system packages:");
7091 printedSomething = true;
7092 printedTitle = true;
7093 }
7094 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007095 pw.print(ps.realName != null ? ps.realName : ps.name);
7096 pw.print("] (");
7097 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7098 pw.println("):");
7099 if (ps.realName != null) {
7100 pw.print(" compat name="); pw.println(ps.name);
7101 }
7102 pw.print(" userId="); pw.println(ps.userId);
7103 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7104 pw.print(" codePath="); pw.println(ps.codePathString);
7105 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7106 }
7107 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007108 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007109 {
7110 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007111 if (packageName != null && su != packageSharedUser) {
7112 continue;
7113 }
7114 if (!printedSomething) {
7115 if (printedTitle) pw.println(" ");
7116 pw.println("Shared users:");
7117 printedSomething = true;
7118 printedTitle = true;
7119 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007120 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7121 pw.print(Integer.toHexString(System.identityHashCode(su)));
7122 pw.println("):");
7123 pw.print(" userId="); pw.print(su.userId);
7124 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007125 pw.println(" grantedPermissions:");
7126 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007127 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 }
7130 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007131
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007132 if (packageName == null) {
7133 if (printedTitle) pw.println(" ");
7134 printedTitle = true;
7135 pw.println("Settings parse messages:");
7136 pw.println(mSettings.mReadMessages.toString());
7137
7138 pw.println(" ");
7139 pw.println("Package warning messages:");
7140 File fname = getSettingsProblemFile();
7141 FileInputStream in;
7142 try {
7143 in = new FileInputStream(fname);
7144 int avail = in.available();
7145 byte[] data = new byte[avail];
7146 in.read(data);
7147 pw.println(new String(data));
7148 } catch (FileNotFoundException e) {
7149 } catch (IOException e) {
7150 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007152 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007153
7154 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007155 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007156 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007157 if (packageName != null && !packageName.equals(p.info.packageName)) {
7158 continue;
7159 }
7160 if (!printedSomething) {
7161 if (printedTitle) pw.println(" ");
7162 pw.println("Registered ContentProviders:");
7163 printedSomething = true;
7164 printedTitle = true;
7165 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007166 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007167 pw.println(p.toString());
7168 }
7169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007170 }
7171
7172 static final class BasePermission {
7173 final static int TYPE_NORMAL = 0;
7174 final static int TYPE_BUILTIN = 1;
7175 final static int TYPE_DYNAMIC = 2;
7176
7177 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007178 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007179 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007180 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007181 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007182 PackageParser.Permission perm;
7183 PermissionInfo pendingInfo;
7184 int uid;
7185 int[] gids;
7186
7187 BasePermission(String _name, String _sourcePackage, int _type) {
7188 name = _name;
7189 sourcePackage = _sourcePackage;
7190 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007191 // Default to most conservative protection level.
7192 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7193 }
7194
7195 public String toString() {
7196 return "BasePermission{"
7197 + Integer.toHexString(System.identityHashCode(this))
7198 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007199 }
7200 }
7201
7202 static class PackageSignatures {
7203 private Signature[] mSignatures;
7204
7205 PackageSignatures(Signature[] sigs) {
7206 assignSignatures(sigs);
7207 }
7208
7209 PackageSignatures() {
7210 }
7211
7212 void writeXml(XmlSerializer serializer, String tagName,
7213 ArrayList<Signature> pastSignatures) throws IOException {
7214 if (mSignatures == null) {
7215 return;
7216 }
7217 serializer.startTag(null, tagName);
7218 serializer.attribute(null, "count",
7219 Integer.toString(mSignatures.length));
7220 for (int i=0; i<mSignatures.length; i++) {
7221 serializer.startTag(null, "cert");
7222 final Signature sig = mSignatures[i];
7223 final int sigHash = sig.hashCode();
7224 final int numPast = pastSignatures.size();
7225 int j;
7226 for (j=0; j<numPast; j++) {
7227 Signature pastSig = pastSignatures.get(j);
7228 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7229 serializer.attribute(null, "index", Integer.toString(j));
7230 break;
7231 }
7232 }
7233 if (j >= numPast) {
7234 pastSignatures.add(sig);
7235 serializer.attribute(null, "index", Integer.toString(numPast));
7236 serializer.attribute(null, "key", sig.toCharsString());
7237 }
7238 serializer.endTag(null, "cert");
7239 }
7240 serializer.endTag(null, tagName);
7241 }
7242
7243 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7244 throws IOException, XmlPullParserException {
7245 String countStr = parser.getAttributeValue(null, "count");
7246 if (countStr == null) {
7247 reportSettingsProblem(Log.WARN,
7248 "Error in package manager settings: <signatures> has"
7249 + " no count at " + parser.getPositionDescription());
7250 XmlUtils.skipCurrentTag(parser);
7251 }
7252 final int count = Integer.parseInt(countStr);
7253 mSignatures = new Signature[count];
7254 int pos = 0;
7255
7256 int outerDepth = parser.getDepth();
7257 int type;
7258 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7259 && (type != XmlPullParser.END_TAG
7260 || parser.getDepth() > outerDepth)) {
7261 if (type == XmlPullParser.END_TAG
7262 || type == XmlPullParser.TEXT) {
7263 continue;
7264 }
7265
7266 String tagName = parser.getName();
7267 if (tagName.equals("cert")) {
7268 if (pos < count) {
7269 String index = parser.getAttributeValue(null, "index");
7270 if (index != null) {
7271 try {
7272 int idx = Integer.parseInt(index);
7273 String key = parser.getAttributeValue(null, "key");
7274 if (key == null) {
7275 if (idx >= 0 && idx < pastSignatures.size()) {
7276 Signature sig = pastSignatures.get(idx);
7277 if (sig != null) {
7278 mSignatures[pos] = pastSignatures.get(idx);
7279 pos++;
7280 } else {
7281 reportSettingsProblem(Log.WARN,
7282 "Error in package manager settings: <cert> "
7283 + "index " + index + " is not defined at "
7284 + parser.getPositionDescription());
7285 }
7286 } else {
7287 reportSettingsProblem(Log.WARN,
7288 "Error in package manager settings: <cert> "
7289 + "index " + index + " is out of bounds at "
7290 + parser.getPositionDescription());
7291 }
7292 } else {
7293 while (pastSignatures.size() <= idx) {
7294 pastSignatures.add(null);
7295 }
7296 Signature sig = new Signature(key);
7297 pastSignatures.set(idx, sig);
7298 mSignatures[pos] = sig;
7299 pos++;
7300 }
7301 } catch (NumberFormatException e) {
7302 reportSettingsProblem(Log.WARN,
7303 "Error in package manager settings: <cert> "
7304 + "index " + index + " is not a number at "
7305 + parser.getPositionDescription());
7306 }
7307 } else {
7308 reportSettingsProblem(Log.WARN,
7309 "Error in package manager settings: <cert> has"
7310 + " no index at " + parser.getPositionDescription());
7311 }
7312 } else {
7313 reportSettingsProblem(Log.WARN,
7314 "Error in package manager settings: too "
7315 + "many <cert> tags, expected " + count
7316 + " at " + parser.getPositionDescription());
7317 }
7318 } else {
7319 reportSettingsProblem(Log.WARN,
7320 "Unknown element under <cert>: "
7321 + parser.getName());
7322 }
7323 XmlUtils.skipCurrentTag(parser);
7324 }
7325
7326 if (pos < count) {
7327 // Should never happen -- there is an error in the written
7328 // settings -- but if it does we don't want to generate
7329 // a bad array.
7330 Signature[] newSigs = new Signature[pos];
7331 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7332 mSignatures = newSigs;
7333 }
7334 }
7335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007336 private void assignSignatures(Signature[] sigs) {
7337 if (sigs == null) {
7338 mSignatures = null;
7339 return;
7340 }
7341 mSignatures = new Signature[sigs.length];
7342 for (int i=0; i<sigs.length; i++) {
7343 mSignatures[i] = sigs[i];
7344 }
7345 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007347 @Override
7348 public String toString() {
7349 StringBuffer buf = new StringBuffer(128);
7350 buf.append("PackageSignatures{");
7351 buf.append(Integer.toHexString(System.identityHashCode(this)));
7352 buf.append(" [");
7353 if (mSignatures != null) {
7354 for (int i=0; i<mSignatures.length; i++) {
7355 if (i > 0) buf.append(", ");
7356 buf.append(Integer.toHexString(
7357 System.identityHashCode(mSignatures[i])));
7358 }
7359 }
7360 buf.append("]}");
7361 return buf.toString();
7362 }
7363 }
7364
7365 static class PreferredActivity extends IntentFilter {
7366 final int mMatch;
7367 final String[] mSetPackages;
7368 final String[] mSetClasses;
7369 final String[] mSetComponents;
7370 final ComponentName mActivity;
7371 final String mShortActivity;
7372 String mParseError;
7373
7374 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7375 ComponentName activity) {
7376 super(filter);
7377 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7378 mActivity = activity;
7379 mShortActivity = activity.flattenToShortString();
7380 mParseError = null;
7381 if (set != null) {
7382 final int N = set.length;
7383 String[] myPackages = new String[N];
7384 String[] myClasses = new String[N];
7385 String[] myComponents = new String[N];
7386 for (int i=0; i<N; i++) {
7387 ComponentName cn = set[i];
7388 if (cn == null) {
7389 mSetPackages = null;
7390 mSetClasses = null;
7391 mSetComponents = null;
7392 return;
7393 }
7394 myPackages[i] = cn.getPackageName().intern();
7395 myClasses[i] = cn.getClassName().intern();
7396 myComponents[i] = cn.flattenToShortString().intern();
7397 }
7398 mSetPackages = myPackages;
7399 mSetClasses = myClasses;
7400 mSetComponents = myComponents;
7401 } else {
7402 mSetPackages = null;
7403 mSetClasses = null;
7404 mSetComponents = null;
7405 }
7406 }
7407
7408 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7409 IOException {
7410 mShortActivity = parser.getAttributeValue(null, "name");
7411 mActivity = ComponentName.unflattenFromString(mShortActivity);
7412 if (mActivity == null) {
7413 mParseError = "Bad activity name " + mShortActivity;
7414 }
7415 String matchStr = parser.getAttributeValue(null, "match");
7416 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7417 String setCountStr = parser.getAttributeValue(null, "set");
7418 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7419
7420 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7421 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7422 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7423
7424 int setPos = 0;
7425
7426 int outerDepth = parser.getDepth();
7427 int type;
7428 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7429 && (type != XmlPullParser.END_TAG
7430 || parser.getDepth() > outerDepth)) {
7431 if (type == XmlPullParser.END_TAG
7432 || type == XmlPullParser.TEXT) {
7433 continue;
7434 }
7435
7436 String tagName = parser.getName();
7437 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7438 // + parser.getDepth() + " tag=" + tagName);
7439 if (tagName.equals("set")) {
7440 String name = parser.getAttributeValue(null, "name");
7441 if (name == null) {
7442 if (mParseError == null) {
7443 mParseError = "No name in set tag in preferred activity "
7444 + mShortActivity;
7445 }
7446 } else if (setPos >= setCount) {
7447 if (mParseError == null) {
7448 mParseError = "Too many set tags in preferred activity "
7449 + mShortActivity;
7450 }
7451 } else {
7452 ComponentName cn = ComponentName.unflattenFromString(name);
7453 if (cn == null) {
7454 if (mParseError == null) {
7455 mParseError = "Bad set name " + name + " in preferred activity "
7456 + mShortActivity;
7457 }
7458 } else {
7459 myPackages[setPos] = cn.getPackageName();
7460 myClasses[setPos] = cn.getClassName();
7461 myComponents[setPos] = name;
7462 setPos++;
7463 }
7464 }
7465 XmlUtils.skipCurrentTag(parser);
7466 } else if (tagName.equals("filter")) {
7467 //Log.i(TAG, "Starting to parse filter...");
7468 readFromXml(parser);
7469 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7470 // + parser.getDepth() + " tag=" + parser.getName());
7471 } else {
7472 reportSettingsProblem(Log.WARN,
7473 "Unknown element under <preferred-activities>: "
7474 + parser.getName());
7475 XmlUtils.skipCurrentTag(parser);
7476 }
7477 }
7478
7479 if (setPos != setCount) {
7480 if (mParseError == null) {
7481 mParseError = "Not enough set tags (expected " + setCount
7482 + " but found " + setPos + ") in " + mShortActivity;
7483 }
7484 }
7485
7486 mSetPackages = myPackages;
7487 mSetClasses = myClasses;
7488 mSetComponents = myComponents;
7489 }
7490
7491 public void writeToXml(XmlSerializer serializer) throws IOException {
7492 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7493 serializer.attribute(null, "name", mShortActivity);
7494 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7495 serializer.attribute(null, "set", Integer.toString(NS));
7496 for (int s=0; s<NS; s++) {
7497 serializer.startTag(null, "set");
7498 serializer.attribute(null, "name", mSetComponents[s]);
7499 serializer.endTag(null, "set");
7500 }
7501 serializer.startTag(null, "filter");
7502 super.writeToXml(serializer);
7503 serializer.endTag(null, "filter");
7504 }
7505
7506 boolean sameSet(List<ResolveInfo> query, int priority) {
7507 if (mSetPackages == null) return false;
7508 final int NQ = query.size();
7509 final int NS = mSetPackages.length;
7510 int numMatch = 0;
7511 for (int i=0; i<NQ; i++) {
7512 ResolveInfo ri = query.get(i);
7513 if (ri.priority != priority) continue;
7514 ActivityInfo ai = ri.activityInfo;
7515 boolean good = false;
7516 for (int j=0; j<NS; j++) {
7517 if (mSetPackages[j].equals(ai.packageName)
7518 && mSetClasses[j].equals(ai.name)) {
7519 numMatch++;
7520 good = true;
7521 break;
7522 }
7523 }
7524 if (!good) return false;
7525 }
7526 return numMatch == NS;
7527 }
7528 }
7529
7530 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007531 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 HashSet<String> grantedPermissions = new HashSet<String>();
7534 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007535
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007536 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007537 setFlags(pkgFlags);
7538 }
7539
7540 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007541 this.pkgFlags = pkgFlags & (
7542 ApplicationInfo.FLAG_SYSTEM |
7543 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007544 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007545 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 }
7547 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007549 /**
7550 * Settings base class for pending and resolved classes.
7551 */
7552 static class PackageSettingBase extends GrantedPermissions {
7553 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007554 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007555 File codePath;
7556 String codePathString;
7557 File resourcePath;
7558 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007559 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007560 String obbPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561 private long timeStamp;
7562 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007563 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007565 boolean uidError;
7566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007567 PackageSignatures signatures = new PackageSignatures();
7568
7569 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007570 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007572 /* Explicitly disabled components */
7573 HashSet<String> disabledComponents = new HashSet<String>(0);
7574 /* Explicitly enabled components */
7575 HashSet<String> enabledComponents = new HashSet<String>(0);
7576 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7577 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007578
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007579 PackageSettingBase origPackage;
7580
Jacek Surazski65e13172009-04-28 15:26:38 +02007581 /* package name of the app that installed this package */
7582 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007584 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007585 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007586 super(pkgFlags);
7587 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007588 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007589 init(codePath, resourcePath, pVersionCode);
7590 }
7591
7592 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007593 this.codePath = codePath;
7594 this.codePathString = codePath.toString();
7595 this.resourcePath = resourcePath;
7596 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007597 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007598 }
Kenny Root85387d72010-08-26 10:13:11 -07007599
Jacek Surazski65e13172009-04-28 15:26:38 +02007600 public void setInstallerPackageName(String packageName) {
7601 installerPackageName = packageName;
7602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007603
Jacek Surazski65e13172009-04-28 15:26:38 +02007604 String getInstallerPackageName() {
7605 return installerPackageName;
7606 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 public void setInstallStatus(int newStatus) {
7609 installStatus = newStatus;
7610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007612 public int getInstallStatus() {
7613 return installStatus;
7614 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 public void setTimeStamp(long newStamp) {
7617 if (newStamp != timeStamp) {
7618 timeStamp = newStamp;
7619 timeStampString = Long.toString(newStamp);
7620 }
7621 }
7622
7623 public void setTimeStamp(long newStamp, String newStampStr) {
7624 timeStamp = newStamp;
7625 timeStampString = newStampStr;
7626 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007628 public long getTimeStamp() {
7629 return timeStamp;
7630 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007631
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007632 public String getTimeStampStr() {
7633 return timeStampString;
7634 }
7635
7636 public void copyFrom(PackageSettingBase base) {
7637 grantedPermissions = base.grantedPermissions;
7638 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007640 timeStamp = base.timeStamp;
7641 timeStampString = base.timeStampString;
7642 signatures = base.signatures;
7643 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007644 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007645 disabledComponents = base.disabledComponents;
7646 enabledComponents = base.enabledComponents;
7647 enabled = base.enabled;
7648 installStatus = base.installStatus;
7649 }
7650
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007651 boolean enableComponentLP(String componentClassName) {
7652 boolean changed = disabledComponents.remove(componentClassName);
7653 changed |= enabledComponents.add(componentClassName);
7654 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007655 }
7656
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007657 boolean disableComponentLP(String componentClassName) {
7658 boolean changed = enabledComponents.remove(componentClassName);
7659 changed |= disabledComponents.add(componentClassName);
7660 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007661 }
7662
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007663 boolean restoreComponentLP(String componentClassName) {
7664 boolean changed = enabledComponents.remove(componentClassName);
7665 changed |= disabledComponents.remove(componentClassName);
7666 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007667 }
7668
7669 int currentEnabledStateLP(String componentName) {
7670 if (enabledComponents.contains(componentName)) {
7671 return COMPONENT_ENABLED_STATE_ENABLED;
7672 } else if (disabledComponents.contains(componentName)) {
7673 return COMPONENT_ENABLED_STATE_DISABLED;
7674 } else {
7675 return COMPONENT_ENABLED_STATE_DEFAULT;
7676 }
7677 }
7678 }
7679
7680 /**
7681 * Settings data for a particular package we know about.
7682 */
7683 static final class PackageSetting extends PackageSettingBase {
7684 int userId;
7685 PackageParser.Package pkg;
7686 SharedUserSetting sharedUser;
7687
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007688 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007689 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007690 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007691 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007693 @Override
7694 public String toString() {
7695 return "PackageSetting{"
7696 + Integer.toHexString(System.identityHashCode(this))
7697 + " " + name + "/" + userId + "}";
7698 }
7699 }
7700
7701 /**
7702 * Settings data for a particular shared user ID we know about.
7703 */
7704 static final class SharedUserSetting extends GrantedPermissions {
7705 final String name;
7706 int userId;
7707 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7708 final PackageSignatures signatures = new PackageSignatures();
7709
7710 SharedUserSetting(String _name, int _pkgFlags) {
7711 super(_pkgFlags);
7712 name = _name;
7713 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007715 @Override
7716 public String toString() {
7717 return "SharedUserSetting{"
7718 + Integer.toHexString(System.identityHashCode(this))
7719 + " " + name + "/" + userId + "}";
7720 }
7721 }
7722
7723 /**
7724 * Holds information about dynamic settings.
7725 */
7726 private static final class Settings {
7727 private final File mSettingsFilename;
7728 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007729 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007730 private final HashMap<String, PackageSetting> mPackages =
7731 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007732 // List of replaced system applications
7733 final HashMap<String, PackageSetting> mDisabledSysPackages =
7734 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007735
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007736 // These are the last platform API version we were using for
7737 // the apps installed on internal and external storage. It is
7738 // used to grant newer permissions one time during a system upgrade.
7739 int mInternalSdkPlatform;
7740 int mExternalSdkPlatform;
7741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007742 // The user's preferred activities associated with particular intent
7743 // filters.
7744 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7745 new IntentResolver<PreferredActivity, PreferredActivity>() {
7746 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007747 protected String packageForFilter(PreferredActivity filter) {
7748 return filter.mActivity.getPackageName();
7749 }
7750 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007751 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007752 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007753 out.print(prefix); out.print(
7754 Integer.toHexString(System.identityHashCode(filter)));
7755 out.print(' ');
7756 out.print(filter.mActivity.flattenToShortString());
7757 out.print(" match=0x");
7758 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007759 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007760 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007762 out.print(prefix); out.print(" ");
7763 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007764 }
7765 }
7766 }
7767 };
7768 private final HashMap<String, SharedUserSetting> mSharedUsers =
7769 new HashMap<String, SharedUserSetting>();
7770 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7771 private final SparseArray<Object> mOtherUserIds =
7772 new SparseArray<Object>();
7773
7774 // For reading/writing settings file.
7775 private final ArrayList<Signature> mPastSignatures =
7776 new ArrayList<Signature>();
7777
7778 // Mapping from permission names to info about them.
7779 final HashMap<String, BasePermission> mPermissions =
7780 new HashMap<String, BasePermission>();
7781
7782 // Mapping from permission tree names to info about them.
7783 final HashMap<String, BasePermission> mPermissionTrees =
7784 new HashMap<String, BasePermission>();
7785
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007786 // Packages that have been uninstalled and still need their external
7787 // storage data deleted.
7788 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7789
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007790 // Packages that have been renamed since they were first installed.
7791 // Keys are the new names of the packages, values are the original
7792 // names. The packages appear everwhere else under their original
7793 // names.
7794 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007796 private final StringBuilder mReadMessages = new StringBuilder();
7797
7798 private static final class PendingPackage extends PackageSettingBase {
7799 final int sharedId;
7800
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007801 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007802 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007803 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007804 this.sharedId = sharedId;
7805 }
7806 }
7807 private final ArrayList<PendingPackage> mPendingPackages
7808 = new ArrayList<PendingPackage>();
7809
7810 Settings() {
7811 File dataDir = Environment.getDataDirectory();
7812 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007813 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7814 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007815 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007816 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007817 FileUtils.setPermissions(systemDir.toString(),
7818 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7819 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7820 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007821 FileUtils.setPermissions(systemSecureDir.toString(),
7822 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7823 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7824 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825 mSettingsFilename = new File(systemDir, "packages.xml");
7826 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007827 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 }
7829
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007830 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007831 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007832 int pkgFlags, boolean create, boolean add) {
7833 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007834 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007835 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007836 return p;
7837 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007838
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007839 PackageSetting peekPackageLP(String name) {
7840 return mPackages.get(name);
7841 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007842 PackageSetting p = mPackages.get(name);
7843 if (p != null && p.codePath.getPath().equals(codePath)) {
7844 return p;
7845 }
7846 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007847 */
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 void setInstallStatus(String pkgName, int status) {
7851 PackageSetting p = mPackages.get(pkgName);
7852 if(p != null) {
7853 if(p.getInstallStatus() != status) {
7854 p.setInstallStatus(status);
7855 }
7856 }
7857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007858
Jacek Surazski65e13172009-04-28 15:26:38 +02007859 void setInstallerPackageName(String pkgName,
7860 String installerPkgName) {
7861 PackageSetting p = mPackages.get(pkgName);
7862 if(p != null) {
7863 p.setInstallerPackageName(installerPkgName);
7864 }
7865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007866
Jacek Surazski65e13172009-04-28 15:26:38 +02007867 String getInstallerPackageName(String pkgName) {
7868 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007869 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007870 }
7871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007872 int getInstallStatus(String pkgName) {
7873 PackageSetting p = mPackages.get(pkgName);
7874 if(p != null) {
7875 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007876 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007877 return -1;
7878 }
7879
7880 SharedUserSetting getSharedUserLP(String name,
7881 int pkgFlags, boolean create) {
7882 SharedUserSetting s = mSharedUsers.get(name);
7883 if (s == null) {
7884 if (!create) {
7885 return null;
7886 }
7887 s = new SharedUserSetting(name, pkgFlags);
7888 if (MULTIPLE_APPLICATION_UIDS) {
7889 s.userId = newUserIdLP(s);
7890 } else {
7891 s.userId = FIRST_APPLICATION_UID;
7892 }
7893 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7894 // < 0 means we couldn't assign a userid; fall out and return
7895 // s, which is currently null
7896 if (s.userId >= 0) {
7897 mSharedUsers.put(name, s);
7898 }
7899 }
7900
7901 return s;
7902 }
7903
7904 int disableSystemPackageLP(String name) {
7905 PackageSetting p = mPackages.get(name);
7906 if(p == null) {
7907 Log.w(TAG, "Package:"+name+" is not an installed package");
7908 return -1;
7909 }
7910 PackageSetting dp = mDisabledSysPackages.get(name);
7911 // always make sure the system package code and resource paths dont change
7912 if(dp == null) {
7913 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7914 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7915 }
7916 mDisabledSysPackages.put(name, p);
7917 }
7918 return removePackageLP(name);
7919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007920
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007921 PackageSetting enableSystemPackageLP(String name) {
7922 PackageSetting p = mDisabledSysPackages.get(name);
7923 if(p == null) {
7924 Log.w(TAG, "Package:"+name+" is not disabled");
7925 return null;
7926 }
7927 // Reset flag in ApplicationInfo object
7928 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7929 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7930 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007931 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007932 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007933 mDisabledSysPackages.remove(name);
7934 return ret;
7935 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007936
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007937 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007938 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007939 PackageSetting p = mPackages.get(name);
7940 if (p != null) {
7941 if (p.userId == uid) {
7942 return p;
7943 }
7944 reportSettingsProblem(Log.ERROR,
7945 "Adding duplicate package, keeping first: " + name);
7946 return null;
7947 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007948 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007949 p.userId = uid;
7950 if (addUserIdLP(uid, p, name)) {
7951 mPackages.put(name, p);
7952 return p;
7953 }
7954 return null;
7955 }
7956
7957 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7958 SharedUserSetting s = mSharedUsers.get(name);
7959 if (s != null) {
7960 if (s.userId == uid) {
7961 return s;
7962 }
7963 reportSettingsProblem(Log.ERROR,
7964 "Adding duplicate shared user, keeping first: " + name);
7965 return null;
7966 }
7967 s = new SharedUserSetting(name, pkgFlags);
7968 s.userId = uid;
7969 if (addUserIdLP(uid, s, name)) {
7970 mSharedUsers.put(name, s);
7971 return s;
7972 }
7973 return null;
7974 }
7975
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007976 // Transfer ownership of permissions from one package to another.
7977 private void transferPermissions(String origPkg, String newPkg) {
7978 // Transfer ownership of permissions to the new package.
7979 for (int i=0; i<2; i++) {
7980 HashMap<String, BasePermission> permissions =
7981 i == 0 ? mPermissionTrees : mPermissions;
7982 for (BasePermission bp : permissions.values()) {
7983 if (origPkg.equals(bp.sourcePackage)) {
7984 if (DEBUG_UPGRADE) Log.v(TAG,
7985 "Moving permission " + bp.name
7986 + " from pkg " + bp.sourcePackage
7987 + " to " + newPkg);
7988 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007989 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007990 bp.perm = null;
7991 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007992 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007993 }
7994 bp.uid = 0;
7995 bp.gids = null;
7996 }
7997 }
7998 }
7999 }
8000
8001 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008002 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008003 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008004 PackageSetting p = mPackages.get(name);
8005 if (p != null) {
8006 if (!p.codePath.equals(codePath)) {
8007 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008008 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008009 // This is an updated system app with versions in both system
8010 // and data partition. Just let the most recent version
8011 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008012 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008013 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008014 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008015 // Just a change in the code path is not an issue, but
8016 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008017 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008018 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008019 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008020 }
8021 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008022 reportSettingsProblem(Log.WARN,
8023 "Package " + name + " shared user changed from "
8024 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8025 + " to "
8026 + (sharedUser != null ? sharedUser.name : "<nothing>")
8027 + "; replacing with new");
8028 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008029 } else {
8030 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8031 // If what we are scanning is a system package, then
8032 // make it so, regardless of whether it was previously
8033 // installed only in the data partition.
8034 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008036 }
8037 }
8038 if (p == null) {
8039 // Create a new PackageSettings entry. this can end up here because
8040 // of code path mismatch or user id mismatch of an updated system partition
8041 if (!create) {
8042 return null;
8043 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008044 if (origPackage != null) {
8045 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008046 p = new PackageSetting(origPackage.name, name, codePath,
8047 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008048 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8049 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008050 // Note that we will retain the new package's signature so
8051 // that we can keep its data.
8052 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008053 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008054 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008055 p.sharedUser = origPackage.sharedUser;
8056 p.userId = origPackage.userId;
8057 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008058 mRenamedPackages.put(name, origPackage.name);
8059 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008060 // Update new package state.
8061 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008062 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008063 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008064 p.setTimeStamp(codePath.lastModified());
8065 p.sharedUser = sharedUser;
8066 if (sharedUser != null) {
8067 p.userId = sharedUser.userId;
8068 } else if (MULTIPLE_APPLICATION_UIDS) {
8069 // Clone the setting here for disabled system packages
8070 PackageSetting dis = mDisabledSysPackages.get(name);
8071 if (dis != null) {
8072 // For disabled packages a new setting is created
8073 // from the existing user id. This still has to be
8074 // added to list of user id's
8075 // Copy signatures from previous setting
8076 if (dis.signatures.mSignatures != null) {
8077 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8078 }
8079 p.userId = dis.userId;
8080 // Clone permissions
8081 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008082 // Clone component info
8083 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8084 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8085 // Add new setting to list of user ids
8086 addUserIdLP(p.userId, p, name);
8087 } else {
8088 // Assign new user id
8089 p.userId = newUserIdLP(p);
8090 }
8091 } else {
8092 p.userId = FIRST_APPLICATION_UID;
8093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008094 }
8095 if (p.userId < 0) {
8096 reportSettingsProblem(Log.WARN,
8097 "Package " + name + " could not be assigned a valid uid");
8098 return null;
8099 }
8100 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008101 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008102 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008103 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008104 }
8105 }
8106 return p;
8107 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008108
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008109 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008110 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008111 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008112 final String codePath = pkg.applicationInfo.sourceDir;
8113 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008114 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008115 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008116 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008117 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008118 p.codePath = new File(codePath);
8119 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008120 }
8121 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008122 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008123 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008124 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008125 p.resourcePath = new File(resourcePath);
8126 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008127 }
Kenny Root85387d72010-08-26 10:13:11 -07008128 // Update the native library path if needed
8129 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8130 if (nativeLibraryPath != null
8131 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8132 p.nativeLibraryPathString = nativeLibraryPath;
8133 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008134 // Update version code if needed
8135 if (pkg.mVersionCode != p.versionCode) {
8136 p.versionCode = pkg.mVersionCode;
8137 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008138 // Update signatures if needed.
8139 if (p.signatures.mSignatures == null) {
8140 p.signatures.assignSignatures(pkg.mSignatures);
8141 }
8142 // If this app defines a shared user id initialize
8143 // the shared user signatures as well.
8144 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8145 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8146 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008147 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8148 }
8149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 // Utility method that adds a PackageSetting to mPackages and
8151 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008152 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008153 SharedUserSetting sharedUser) {
8154 mPackages.put(name, p);
8155 if (sharedUser != null) {
8156 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8157 reportSettingsProblem(Log.ERROR,
8158 "Package " + p.name + " was user "
8159 + p.sharedUser + " but is now " + sharedUser
8160 + "; I am not changing its files so it will probably fail!");
8161 p.sharedUser.packages.remove(p);
8162 } else if (p.userId != sharedUser.userId) {
8163 reportSettingsProblem(Log.ERROR,
8164 "Package " + p.name + " was user id " + p.userId
8165 + " but is now user " + sharedUser
8166 + " with id " + sharedUser.userId
8167 + "; I am not changing its files so it will probably fail!");
8168 }
8169
8170 sharedUser.packages.add(p);
8171 p.sharedUser = sharedUser;
8172 p.userId = sharedUser.userId;
8173 }
8174 }
8175
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008176 /*
8177 * Update the shared user setting when a package using
8178 * specifying the shared user id is removed. The gids
8179 * associated with each permission of the deleted package
8180 * are removed from the shared user's gid list only if its
8181 * not in use by other permissions of packages in the
8182 * shared user setting.
8183 */
8184 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008185 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008186 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008187 return;
8188 }
8189 // No sharedUserId
8190 if (deletedPs.sharedUser == null) {
8191 return;
8192 }
8193 SharedUserSetting sus = deletedPs.sharedUser;
8194 // Update permissions
8195 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8196 boolean used = false;
8197 if (!sus.grantedPermissions.contains (eachPerm)) {
8198 continue;
8199 }
8200 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008201 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008202 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008203 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008204 used = true;
8205 break;
8206 }
8207 }
8208 if (!used) {
8209 // can safely delete this permission from list
8210 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008211 }
8212 }
8213 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008214 int newGids[] = globalGids;
8215 for (String eachPerm : sus.grantedPermissions) {
8216 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008217 if (bp != null) {
8218 newGids = appendInts(newGids, bp.gids);
8219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008220 }
8221 sus.gids = newGids;
8222 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008224 private int removePackageLP(String name) {
8225 PackageSetting p = mPackages.get(name);
8226 if (p != null) {
8227 mPackages.remove(name);
8228 if (p.sharedUser != null) {
8229 p.sharedUser.packages.remove(p);
8230 if (p.sharedUser.packages.size() == 0) {
8231 mSharedUsers.remove(p.sharedUser.name);
8232 removeUserIdLP(p.sharedUser.userId);
8233 return p.sharedUser.userId;
8234 }
8235 } else {
8236 removeUserIdLP(p.userId);
8237 return p.userId;
8238 }
8239 }
8240 return -1;
8241 }
8242
8243 private boolean addUserIdLP(int uid, Object obj, Object name) {
8244 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8245 return false;
8246 }
8247
8248 if (uid >= FIRST_APPLICATION_UID) {
8249 int N = mUserIds.size();
8250 final int index = uid - FIRST_APPLICATION_UID;
8251 while (index >= N) {
8252 mUserIds.add(null);
8253 N++;
8254 }
8255 if (mUserIds.get(index) != null) {
8256 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008257 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008258 + " name=" + name);
8259 return false;
8260 }
8261 mUserIds.set(index, obj);
8262 } else {
8263 if (mOtherUserIds.get(uid) != null) {
8264 reportSettingsProblem(Log.ERROR,
8265 "Adding duplicate shared id: " + uid
8266 + " name=" + name);
8267 return false;
8268 }
8269 mOtherUserIds.put(uid, obj);
8270 }
8271 return true;
8272 }
8273
8274 public Object getUserIdLP(int uid) {
8275 if (uid >= FIRST_APPLICATION_UID) {
8276 int N = mUserIds.size();
8277 final int index = uid - FIRST_APPLICATION_UID;
8278 return index < N ? mUserIds.get(index) : null;
8279 } else {
8280 return mOtherUserIds.get(uid);
8281 }
8282 }
8283
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008284 private Set<String> findPackagesWithFlag(int flag) {
8285 Set<String> ret = new HashSet<String>();
8286 for (PackageSetting ps : mPackages.values()) {
8287 // Has to match atleast all the flag bits set on flag
8288 if ((ps.pkgFlags & flag) == flag) {
8289 ret.add(ps.name);
8290 }
8291 }
8292 return ret;
8293 }
8294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008295 private void removeUserIdLP(int uid) {
8296 if (uid >= FIRST_APPLICATION_UID) {
8297 int N = mUserIds.size();
8298 final int index = uid - FIRST_APPLICATION_UID;
8299 if (index < N) mUserIds.set(index, null);
8300 } else {
8301 mOtherUserIds.remove(uid);
8302 }
8303 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008305 void writeLP() {
8306 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8307
8308 // Keep the old settings around until we know the new ones have
8309 // been successfully written.
8310 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008311 // Presence of backup settings file indicates that we failed
8312 // to persist settings earlier. So preserve the older
8313 // backup for future reference since the current settings
8314 // might have been corrupted.
8315 if (!mBackupSettingsFilename.exists()) {
8316 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008317 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008318 return;
8319 }
8320 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008321 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008322 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008323 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008324 }
8325
8326 mPastSignatures.clear();
8327
8328 try {
8329 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8330
8331 //XmlSerializer serializer = XmlUtils.serializerInstance();
8332 XmlSerializer serializer = new FastXmlSerializer();
8333 serializer.setOutput(str, "utf-8");
8334 serializer.startDocument(null, true);
8335 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8336
8337 serializer.startTag(null, "packages");
8338
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008339 serializer.startTag(null, "last-platform-version");
8340 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8341 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8342 serializer.endTag(null, "last-platform-version");
8343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 serializer.startTag(null, "permission-trees");
8345 for (BasePermission bp : mPermissionTrees.values()) {
8346 writePermission(serializer, bp);
8347 }
8348 serializer.endTag(null, "permission-trees");
8349
8350 serializer.startTag(null, "permissions");
8351 for (BasePermission bp : mPermissions.values()) {
8352 writePermission(serializer, bp);
8353 }
8354 serializer.endTag(null, "permissions");
8355
8356 for (PackageSetting pkg : mPackages.values()) {
8357 writePackage(serializer, pkg);
8358 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008360 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8361 writeDisabledSysPackage(serializer, pkg);
8362 }
8363
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008364 serializer.startTag(null, "preferred-activities");
8365 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8366 serializer.startTag(null, "item");
8367 pa.writeToXml(serializer);
8368 serializer.endTag(null, "item");
8369 }
8370 serializer.endTag(null, "preferred-activities");
8371
8372 for (SharedUserSetting usr : mSharedUsers.values()) {
8373 serializer.startTag(null, "shared-user");
8374 serializer.attribute(null, "name", usr.name);
8375 serializer.attribute(null, "userId",
8376 Integer.toString(usr.userId));
8377 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8378 serializer.startTag(null, "perms");
8379 for (String name : usr.grantedPermissions) {
8380 serializer.startTag(null, "item");
8381 serializer.attribute(null, "name", name);
8382 serializer.endTag(null, "item");
8383 }
8384 serializer.endTag(null, "perms");
8385 serializer.endTag(null, "shared-user");
8386 }
8387
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008388 if (mPackagesToBeCleaned.size() > 0) {
8389 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8390 serializer.startTag(null, "cleaning-package");
8391 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8392 serializer.endTag(null, "cleaning-package");
8393 }
8394 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008395
8396 if (mRenamedPackages.size() > 0) {
8397 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8398 serializer.startTag(null, "renamed-package");
8399 serializer.attribute(null, "new", e.getKey());
8400 serializer.attribute(null, "old", e.getValue());
8401 serializer.endTag(null, "renamed-package");
8402 }
8403 }
8404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008405 serializer.endTag(null, "packages");
8406
8407 serializer.endDocument();
8408
8409 str.flush();
8410 str.close();
8411
8412 // New settings successfully written, old ones are no longer
8413 // needed.
8414 mBackupSettingsFilename.delete();
8415 FileUtils.setPermissions(mSettingsFilename.toString(),
8416 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8417 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8418 |FileUtils.S_IROTH,
8419 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008420
8421 // Write package list file now, use a JournaledFile.
8422 //
8423 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8424 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8425
8426 str = new FileOutputStream(journal.chooseForWrite());
8427 try {
8428 StringBuilder sb = new StringBuilder();
8429 for (PackageSetting pkg : mPackages.values()) {
8430 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008431 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008432 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8433
8434 // Avoid any application that has a space in its path
8435 // or that is handled by the system.
8436 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8437 continue;
8438
8439 // we store on each line the following information for now:
8440 //
8441 // pkgName - package name
8442 // userId - application-specific user id
8443 // debugFlag - 0 or 1 if the package is debuggable.
8444 // dataPath - path to package's data path
8445 //
8446 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8447 //
8448 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8449 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8450 // system/core/run-as/run-as.c
8451 //
8452 sb.setLength(0);
8453 sb.append(ai.packageName);
8454 sb.append(" ");
8455 sb.append((int)ai.uid);
8456 sb.append(isDebug ? " 1 " : " 0 ");
8457 sb.append(dataPath);
8458 sb.append("\n");
8459 str.write(sb.toString().getBytes());
8460 }
8461 str.flush();
8462 str.close();
8463 journal.commit();
8464 }
8465 catch (Exception e) {
8466 journal.rollback();
8467 }
8468
8469 FileUtils.setPermissions(mPackageListFilename.toString(),
8470 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8471 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8472 |FileUtils.S_IROTH,
8473 -1, -1);
8474
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008475 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008476
8477 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008478 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 -08008479 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008480 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 -08008481 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008482 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008483 if (mSettingsFilename.exists()) {
8484 if (!mSettingsFilename.delete()) {
8485 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8486 }
8487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008488 //Debug.stopMethodTracing();
8489 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008490
8491 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008492 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008493 serializer.startTag(null, "updated-package");
8494 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008495 if (pkg.realName != null) {
8496 serializer.attribute(null, "realName", pkg.realName);
8497 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008498 serializer.attribute(null, "codePath", pkg.codePathString);
8499 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008500 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008501 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8502 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8503 }
Kenny Root85387d72010-08-26 10:13:11 -07008504 if (pkg.nativeLibraryPathString != null) {
8505 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8506 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008507 if (pkg.sharedUser == null) {
8508 serializer.attribute(null, "userId",
8509 Integer.toString(pkg.userId));
8510 } else {
8511 serializer.attribute(null, "sharedUserId",
8512 Integer.toString(pkg.userId));
8513 }
8514 serializer.startTag(null, "perms");
8515 if (pkg.sharedUser == null) {
8516 // If this is a shared user, the permissions will
8517 // be written there. We still need to write an
8518 // empty permissions list so permissionsFixed will
8519 // be set.
8520 for (final String name : pkg.grantedPermissions) {
8521 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008522 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008523 // We only need to write signature or system permissions but this wont
8524 // match the semantics of grantedPermissions. So write all permissions.
8525 serializer.startTag(null, "item");
8526 serializer.attribute(null, "name", name);
8527 serializer.endTag(null, "item");
8528 }
8529 }
8530 }
8531 serializer.endTag(null, "perms");
8532 serializer.endTag(null, "updated-package");
8533 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008534
8535 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008536 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008537 serializer.startTag(null, "package");
8538 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008539 if (pkg.realName != null) {
8540 serializer.attribute(null, "realName", pkg.realName);
8541 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008542 serializer.attribute(null, "codePath", pkg.codePathString);
8543 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8544 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8545 }
Kenny Root85387d72010-08-26 10:13:11 -07008546 if (pkg.nativeLibraryPathString != null) {
8547 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8548 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008549 serializer.attribute(null, "flags",
8550 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008551 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008552 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008553 if (pkg.sharedUser == null) {
8554 serializer.attribute(null, "userId",
8555 Integer.toString(pkg.userId));
8556 } else {
8557 serializer.attribute(null, "sharedUserId",
8558 Integer.toString(pkg.userId));
8559 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008560 if (pkg.uidError) {
8561 serializer.attribute(null, "uidError", "true");
8562 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008563 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8564 serializer.attribute(null, "enabled",
8565 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8566 ? "true" : "false");
8567 }
8568 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8569 serializer.attribute(null, "installStatus", "false");
8570 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008571 if (pkg.installerPackageName != null) {
8572 serializer.attribute(null, "installer", pkg.installerPackageName);
8573 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008574 if (pkg.obbPathString != null) {
8575 serializer.attribute(null, "obbPath", pkg.obbPathString);
8576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008577 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8578 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8579 serializer.startTag(null, "perms");
8580 if (pkg.sharedUser == null) {
8581 // If this is a shared user, the permissions will
8582 // be written there. We still need to write an
8583 // empty permissions list so permissionsFixed will
8584 // be set.
8585 for (final String name : pkg.grantedPermissions) {
8586 serializer.startTag(null, "item");
8587 serializer.attribute(null, "name", name);
8588 serializer.endTag(null, "item");
8589 }
8590 }
8591 serializer.endTag(null, "perms");
8592 }
8593 if (pkg.disabledComponents.size() > 0) {
8594 serializer.startTag(null, "disabled-components");
8595 for (final String name : pkg.disabledComponents) {
8596 serializer.startTag(null, "item");
8597 serializer.attribute(null, "name", name);
8598 serializer.endTag(null, "item");
8599 }
8600 serializer.endTag(null, "disabled-components");
8601 }
8602 if (pkg.enabledComponents.size() > 0) {
8603 serializer.startTag(null, "enabled-components");
8604 for (final String name : pkg.enabledComponents) {
8605 serializer.startTag(null, "item");
8606 serializer.attribute(null, "name", name);
8607 serializer.endTag(null, "item");
8608 }
8609 serializer.endTag(null, "enabled-components");
8610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 serializer.endTag(null, "package");
8613 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008615 void writePermission(XmlSerializer serializer, BasePermission bp)
8616 throws XmlPullParserException, java.io.IOException {
8617 if (bp.type != BasePermission.TYPE_BUILTIN
8618 && bp.sourcePackage != null) {
8619 serializer.startTag(null, "item");
8620 serializer.attribute(null, "name", bp.name);
8621 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008622 if (bp.protectionLevel !=
8623 PermissionInfo.PROTECTION_NORMAL) {
8624 serializer.attribute(null, "protection",
8625 Integer.toString(bp.protectionLevel));
8626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008627 if (DEBUG_SETTINGS) Log.v(TAG,
8628 "Writing perm: name=" + bp.name + " type=" + bp.type);
8629 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8630 PermissionInfo pi = bp.perm != null ? bp.perm.info
8631 : bp.pendingInfo;
8632 if (pi != null) {
8633 serializer.attribute(null, "type", "dynamic");
8634 if (pi.icon != 0) {
8635 serializer.attribute(null, "icon",
8636 Integer.toString(pi.icon));
8637 }
8638 if (pi.nonLocalizedLabel != null) {
8639 serializer.attribute(null, "label",
8640 pi.nonLocalizedLabel.toString());
8641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008642 }
8643 }
8644 serializer.endTag(null, "item");
8645 }
8646 }
8647
8648 String getReadMessagesLP() {
8649 return mReadMessages.toString();
8650 }
8651
Oscar Montemayora8529f62009-11-18 10:14:20 -08008652 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8654 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008655 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008656 while(its.hasNext()) {
8657 String key = its.next();
8658 PackageSetting ps = mPackages.get(key);
8659 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008660 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008661 }
8662 }
8663 return ret;
8664 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008666 boolean readLP() {
8667 FileInputStream str = null;
8668 if (mBackupSettingsFilename.exists()) {
8669 try {
8670 str = new FileInputStream(mBackupSettingsFilename);
8671 mReadMessages.append("Reading from backup settings file\n");
8672 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008673 if (mSettingsFilename.exists()) {
8674 // If both the backup and settings file exist, we
8675 // ignore the settings since it might have been
8676 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008677 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008678 mSettingsFilename.delete();
8679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008680 } catch (java.io.IOException e) {
8681 // We'll try for the normal settings file.
8682 }
8683 }
8684
8685 mPastSignatures.clear();
8686
8687 try {
8688 if (str == null) {
8689 if (!mSettingsFilename.exists()) {
8690 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008691 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008692 return false;
8693 }
8694 str = new FileInputStream(mSettingsFilename);
8695 }
8696 XmlPullParser parser = Xml.newPullParser();
8697 parser.setInput(str, null);
8698
8699 int type;
8700 while ((type=parser.next()) != XmlPullParser.START_TAG
8701 && type != XmlPullParser.END_DOCUMENT) {
8702 ;
8703 }
8704
8705 if (type != XmlPullParser.START_TAG) {
8706 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008707 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008708 return false;
8709 }
8710
8711 int outerDepth = parser.getDepth();
8712 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8713 && (type != XmlPullParser.END_TAG
8714 || parser.getDepth() > outerDepth)) {
8715 if (type == XmlPullParser.END_TAG
8716 || type == XmlPullParser.TEXT) {
8717 continue;
8718 }
8719
8720 String tagName = parser.getName();
8721 if (tagName.equals("package")) {
8722 readPackageLP(parser);
8723 } else if (tagName.equals("permissions")) {
8724 readPermissionsLP(mPermissions, parser);
8725 } else if (tagName.equals("permission-trees")) {
8726 readPermissionsLP(mPermissionTrees, parser);
8727 } else if (tagName.equals("shared-user")) {
8728 readSharedUserLP(parser);
8729 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008730 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008731 } else if (tagName.equals("preferred-activities")) {
8732 readPreferredActivitiesLP(parser);
8733 } else if(tagName.equals("updated-package")) {
8734 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008735 } else if (tagName.equals("cleaning-package")) {
8736 String name = parser.getAttributeValue(null, "name");
8737 if (name != null) {
8738 mPackagesToBeCleaned.add(name);
8739 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008740 } else if (tagName.equals("renamed-package")) {
8741 String nname = parser.getAttributeValue(null, "new");
8742 String oname = parser.getAttributeValue(null, "old");
8743 if (nname != null && oname != null) {
8744 mRenamedPackages.put(nname, oname);
8745 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008746 } else if (tagName.equals("last-platform-version")) {
8747 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8748 try {
8749 String internal = parser.getAttributeValue(null, "internal");
8750 if (internal != null) {
8751 mInternalSdkPlatform = Integer.parseInt(internal);
8752 }
8753 String external = parser.getAttributeValue(null, "external");
8754 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008755 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008756 }
8757 } catch (NumberFormatException e) {
8758 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008759 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008760 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008761 + parser.getName());
8762 XmlUtils.skipCurrentTag(parser);
8763 }
8764 }
8765
8766 str.close();
8767
8768 } catch(XmlPullParserException e) {
8769 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008770 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008771
8772 } catch(java.io.IOException e) {
8773 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008774 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008775
8776 }
8777
8778 int N = mPendingPackages.size();
8779 for (int i=0; i<N; i++) {
8780 final PendingPackage pp = mPendingPackages.get(i);
8781 Object idObj = getUserIdLP(pp.sharedId);
8782 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008783 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008784 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008785 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008786 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008787 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 + pp.name);
8789 continue;
8790 }
8791 p.copyFrom(pp);
8792 } else if (idObj != null) {
8793 String msg = "Bad package setting: package " + pp.name
8794 + " has shared uid " + pp.sharedId
8795 + " that is not a shared uid\n";
8796 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008797 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008798 } else {
8799 String msg = "Bad package setting: package " + pp.name
8800 + " has shared uid " + pp.sharedId
8801 + " that is not defined\n";
8802 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008803 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008804 }
8805 }
8806 mPendingPackages.clear();
8807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008808 mReadMessages.append("Read completed successfully: "
8809 + mPackages.size() + " packages, "
8810 + mSharedUsers.size() + " shared uids\n");
8811
8812 return true;
8813 }
8814
8815 private int readInt(XmlPullParser parser, String ns, String name,
8816 int defValue) {
8817 String v = parser.getAttributeValue(ns, name);
8818 try {
8819 if (v == null) {
8820 return defValue;
8821 }
8822 return Integer.parseInt(v);
8823 } catch (NumberFormatException e) {
8824 reportSettingsProblem(Log.WARN,
8825 "Error in package manager settings: attribute " +
8826 name + " has bad integer value " + v + " at "
8827 + parser.getPositionDescription());
8828 }
8829 return defValue;
8830 }
8831
8832 private void readPermissionsLP(HashMap<String, BasePermission> out,
8833 XmlPullParser parser)
8834 throws IOException, XmlPullParserException {
8835 int outerDepth = parser.getDepth();
8836 int type;
8837 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8838 && (type != XmlPullParser.END_TAG
8839 || parser.getDepth() > outerDepth)) {
8840 if (type == XmlPullParser.END_TAG
8841 || type == XmlPullParser.TEXT) {
8842 continue;
8843 }
8844
8845 String tagName = parser.getName();
8846 if (tagName.equals("item")) {
8847 String name = parser.getAttributeValue(null, "name");
8848 String sourcePackage = parser.getAttributeValue(null, "package");
8849 String ptype = parser.getAttributeValue(null, "type");
8850 if (name != null && sourcePackage != null) {
8851 boolean dynamic = "dynamic".equals(ptype);
8852 BasePermission bp = new BasePermission(name, sourcePackage,
8853 dynamic
8854 ? BasePermission.TYPE_DYNAMIC
8855 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008856 bp.protectionLevel = readInt(parser, null, "protection",
8857 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008858 if (dynamic) {
8859 PermissionInfo pi = new PermissionInfo();
8860 pi.packageName = sourcePackage.intern();
8861 pi.name = name.intern();
8862 pi.icon = readInt(parser, null, "icon", 0);
8863 pi.nonLocalizedLabel = parser.getAttributeValue(
8864 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008865 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 bp.pendingInfo = pi;
8867 }
8868 out.put(bp.name, bp);
8869 } else {
8870 reportSettingsProblem(Log.WARN,
8871 "Error in package manager settings: permissions has"
8872 + " no name at " + parser.getPositionDescription());
8873 }
8874 } else {
8875 reportSettingsProblem(Log.WARN,
8876 "Unknown element reading permissions: "
8877 + parser.getName() + " at "
8878 + parser.getPositionDescription());
8879 }
8880 XmlUtils.skipCurrentTag(parser);
8881 }
8882 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008884 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008885 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008886 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008887 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888 String codePathStr = parser.getAttributeValue(null, "codePath");
8889 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008890 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008891 resourcePathStr = codePathStr;
8892 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008893 String version = parser.getAttributeValue(null, "version");
8894 int versionCode = 0;
8895 if (version != null) {
8896 try {
8897 versionCode = Integer.parseInt(version);
8898 } catch (NumberFormatException e) {
8899 }
8900 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008901
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008902 int pkgFlags = 0;
8903 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008904 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008905 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008906 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008907 String timeStampStr = parser.getAttributeValue(null, "ts");
8908 if (timeStampStr != null) {
8909 try {
8910 long timeStamp = Long.parseLong(timeStampStr);
8911 ps.setTimeStamp(timeStamp, timeStampStr);
8912 } catch (NumberFormatException e) {
8913 }
8914 }
8915 String idStr = parser.getAttributeValue(null, "userId");
8916 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8917 if(ps.userId <= 0) {
8918 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8919 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8920 }
8921 int outerDepth = parser.getDepth();
8922 int type;
8923 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8924 && (type != XmlPullParser.END_TAG
8925 || parser.getDepth() > outerDepth)) {
8926 if (type == XmlPullParser.END_TAG
8927 || type == XmlPullParser.TEXT) {
8928 continue;
8929 }
8930
8931 String tagName = parser.getName();
8932 if (tagName.equals("perms")) {
8933 readGrantedPermissionsLP(parser,
8934 ps.grantedPermissions);
8935 } else {
8936 reportSettingsProblem(Log.WARN,
8937 "Unknown element under <updated-package>: "
8938 + parser.getName());
8939 XmlUtils.skipCurrentTag(parser);
8940 }
8941 }
8942 mDisabledSysPackages.put(name, ps);
8943 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008944
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008945 private void readPackageLP(XmlPullParser parser)
8946 throws XmlPullParserException, IOException {
8947 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008948 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 String idStr = null;
8950 String sharedIdStr = null;
8951 String codePathStr = null;
8952 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07008953 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07008954 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008956 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008957 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008958 int pkgFlags = 0;
8959 String timeStampStr;
8960 long timeStamp = 0;
8961 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008962 String version = null;
8963 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 try {
8965 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008966 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008967 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008968 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008969 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8970 codePathStr = parser.getAttributeValue(null, "codePath");
8971 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07008972 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07008973 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008974 version = parser.getAttributeValue(null, "version");
8975 if (version != null) {
8976 try {
8977 versionCode = Integer.parseInt(version);
8978 } catch (NumberFormatException e) {
8979 }
8980 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008981 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008982
8983 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008984 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008985 try {
8986 pkgFlags = Integer.parseInt(systemStr);
8987 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008988 }
8989 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008990 // For backward compatibility
8991 systemStr = parser.getAttributeValue(null, "system");
8992 if (systemStr != null) {
8993 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8994 } else {
8995 // Old settings that don't specify system... just treat
8996 // them as system, good enough.
8997 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008999 }
9000 timeStampStr = parser.getAttributeValue(null, "ts");
9001 if (timeStampStr != null) {
9002 try {
9003 timeStamp = Long.parseLong(timeStampStr);
9004 } catch (NumberFormatException e) {
9005 }
9006 }
9007 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9008 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9009 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9010 if (resourcePathStr == null) {
9011 resourcePathStr = codePathStr;
9012 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009013 if (realName != null) {
9014 realName = realName.intern();
9015 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009016 if (name == null) {
9017 reportSettingsProblem(Log.WARN,
9018 "Error in package manager settings: <package> has no name at "
9019 + parser.getPositionDescription());
9020 } else if (codePathStr == null) {
9021 reportSettingsProblem(Log.WARN,
9022 "Error in package manager settings: <package> has no codePath at "
9023 + parser.getPositionDescription());
9024 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009025 packageSetting = addPackageLP(name.intern(), realName,
9026 new File(codePathStr), new File(resourcePathStr),
9027 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009028 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9029 + ": userId=" + userId + " pkg=" + packageSetting);
9030 if (packageSetting == null) {
9031 reportSettingsProblem(Log.ERROR,
9032 "Failure adding uid " + userId
9033 + " while parsing settings at "
9034 + parser.getPositionDescription());
9035 } else {
9036 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9037 }
9038 } else if (sharedIdStr != null) {
9039 userId = sharedIdStr != null
9040 ? Integer.parseInt(sharedIdStr) : 0;
9041 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009042 packageSetting = new PendingPackage(name.intern(), realName,
9043 new File(codePathStr), new File(resourcePathStr),
9044 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009045 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9046 mPendingPackages.add((PendingPackage) packageSetting);
9047 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9048 + ": sharedUserId=" + userId + " pkg="
9049 + packageSetting);
9050 } else {
9051 reportSettingsProblem(Log.WARN,
9052 "Error in package manager settings: package "
9053 + name + " has bad sharedId " + sharedIdStr
9054 + " at " + parser.getPositionDescription());
9055 }
9056 } else {
9057 reportSettingsProblem(Log.WARN,
9058 "Error in package manager settings: package "
9059 + name + " has bad userId " + idStr + " at "
9060 + parser.getPositionDescription());
9061 }
9062 } catch (NumberFormatException e) {
9063 reportSettingsProblem(Log.WARN,
9064 "Error in package manager settings: package "
9065 + name + " has bad userId " + idStr + " at "
9066 + parser.getPositionDescription());
9067 }
9068 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009069 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009070 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009071 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009072 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009073 final String enabledStr = parser.getAttributeValue(null, "enabled");
9074 if (enabledStr != null) {
9075 if (enabledStr.equalsIgnoreCase("true")) {
9076 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9077 } else if (enabledStr.equalsIgnoreCase("false")) {
9078 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9079 } else if (enabledStr.equalsIgnoreCase("default")) {
9080 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9081 } else {
9082 reportSettingsProblem(Log.WARN,
9083 "Error in package manager settings: package "
9084 + name + " has bad enabled value: " + idStr
9085 + " at " + parser.getPositionDescription());
9086 }
9087 } else {
9088 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9089 }
9090 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9091 if (installStatusStr != null) {
9092 if (installStatusStr.equalsIgnoreCase("false")) {
9093 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9094 } else {
9095 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9096 }
9097 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009098
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009099 int outerDepth = parser.getDepth();
9100 int type;
9101 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9102 && (type != XmlPullParser.END_TAG
9103 || parser.getDepth() > outerDepth)) {
9104 if (type == XmlPullParser.END_TAG
9105 || type == XmlPullParser.TEXT) {
9106 continue;
9107 }
9108
9109 String tagName = parser.getName();
9110 if (tagName.equals("disabled-components")) {
9111 readDisabledComponentsLP(packageSetting, parser);
9112 } else if (tagName.equals("enabled-components")) {
9113 readEnabledComponentsLP(packageSetting, parser);
9114 } else if (tagName.equals("sigs")) {
9115 packageSetting.signatures.readXml(parser, mPastSignatures);
9116 } else if (tagName.equals("perms")) {
9117 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009118 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009119 packageSetting.permissionsFixed = true;
9120 } else {
9121 reportSettingsProblem(Log.WARN,
9122 "Unknown element under <package>: "
9123 + parser.getName());
9124 XmlUtils.skipCurrentTag(parser);
9125 }
9126 }
9127 } else {
9128 XmlUtils.skipCurrentTag(parser);
9129 }
9130 }
9131
9132 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9133 XmlPullParser parser)
9134 throws IOException, XmlPullParserException {
9135 int outerDepth = parser.getDepth();
9136 int type;
9137 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9138 && (type != XmlPullParser.END_TAG
9139 || parser.getDepth() > outerDepth)) {
9140 if (type == XmlPullParser.END_TAG
9141 || type == XmlPullParser.TEXT) {
9142 continue;
9143 }
9144
9145 String tagName = parser.getName();
9146 if (tagName.equals("item")) {
9147 String name = parser.getAttributeValue(null, "name");
9148 if (name != null) {
9149 packageSetting.disabledComponents.add(name.intern());
9150 } else {
9151 reportSettingsProblem(Log.WARN,
9152 "Error in package manager settings: <disabled-components> has"
9153 + " no name at " + parser.getPositionDescription());
9154 }
9155 } else {
9156 reportSettingsProblem(Log.WARN,
9157 "Unknown element under <disabled-components>: "
9158 + parser.getName());
9159 }
9160 XmlUtils.skipCurrentTag(parser);
9161 }
9162 }
9163
9164 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9165 XmlPullParser parser)
9166 throws IOException, XmlPullParserException {
9167 int outerDepth = parser.getDepth();
9168 int type;
9169 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9170 && (type != XmlPullParser.END_TAG
9171 || parser.getDepth() > outerDepth)) {
9172 if (type == XmlPullParser.END_TAG
9173 || type == XmlPullParser.TEXT) {
9174 continue;
9175 }
9176
9177 String tagName = parser.getName();
9178 if (tagName.equals("item")) {
9179 String name = parser.getAttributeValue(null, "name");
9180 if (name != null) {
9181 packageSetting.enabledComponents.add(name.intern());
9182 } else {
9183 reportSettingsProblem(Log.WARN,
9184 "Error in package manager settings: <enabled-components> has"
9185 + " no name at " + parser.getPositionDescription());
9186 }
9187 } else {
9188 reportSettingsProblem(Log.WARN,
9189 "Unknown element under <enabled-components>: "
9190 + parser.getName());
9191 }
9192 XmlUtils.skipCurrentTag(parser);
9193 }
9194 }
9195
9196 private void readSharedUserLP(XmlPullParser parser)
9197 throws XmlPullParserException, IOException {
9198 String name = null;
9199 String idStr = null;
9200 int pkgFlags = 0;
9201 SharedUserSetting su = null;
9202 try {
9203 name = parser.getAttributeValue(null, "name");
9204 idStr = parser.getAttributeValue(null, "userId");
9205 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9206 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9207 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9208 }
9209 if (name == null) {
9210 reportSettingsProblem(Log.WARN,
9211 "Error in package manager settings: <shared-user> has no name at "
9212 + parser.getPositionDescription());
9213 } else if (userId == 0) {
9214 reportSettingsProblem(Log.WARN,
9215 "Error in package manager settings: shared-user "
9216 + name + " has bad userId " + idStr + " at "
9217 + parser.getPositionDescription());
9218 } else {
9219 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9220 reportSettingsProblem(Log.ERROR,
9221 "Occurred while parsing settings at "
9222 + parser.getPositionDescription());
9223 }
9224 }
9225 } catch (NumberFormatException e) {
9226 reportSettingsProblem(Log.WARN,
9227 "Error in package manager settings: package "
9228 + name + " has bad userId " + idStr + " at "
9229 + parser.getPositionDescription());
9230 };
9231
9232 if (su != null) {
9233 int outerDepth = parser.getDepth();
9234 int type;
9235 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9236 && (type != XmlPullParser.END_TAG
9237 || parser.getDepth() > outerDepth)) {
9238 if (type == XmlPullParser.END_TAG
9239 || type == XmlPullParser.TEXT) {
9240 continue;
9241 }
9242
9243 String tagName = parser.getName();
9244 if (tagName.equals("sigs")) {
9245 su.signatures.readXml(parser, mPastSignatures);
9246 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009247 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009248 } else {
9249 reportSettingsProblem(Log.WARN,
9250 "Unknown element under <shared-user>: "
9251 + parser.getName());
9252 XmlUtils.skipCurrentTag(parser);
9253 }
9254 }
9255
9256 } else {
9257 XmlUtils.skipCurrentTag(parser);
9258 }
9259 }
9260
9261 private void readGrantedPermissionsLP(XmlPullParser parser,
9262 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9263 int outerDepth = parser.getDepth();
9264 int type;
9265 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9266 && (type != XmlPullParser.END_TAG
9267 || parser.getDepth() > outerDepth)) {
9268 if (type == XmlPullParser.END_TAG
9269 || type == XmlPullParser.TEXT) {
9270 continue;
9271 }
9272
9273 String tagName = parser.getName();
9274 if (tagName.equals("item")) {
9275 String name = parser.getAttributeValue(null, "name");
9276 if (name != null) {
9277 outPerms.add(name.intern());
9278 } else {
9279 reportSettingsProblem(Log.WARN,
9280 "Error in package manager settings: <perms> has"
9281 + " no name at " + parser.getPositionDescription());
9282 }
9283 } else {
9284 reportSettingsProblem(Log.WARN,
9285 "Unknown element under <perms>: "
9286 + parser.getName());
9287 }
9288 XmlUtils.skipCurrentTag(parser);
9289 }
9290 }
9291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009292 private void readPreferredActivitiesLP(XmlPullParser parser)
9293 throws XmlPullParserException, IOException {
9294 int outerDepth = parser.getDepth();
9295 int type;
9296 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9297 && (type != XmlPullParser.END_TAG
9298 || parser.getDepth() > outerDepth)) {
9299 if (type == XmlPullParser.END_TAG
9300 || type == XmlPullParser.TEXT) {
9301 continue;
9302 }
9303
9304 String tagName = parser.getName();
9305 if (tagName.equals("item")) {
9306 PreferredActivity pa = new PreferredActivity(parser);
9307 if (pa.mParseError == null) {
9308 mPreferredActivities.addFilter(pa);
9309 } else {
9310 reportSettingsProblem(Log.WARN,
9311 "Error in package manager settings: <preferred-activity> "
9312 + pa.mParseError + " at "
9313 + parser.getPositionDescription());
9314 }
9315 } else {
9316 reportSettingsProblem(Log.WARN,
9317 "Unknown element under <preferred-activities>: "
9318 + parser.getName());
9319 XmlUtils.skipCurrentTag(parser);
9320 }
9321 }
9322 }
9323
9324 // Returns -1 if we could not find an available UserId to assign
9325 private int newUserIdLP(Object obj) {
9326 // Let's be stupidly inefficient for now...
9327 final int N = mUserIds.size();
9328 for (int i=0; i<N; i++) {
9329 if (mUserIds.get(i) == null) {
9330 mUserIds.set(i, obj);
9331 return FIRST_APPLICATION_UID + i;
9332 }
9333 }
9334
9335 // None left?
9336 if (N >= MAX_APPLICATION_UIDS) {
9337 return -1;
9338 }
9339
9340 mUserIds.add(obj);
9341 return FIRST_APPLICATION_UID + N;
9342 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009344 public PackageSetting getDisabledSystemPkg(String name) {
9345 synchronized(mPackages) {
9346 PackageSetting ps = mDisabledSysPackages.get(name);
9347 return ps;
9348 }
9349 }
9350
9351 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009352 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9353 return true;
9354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009355 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9356 if (Config.LOGV) {
9357 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9358 + " componentName = " + componentInfo.name);
9359 Log.v(TAG, "enabledComponents: "
9360 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9361 Log.v(TAG, "disabledComponents: "
9362 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9363 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009364 if (packageSettings == null) {
9365 if (false) {
9366 Log.w(TAG, "WAITING FOR DEBUGGER");
9367 Debug.waitForDebugger();
9368 Log.i(TAG, "We will crash!");
9369 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009370 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009371 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009372 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9373 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9374 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9375 return false;
9376 }
9377 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9378 return true;
9379 }
9380 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9381 return false;
9382 }
9383 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009384 }
9385 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009386
9387 // ------- apps on sdcard specific code -------
9388 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009389 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009390 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009391 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009392 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009393
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009394 private String getEncryptKey() {
9395 try {
9396 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9397 if (sdEncKey == null) {
9398 sdEncKey = SystemKeyStore.getInstance().
9399 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9400 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009401 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009402 return null;
9403 }
9404 }
9405 return sdEncKey;
9406 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009407 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009408 return null;
9409 }
9410 }
9411
Kenny Rootc78a8072010-07-27 15:18:38 -07009412 /* package */ static String getTempContainerId() {
9413 int tmpIdx = 1;
9414 String list[] = PackageHelper.getSecureContainerList();
9415 if (list != null) {
9416 for (final String name : list) {
9417 // Ignore null and non-temporary container entries
9418 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9419 continue;
9420 }
9421
9422 String subStr = name.substring(mTempContainerPrefix.length());
9423 try {
9424 int cid = Integer.parseInt(subStr);
9425 if (cid >= tmpIdx) {
9426 tmpIdx = cid + 1;
9427 }
9428 } catch (NumberFormatException e) {
9429 }
9430 }
9431 }
9432 return mTempContainerPrefix + tmpIdx;
9433 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009434
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009435 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009436 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009437 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009438 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9439 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9440 throw new SecurityException("Media status can only be updated by the system");
9441 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009442 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009443 Log.i(TAG, "Updating external media status from " +
9444 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9445 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009446 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9447 mediaStatus+", mMediaMounted=" + mMediaMounted);
9448 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009449 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9450 reportStatus ? 1 : 0, -1);
9451 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009452 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009453 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009454 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009455 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009456 // Queue up an async operation since the package installation may take a little while.
9457 mHandler.post(new Runnable() {
9458 public void run() {
9459 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009460 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009461 }
9462 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009463 }
9464
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009465 /*
9466 * Collect information of applications on external media, map them
9467 * against existing containers and update information based on current
9468 * mount status. Please note that we always have to report status
9469 * if reportStatus has been set to true especially when unloading packages.
9470 */
9471 private void updateExternalMediaStatusInner(boolean mediaStatus,
9472 boolean reportStatus) {
9473 // Collection of uids
9474 int uidArr[] = null;
9475 // Collection of stale containers
9476 HashSet<String> removeCids = new HashSet<String>();
9477 // Collection of packages on external media with valid containers.
9478 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9479 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009480 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009481 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009482 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009483 } else {
9484 // Process list of secure containers and categorize them
9485 // as active or stale based on their package internal state.
9486 int uidList[] = new int[list.length];
9487 int num = 0;
9488 synchronized (mPackages) {
9489 for (String cid : list) {
9490 SdInstallArgs args = new SdInstallArgs(cid);
9491 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009492 String pkgName = args.getPackageName();
9493 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009494 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9495 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009496 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009497 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009498 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9499 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009500 // The package status is changed only if the code path
9501 // matches between settings and the container id.
9502 if (ps != null && ps.codePathString != null &&
9503 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009504 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9505 " corresponds to pkg : " + pkgName +
9506 " at code path: " + ps.codePathString);
9507 // We do have a valid package installed on sdcard
9508 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009509 int uid = ps.userId;
9510 if (uid != -1) {
9511 uidList[num++] = uid;
9512 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009513 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009514 // Stale container on sdcard. Just delete
9515 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9516 removeCids.add(cid);
9517 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009518 }
9519 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009520
9521 if (num > 0) {
9522 // Sort uid list
9523 Arrays.sort(uidList, 0, num);
9524 // Throw away duplicates
9525 uidArr = new int[num];
9526 uidArr[0] = uidList[0];
9527 int di = 0;
9528 for (int i = 1; i < num; i++) {
9529 if (uidList[i-1] != uidList[i]) {
9530 uidArr[di++] = uidList[i];
9531 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009532 }
9533 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009534 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009535 // Process packages with valid entries.
9536 if (mediaStatus) {
9537 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009538 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009539 startCleaningPackages();
9540 } else {
9541 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009542 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009543 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009544 }
9545
9546 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009547 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009548 int size = pkgList.size();
9549 if (size > 0) {
9550 // Send broadcasts here
9551 Bundle extras = new Bundle();
9552 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9553 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009554 if (uidArr != null) {
9555 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9556 }
9557 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9558 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009559 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009560 }
9561 }
9562
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009563 /*
9564 * Look at potentially valid container ids from processCids
9565 * If package information doesn't match the one on record
9566 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009567 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009568 */
9569 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009570 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009571 ArrayList<String> pkgList = new ArrayList<String>();
9572 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009573 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009574 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009575 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009576 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9577 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009578 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009579 try {
9580 // Make sure there are no container errors first.
9581 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9582 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009583 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009584 " when installing from sdcard");
9585 continue;
9586 }
9587 // Check code path here.
9588 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009589 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009590 " does not match one in settings " + codePath);
9591 continue;
9592 }
9593 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009594 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009595 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009596 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009597 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9598 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009599 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009600 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009601 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009602 retCode = PackageManager.INSTALL_SUCCEEDED;
9603 pkgList.add(pkg.packageName);
9604 // Post process args
9605 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9606 }
9607 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009608 Slog.i(TAG, "Failed to install pkg from " +
9609 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009610 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009611 }
9612
9613 } finally {
9614 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9615 // Don't destroy container here. Wait till gc clears things up.
9616 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009617 }
9618 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009619 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009620 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009621 // If the platform SDK has changed since the last time we booted,
9622 // we need to re-grant app permission to catch any new ones that
9623 // appear. This is really a hack, and means that apps can in some
9624 // cases get permissions that the user didn't initially explicitly
9625 // allow... it would be nice to have some better way to handle
9626 // this situation.
9627 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9628 != mSdkVersion;
9629 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9630 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9631 + "; regranting permissions for external storage");
9632 mSettings.mExternalSdkPlatform = mSdkVersion;
9633
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009634 // Make sure group IDs have been assigned, and any permission
9635 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009636 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009637 // Persist settings
9638 mSettings.writeLP();
9639 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009640 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009641 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009642 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009643 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009644 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009645 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009646 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009647 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009648 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009649 if (removeCids != null) {
9650 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009651 if (cid.startsWith(mTempContainerPrefix)) {
9652 Log.i(TAG, "Destroying stale temporary container " + cid);
9653 PackageHelper.destroySdDir(cid);
9654 } else {
9655 Log.w(TAG, "Container " + cid + " is stale");
9656 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009657 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009658 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009659 }
9660
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009661 /*
9662 * Utility method to unload a list of specified containers
9663 */
9664 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9665 // Just unmount all valid containers.
9666 for (SdInstallArgs arg : cidArgs) {
9667 synchronized (mInstallLock) {
9668 arg.doPostDeleteLI(false);
9669 }
9670 }
9671 }
9672
9673 /*
9674 * Unload packages mounted on external media. This involves deleting
9675 * package data from internal structures, sending broadcasts about
9676 * diabled packages, gc'ing to free up references, unmounting all
9677 * secure containers corresponding to packages on external media, and
9678 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9679 * Please note that we always have to post this message if status has
9680 * been requested no matter what.
9681 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009682 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009683 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009684 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009685 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009686 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009687 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009688 for (SdInstallArgs args : keys) {
9689 String cid = args.cid;
9690 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009691 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009692 // Delete package internally
9693 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9694 synchronized (mInstallLock) {
9695 boolean res = deletePackageLI(pkgName, false,
9696 PackageManager.DONT_DELETE_DATA, outInfo);
9697 if (res) {
9698 pkgList.add(pkgName);
9699 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009700 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009701 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009702 }
9703 }
9704 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009705 // We have to absolutely send UPDATED_MEDIA_STATUS only
9706 // after confirming that all the receivers processed the ordered
9707 // broadcast when packages get disabled, force a gc to clean things up.
9708 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009709 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009710 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9711 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9712 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009713 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9714 reportStatus ? 1 : 0, 1, keys);
9715 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009716 }
9717 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009718 } else {
9719 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9720 reportStatus ? 1 : 0, -1, keys);
9721 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009722 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009723 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009724
9725 public void movePackage(final String packageName,
9726 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009727 mContext.enforceCallingOrSelfPermission(
9728 android.Manifest.permission.MOVE_PACKAGE, null);
9729 int returnCode = PackageManager.MOVE_SUCCEEDED;
9730 int currFlags = 0;
9731 int newFlags = 0;
9732 synchronized (mPackages) {
9733 PackageParser.Package pkg = mPackages.get(packageName);
9734 if (pkg == null) {
9735 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009736 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009737 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009738 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009739 Slog.w(TAG, "Cannot move system application");
9740 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009741 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009742 Slog.w(TAG, "Cannot move forward locked app.");
9743 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009744 } else if (pkg.mOperationPending) {
9745 Slog.w(TAG, "Attempt to move package which has pending operations");
9746 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009747 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009748 // Find install location first
9749 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9750 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9751 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009752 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009753 } else {
9754 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9755 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009756 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9757 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009758 if (newFlags == currFlags) {
9759 Slog.w(TAG, "No move required. Trying to move to same location");
9760 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9761 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009762 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009763 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9764 pkg.mOperationPending = true;
9765 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009766 }
9767 }
9768 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009769 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009770 } else {
9771 Message msg = mHandler.obtainMessage(INIT_COPY);
9772 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009773 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9774 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9775 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009776 msg.obj = mp;
9777 mHandler.sendMessage(msg);
9778 }
9779 }
9780 }
9781
9782 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9783 // Queue up an async operation since the package deletion may take a little while.
9784 mHandler.post(new Runnable() {
9785 public void run() {
9786 mHandler.removeCallbacks(this);
9787 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009788 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9789 int uidArr[] = null;
9790 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009791 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009792 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009793 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009794 Slog.w(TAG, " Package " + mp.packageName +
9795 " doesn't exist. Aborting move");
9796 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9797 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9798 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9799 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9800 " Aborting move and returning error");
9801 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9802 } else {
9803 uidArr = new int[] { pkg.applicationInfo.uid };
9804 pkgList = new ArrayList<String>();
9805 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009806 }
9807 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009808 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9809 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009810 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009811 // Update package code and resource paths
9812 synchronized (mInstallLock) {
9813 synchronized (mPackages) {
9814 PackageParser.Package pkg = mPackages.get(mp.packageName);
9815 // Recheck for package again.
9816 if (pkg == null ) {
9817 Slog.w(TAG, " Package " + mp.packageName +
9818 " doesn't exist. Aborting move");
9819 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9820 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9821 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9822 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9823 " Aborting move and returning error");
9824 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9825 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009826 final String oldCodePath = pkg.mPath;
9827 final String newCodePath = mp.targetArgs.getCodePath();
9828 final String newResPath = mp.targetArgs.getResourcePath();
9829 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009830 pkg.mPath = newCodePath;
9831 // Move dex files around
9832 if (moveDexFilesLI(pkg)
9833 != PackageManager.INSTALL_SUCCEEDED) {
9834 // Moving of dex files failed. Set
9835 // error code and abort move.
9836 pkg.mPath = pkg.mScanPath;
9837 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9838 } else {
9839 pkg.mScanPath = newCodePath;
9840 pkg.applicationInfo.sourceDir = newCodePath;
9841 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009842 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009843 PackageSetting ps = (PackageSetting) pkg.mExtras;
9844 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9845 ps.codePathString = ps.codePath.getPath();
9846 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9847 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009848 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009849 // Set the application info flag correctly.
9850 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9851 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9852 } else {
9853 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9854 }
9855 ps.setFlags(pkg.applicationInfo.flags);
9856 mAppDirs.remove(oldCodePath);
9857 mAppDirs.put(newCodePath, pkg);
9858 // Persist settings
9859 mSettings.writeLP();
9860 }
9861 }
9862 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009863 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009864 // Send resources available broadcast
9865 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009866 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009867 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009868 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009869 // Clean up failed installation
9870 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009871 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009872 }
9873 } else {
9874 // Force a gc to clear things up.
9875 Runtime.getRuntime().gc();
9876 // Delete older code
9877 synchronized (mInstallLock) {
9878 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009879 }
9880 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009881
9882 // Allow more operations on this file if we didn't fail because
9883 // an operation was already pending for this package.
9884 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9885 synchronized (mPackages) {
9886 PackageParser.Package pkg = mPackages.get(mp.packageName);
9887 if (pkg != null) {
9888 pkg.mOperationPending = false;
9889 }
9890 }
9891 }
9892
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009893 IPackageMoveObserver observer = mp.observer;
9894 if (observer != null) {
9895 try {
9896 observer.packageMoved(mp.packageName, returnCode);
9897 } catch (RemoteException e) {
9898 Log.i(TAG, "Observer no longer exists.");
9899 }
9900 }
9901 }
9902 });
9903 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009904
9905 public boolean setInstallLocation(int loc) {
9906 mContext.enforceCallingOrSelfPermission(
9907 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9908 if (getInstallLocation() == loc) {
9909 return true;
9910 }
9911 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9912 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9913 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9914 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9915 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9916 return true;
9917 }
9918 return false;
9919 }
9920
9921 public int getInstallLocation() {
9922 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9923 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9924 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009925}