blob: 1279cf72664c3290eec6ef2770237e41930c2a85 [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:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002025 if (ai != null) {
2026 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2027 } else {
2028 Log.v(TAG, " null");
2029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
2031 if (ai != null) {
2032 for (int j=0; j<N; j++) {
2033 ResolveInfo ri = query.get(j);
2034 if (!ri.activityInfo.applicationInfo.packageName
2035 .equals(ai.applicationInfo.packageName)) {
2036 continue;
2037 }
2038 if (!ri.activityInfo.name.equals(ai.name)) {
2039 continue;
2040 }
2041
2042 // Okay we found a previously set preferred app.
2043 // If the result set is different from when this
2044 // was created, we need to clear it and re-ask the
2045 // user their preference.
2046 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002047 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 + intent + " type " + resolvedType);
2049 mSettings.mPreferredActivities.removeFilter(pa);
2050 return null;
2051 }
2052
2053 // Yay!
2054 return ri;
2055 }
2056 }
2057 }
2058 }
2059 }
2060 return null;
2061 }
2062
2063 public List<ResolveInfo> queryIntentActivities(Intent intent,
2064 String resolvedType, int flags) {
2065 ComponentName comp = intent.getComponent();
2066 if (comp != null) {
2067 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2068 ActivityInfo ai = getActivityInfo(comp, flags);
2069 if (ai != null) {
2070 ResolveInfo ri = new ResolveInfo();
2071 ri.activityInfo = ai;
2072 list.add(ri);
2073 }
2074 return list;
2075 }
2076
2077 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002078 String pkgName = intent.getPackage();
2079 if (pkgName == null) {
2080 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2081 resolvedType, flags);
2082 }
2083 PackageParser.Package pkg = mPackages.get(pkgName);
2084 if (pkg != null) {
2085 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2086 resolvedType, flags, pkg.activities);
2087 }
2088 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090 }
2091
2092 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2093 Intent[] specifics, String[] specificTypes, Intent intent,
2094 String resolvedType, int flags) {
2095 final String resultsAction = intent.getAction();
2096
2097 List<ResolveInfo> results = queryIntentActivities(
2098 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2099 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2100
2101 int specificsPos = 0;
2102 int N;
2103
2104 // todo: note that the algorithm used here is O(N^2). This
2105 // isn't a problem in our current environment, but if we start running
2106 // into situations where we have more than 5 or 10 matches then this
2107 // should probably be changed to something smarter...
2108
2109 // First we go through and resolve each of the specific items
2110 // that were supplied, taking care of removing any corresponding
2111 // duplicate items in the generic resolve list.
2112 if (specifics != null) {
2113 for (int i=0; i<specifics.length; i++) {
2114 final Intent sintent = specifics[i];
2115 if (sintent == null) {
2116 continue;
2117 }
2118
2119 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2120 String action = sintent.getAction();
2121 if (resultsAction != null && resultsAction.equals(action)) {
2122 // If this action was explicitly requested, then don't
2123 // remove things that have it.
2124 action = null;
2125 }
2126 ComponentName comp = sintent.getComponent();
2127 ResolveInfo ri = null;
2128 ActivityInfo ai = null;
2129 if (comp == null) {
2130 ri = resolveIntent(
2131 sintent,
2132 specificTypes != null ? specificTypes[i] : null,
2133 flags);
2134 if (ri == null) {
2135 continue;
2136 }
2137 if (ri == mResolveInfo) {
2138 // ACK! Must do something better with this.
2139 }
2140 ai = ri.activityInfo;
2141 comp = new ComponentName(ai.applicationInfo.packageName,
2142 ai.name);
2143 } else {
2144 ai = getActivityInfo(comp, flags);
2145 if (ai == null) {
2146 continue;
2147 }
2148 }
2149
2150 // Look for any generic query activities that are duplicates
2151 // of this specific one, and remove them from the results.
2152 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2153 N = results.size();
2154 int j;
2155 for (j=specificsPos; j<N; j++) {
2156 ResolveInfo sri = results.get(j);
2157 if ((sri.activityInfo.name.equals(comp.getClassName())
2158 && sri.activityInfo.applicationInfo.packageName.equals(
2159 comp.getPackageName()))
2160 || (action != null && sri.filter.matchAction(action))) {
2161 results.remove(j);
2162 if (Config.LOGV) Log.v(
2163 TAG, "Removing duplicate item from " + j
2164 + " due to specific " + specificsPos);
2165 if (ri == null) {
2166 ri = sri;
2167 }
2168 j--;
2169 N--;
2170 }
2171 }
2172
2173 // Add this specific item to its proper place.
2174 if (ri == null) {
2175 ri = new ResolveInfo();
2176 ri.activityInfo = ai;
2177 }
2178 results.add(specificsPos, ri);
2179 ri.specificIndex = i;
2180 specificsPos++;
2181 }
2182 }
2183
2184 // Now we go through the remaining generic results and remove any
2185 // duplicate actions that are found here.
2186 N = results.size();
2187 for (int i=specificsPos; i<N-1; i++) {
2188 final ResolveInfo rii = results.get(i);
2189 if (rii.filter == null) {
2190 continue;
2191 }
2192
2193 // Iterate over all of the actions of this result's intent
2194 // filter... typically this should be just one.
2195 final Iterator<String> it = rii.filter.actionsIterator();
2196 if (it == null) {
2197 continue;
2198 }
2199 while (it.hasNext()) {
2200 final String action = it.next();
2201 if (resultsAction != null && resultsAction.equals(action)) {
2202 // If this action was explicitly requested, then don't
2203 // remove things that have it.
2204 continue;
2205 }
2206 for (int j=i+1; j<N; j++) {
2207 final ResolveInfo rij = results.get(j);
2208 if (rij.filter != null && rij.filter.hasAction(action)) {
2209 results.remove(j);
2210 if (Config.LOGV) Log.v(
2211 TAG, "Removing duplicate item from " + j
2212 + " due to action " + action + " at " + i);
2213 j--;
2214 N--;
2215 }
2216 }
2217 }
2218
2219 // If the caller didn't request filter information, drop it now
2220 // so we don't have to marshall/unmarshall it.
2221 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2222 rii.filter = null;
2223 }
2224 }
2225
2226 // Filter out the caller activity if so requested.
2227 if (caller != null) {
2228 N = results.size();
2229 for (int i=0; i<N; i++) {
2230 ActivityInfo ainfo = results.get(i).activityInfo;
2231 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2232 && caller.getClassName().equals(ainfo.name)) {
2233 results.remove(i);
2234 break;
2235 }
2236 }
2237 }
2238
2239 // If the caller didn't request filter information,
2240 // drop them now so we don't have to
2241 // marshall/unmarshall it.
2242 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2243 N = results.size();
2244 for (int i=0; i<N; i++) {
2245 results.get(i).filter = null;
2246 }
2247 }
2248
2249 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2250 return results;
2251 }
2252
2253 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2254 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002255 ComponentName comp = intent.getComponent();
2256 if (comp != null) {
2257 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2258 ActivityInfo ai = getReceiverInfo(comp, flags);
2259 if (ai != null) {
2260 ResolveInfo ri = new ResolveInfo();
2261 ri.activityInfo = ai;
2262 list.add(ri);
2263 }
2264 return list;
2265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002268 String pkgName = intent.getPackage();
2269 if (pkgName == null) {
2270 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2271 resolvedType, flags);
2272 }
2273 PackageParser.Package pkg = mPackages.get(pkgName);
2274 if (pkg != null) {
2275 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2276 resolvedType, flags, pkg.receivers);
2277 }
2278 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 }
2280 }
2281
2282 public ResolveInfo resolveService(Intent intent, String resolvedType,
2283 int flags) {
2284 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2285 flags);
2286 if (query != null) {
2287 if (query.size() >= 1) {
2288 // If there is more than one service with the same priority,
2289 // just arbitrarily pick the first one.
2290 return query.get(0);
2291 }
2292 }
2293 return null;
2294 }
2295
2296 public List<ResolveInfo> queryIntentServices(Intent intent,
2297 String resolvedType, int flags) {
2298 ComponentName comp = intent.getComponent();
2299 if (comp != null) {
2300 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2301 ServiceInfo si = getServiceInfo(comp, flags);
2302 if (si != null) {
2303 ResolveInfo ri = new ResolveInfo();
2304 ri.serviceInfo = si;
2305 list.add(ri);
2306 }
2307 return list;
2308 }
2309
2310 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002311 String pkgName = intent.getPackage();
2312 if (pkgName == null) {
2313 return (List<ResolveInfo>)mServices.queryIntent(intent,
2314 resolvedType, flags);
2315 }
2316 PackageParser.Package pkg = mPackages.get(pkgName);
2317 if (pkg != null) {
2318 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2319 resolvedType, flags, pkg.services);
2320 }
2321 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
2323 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 public List<PackageInfo> getInstalledPackages(int flags) {
2326 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2327
2328 synchronized (mPackages) {
2329 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2330 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2331 while (i.hasNext()) {
2332 final PackageSetting ps = i.next();
2333 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2334 if(psPkg != null) {
2335 finalList.add(psPkg);
2336 }
2337 }
2338 }
2339 else {
2340 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2341 while (i.hasNext()) {
2342 final PackageParser.Package p = i.next();
2343 if (p.applicationInfo != null) {
2344 PackageInfo pi = generatePackageInfo(p, flags);
2345 if(pi != null) {
2346 finalList.add(pi);
2347 }
2348 }
2349 }
2350 }
2351 }
2352 return finalList;
2353 }
2354
2355 public List<ApplicationInfo> getInstalledApplications(int flags) {
2356 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2357 synchronized(mPackages) {
2358 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2359 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2360 while (i.hasNext()) {
2361 final PackageSetting ps = i.next();
2362 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2363 if(ai != null) {
2364 finalList.add(ai);
2365 }
2366 }
2367 }
2368 else {
2369 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2370 while (i.hasNext()) {
2371 final PackageParser.Package p = i.next();
2372 if (p.applicationInfo != null) {
2373 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2374 if(ai != null) {
2375 finalList.add(ai);
2376 }
2377 }
2378 }
2379 }
2380 }
2381 return finalList;
2382 }
2383
2384 public List<ApplicationInfo> getPersistentApplications(int flags) {
2385 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2386
2387 synchronized (mPackages) {
2388 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2389 while (i.hasNext()) {
2390 PackageParser.Package p = i.next();
2391 if (p.applicationInfo != null
2392 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002393 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002394 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 }
2396 }
2397 }
2398
2399 return finalList;
2400 }
2401
2402 public ProviderInfo resolveContentProvider(String name, int flags) {
2403 synchronized (mPackages) {
2404 final PackageParser.Provider provider = mProviders.get(name);
2405 return provider != null
2406 && mSettings.isEnabledLP(provider.info, flags)
2407 && (!mSafeMode || (provider.info.applicationInfo.flags
2408 &ApplicationInfo.FLAG_SYSTEM) != 0)
2409 ? PackageParser.generateProviderInfo(provider, flags)
2410 : null;
2411 }
2412 }
2413
Fred Quintana718d8a22009-04-29 17:53:20 -07002414 /**
2415 * @deprecated
2416 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 public void querySyncProviders(List outNames, List outInfo) {
2418 synchronized (mPackages) {
2419 Iterator<Map.Entry<String, PackageParser.Provider>> i
2420 = mProviders.entrySet().iterator();
2421
2422 while (i.hasNext()) {
2423 Map.Entry<String, PackageParser.Provider> entry = i.next();
2424 PackageParser.Provider p = entry.getValue();
2425
2426 if (p.syncable
2427 && (!mSafeMode || (p.info.applicationInfo.flags
2428 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2429 outNames.add(entry.getKey());
2430 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2431 }
2432 }
2433 }
2434 }
2435
2436 public List<ProviderInfo> queryContentProviders(String processName,
2437 int uid, int flags) {
2438 ArrayList<ProviderInfo> finalList = null;
2439
2440 synchronized (mPackages) {
2441 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2442 while (i.hasNext()) {
2443 PackageParser.Provider p = i.next();
2444 if (p.info.authority != null
2445 && (processName == null ||
2446 (p.info.processName.equals(processName)
2447 && p.info.applicationInfo.uid == uid))
2448 && mSettings.isEnabledLP(p.info, flags)
2449 && (!mSafeMode || (p.info.applicationInfo.flags
2450 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2451 if (finalList == null) {
2452 finalList = new ArrayList<ProviderInfo>(3);
2453 }
2454 finalList.add(PackageParser.generateProviderInfo(p,
2455 flags));
2456 }
2457 }
2458 }
2459
2460 if (finalList != null) {
2461 Collections.sort(finalList, mProviderInitOrderSorter);
2462 }
2463
2464 return finalList;
2465 }
2466
2467 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2468 int flags) {
2469 synchronized (mPackages) {
2470 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2471 return PackageParser.generateInstrumentationInfo(i, flags);
2472 }
2473 }
2474
2475 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2476 int flags) {
2477 ArrayList<InstrumentationInfo> finalList =
2478 new ArrayList<InstrumentationInfo>();
2479
2480 synchronized (mPackages) {
2481 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2482 while (i.hasNext()) {
2483 PackageParser.Instrumentation p = i.next();
2484 if (targetPackage == null
2485 || targetPackage.equals(p.info.targetPackage)) {
2486 finalList.add(PackageParser.generateInstrumentationInfo(p,
2487 flags));
2488 }
2489 }
2490 }
2491
2492 return finalList;
2493 }
2494
2495 private void scanDirLI(File dir, int flags, int scanMode) {
2496 Log.d(TAG, "Scanning app dir " + dir);
2497
2498 String[] files = dir.list();
2499
2500 int i;
2501 for (i=0; i<files.length; i++) {
2502 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002503 if (!isPackageFilename(files[i])) {
2504 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002505 continue;
2506 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002507 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002509 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002510 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2511 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002512 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002513 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002514 file.delete();
2515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517 }
2518
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002519 private static File getSettingsProblemFile() {
2520 File dataDir = Environment.getDataDirectory();
2521 File systemDir = new File(dataDir, "system");
2522 File fname = new File(systemDir, "uiderrors.txt");
2523 return fname;
2524 }
2525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 private static void reportSettingsProblem(int priority, String msg) {
2527 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002528 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 FileOutputStream out = new FileOutputStream(fname, true);
2530 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002531 SimpleDateFormat formatter = new SimpleDateFormat();
2532 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2533 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 pw.close();
2535 FileUtils.setPermissions(
2536 fname.toString(),
2537 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2538 -1, -1);
2539 } catch (java.io.IOException e) {
2540 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002541 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 }
2543
2544 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2545 PackageParser.Package pkg, File srcFile, int parseFlags) {
2546 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002547 if (ps != null
2548 && ps.codePath.equals(srcFile)
2549 && ps.getTimeStamp() == srcFile.lastModified()) {
2550 if (ps.signatures.mSignatures != null
2551 && ps.signatures.mSignatures.length != 0) {
2552 // Optimization: reuse the existing cached certificates
2553 // if the package appears to be unchanged.
2554 pkg.mSignatures = ps.signatures.mSignatures;
2555 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 }
Jeff Browne7600722010-04-07 18:28:23 -07002557
2558 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002559 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002560 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2561 }
2562
2563 if (!pp.collectCertificates(pkg, parseFlags)) {
2564 mLastScanError = pp.getParseError();
2565 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 }
2567 }
2568 return true;
2569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 /*
2572 * Scan a package and return the newly parsed package.
2573 * Returns null in case of errors and the error code is stored in mLastScanError
2574 */
2575 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002576 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002578 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002580 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002583 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 if (pkg == null) {
2585 mLastScanError = pp.getParseError();
2586 return null;
2587 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002588 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 PackageSetting updatedPkg;
2590 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 // Look to see if we already know about this package.
2592 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002593 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002594 // This package has been renamed to its original name. Let's
2595 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002596 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002597 }
2598 // If there was no original package, see one for the real package name.
2599 if (ps == null) {
2600 ps = mSettings.peekPackageLP(pkg.packageName);
2601 }
2602 // Check to see if this package could be hiding/updating a system
2603 // package. Must look for it either under the original or real
2604 // package name depending on our state.
2605 updatedPkg = mSettings.mDisabledSysPackages.get(
2606 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002608 // First check if this is a system package that may involve an update
2609 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002610 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002611 // The path has changed from what was last scanned... check the
2612 // version of the new path against what we have stored to determine
2613 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002614 if (pkg.mVersionCode < ps.versionCode) {
2615 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 // Ignore entry. Skip it.
2617 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2618 + "ignored: updated version " + ps.versionCode
2619 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002620 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2621 return null;
2622 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002623 // The current app on the system partion is better than
2624 // what we have updated to on the data partition; switch
2625 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002626 // At this point, its safely assumed that package installation for
2627 // apps in system partition will go through. If not there won't be a working
2628 // version of the app
2629 synchronized (mPackages) {
2630 // Just remove the loaded entries from package lists.
2631 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002632 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002633 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002634 + "reverting from " + ps.codePathString
2635 + ": new version " + pkg.mVersionCode
2636 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002637 InstallArgs args = new FileInstallArgs(ps.codePathString,
2638 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002639 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002640 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
2643 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002644 if (updatedPkg != null) {
2645 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2646 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2647 }
2648 // Verify certificates against what was last scanned
2649 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002650 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002651 return null;
2652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 // The apk is forward locked (not public) if its code and resources
2654 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002655 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002657 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002658 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002659
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002660 String codePath = null;
2661 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002662 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2663 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002664 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002665 } else {
2666 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002667 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002668 }
2669 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002670 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002671 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002672 codePath = pkg.mScanPath;
2673 // Set application objects path explicitly.
2674 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002676 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 }
2678
Kenny Root85387d72010-08-26 10:13:11 -07002679 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2680 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002681 pkg.mPath = pkg.mScanPath = destCodePath;
2682 pkg.applicationInfo.sourceDir = destCodePath;
2683 pkg.applicationInfo.publicSourceDir = destResPath;
2684 }
2685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 private static String fixProcessName(String defProcessName,
2687 String processName, int uid) {
2688 if (processName == null) {
2689 return defProcessName;
2690 }
2691 return processName;
2692 }
2693
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002694 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002695 PackageParser.Package pkg) {
2696 if (pkgSetting.signatures.mSignatures != null) {
2697 // Already existing package. Make sure signatures match
2698 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2699 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002700 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002701 + " signatures do not match the previously installed version; ignoring!");
2702 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 return false;
2704 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002705 }
2706 // Check for shared user signatures
2707 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2708 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2709 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2710 Slog.e(TAG, "Package " + pkg.packageName
2711 + " has no signatures that match those in shared user "
2712 + pkgSetting.sharedUser.name + "; ignoring!");
2713 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2714 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717 return true;
2718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002719
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002720 public boolean performDexOpt(String packageName) {
2721 if (!mNoDexOpt) {
2722 return false;
2723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002724
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002725 PackageParser.Package p;
2726 synchronized (mPackages) {
2727 p = mPackages.get(packageName);
2728 if (p == null || p.mDidDexOpt) {
2729 return false;
2730 }
2731 }
2732 synchronized (mInstallLock) {
2733 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2734 }
2735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 static final int DEX_OPT_SKIPPED = 0;
2738 static final int DEX_OPT_PERFORMED = 1;
2739 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002740
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002741 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2742 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002743 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002744 String path = pkg.mScanPath;
2745 int ret = 0;
2746 try {
2747 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002748 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002749 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002750 pkg.mDidDexOpt = true;
2751 performed = true;
2752 }
2753 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002754 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002755 ret = -1;
2756 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002757 Slog.w(TAG, "IOException reading apk: " + path, e);
2758 ret = -1;
2759 } catch (dalvik.system.StaleDexCacheError e) {
2760 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2761 ret = -1;
2762 } catch (Exception e) {
2763 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002764 ret = -1;
2765 }
2766 if (ret < 0) {
2767 //error from installer
2768 return DEX_OPT_FAILED;
2769 }
2770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002771
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002772 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2773 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002774
2775 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2776 return Environment.isEncryptedFilesystemEnabled() &&
2777 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2778 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002779
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002780 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2781 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002782 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002783 + " to " + newPkg.packageName
2784 + ": old package not in system partition");
2785 return false;
2786 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002787 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002788 + " to " + newPkg.packageName
2789 + ": old package still exists");
2790 return false;
2791 }
2792 return true;
2793 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002794
2795 private File getDataPathForPackage(PackageParser.Package pkg) {
2796 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2797 File dataPath;
2798 if (useEncryptedFSDir) {
2799 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2800 } else {
2801 dataPath = new File(mAppDataDir, pkg.packageName);
2802 }
2803 return dataPath;
2804 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002805
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002806 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2807 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002808 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002809 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2810 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002811 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002812 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002813 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2814 return null;
2815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 mScanningPath = scanFile;
2817 if (pkg == null) {
2818 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2819 return null;
2820 }
2821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2823 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2824 }
2825
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002826 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 synchronized (mPackages) {
2828 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002829 Slog.w(TAG, "*************************************************");
2830 Slog.w(TAG, "Core android package being redefined. Skipping.");
2831 Slog.w(TAG, " file=" + mScanningPath);
2832 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2834 return null;
2835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 // Set up information for our fall-back user intent resolution
2838 // activity.
2839 mPlatformPackage = pkg;
2840 pkg.mVersionCode = mSdkVersion;
2841 mAndroidApplication = pkg.applicationInfo;
2842 mResolveActivity.applicationInfo = mAndroidApplication;
2843 mResolveActivity.name = ResolverActivity.class.getName();
2844 mResolveActivity.packageName = mAndroidApplication.packageName;
2845 mResolveActivity.processName = mAndroidApplication.processName;
2846 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2847 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2848 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2849 mResolveActivity.exported = true;
2850 mResolveActivity.enabled = true;
2851 mResolveInfo.activityInfo = mResolveActivity;
2852 mResolveInfo.priority = 0;
2853 mResolveInfo.preferredOrder = 0;
2854 mResolveInfo.match = 0;
2855 mResolveComponentName = new ComponentName(
2856 mAndroidApplication.packageName, mResolveActivity.name);
2857 }
2858 }
2859
2860 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002861 TAG, "Scanning package " + pkg.packageName);
2862 if (mPackages.containsKey(pkg.packageName)
2863 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002864 Slog.w(TAG, "*************************************************");
2865 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002867 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2869 return null;
2870 }
2871
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002872 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002873 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2874 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 SharedUserSetting suid = null;
2877 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002878
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002879 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2880 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002881 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002882 pkg.mRealPackage = null;
2883 pkg.mAdoptPermissions = null;
2884 }
2885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 synchronized (mPackages) {
2887 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002888 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2889 if (mTmpSharedLibraries == null ||
2890 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2891 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2892 }
2893 int num = 0;
2894 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2895 for (int i=0; i<N; i++) {
2896 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002898 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002900 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2902 return null;
2903 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002904 mTmpSharedLibraries[num] = file;
2905 num++;
2906 }
2907 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2908 for (int i=0; i<N; i++) {
2909 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2910 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002911 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002912 + " desires unavailable shared library "
2913 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2914 } else {
2915 mTmpSharedLibraries[num] = file;
2916 num++;
2917 }
2918 }
2919 if (num > 0) {
2920 pkg.usesLibraryFiles = new String[num];
2921 System.arraycopy(mTmpSharedLibraries, 0,
2922 pkg.usesLibraryFiles, 0, num);
2923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002924
Dianne Hackborn49237342009-08-27 20:08:01 -07002925 if (pkg.reqFeatures != null) {
2926 N = pkg.reqFeatures.size();
2927 for (int i=0; i<N; i++) {
2928 FeatureInfo fi = pkg.reqFeatures.get(i);
2929 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2930 // Don't care.
2931 continue;
2932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002933
Dianne Hackborn49237342009-08-27 20:08:01 -07002934 if (fi.name != null) {
2935 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002936 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002937 + " requires unavailable feature "
2938 + fi.name + "; failing!");
2939 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2940 return null;
2941 }
2942 }
2943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 }
2945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 if (pkg.mSharedUserId != null) {
2948 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2949 pkg.applicationInfo.flags, true);
2950 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002951 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 + " for shared user failed");
2953 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2954 return null;
2955 }
2956 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2957 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2958 + suid.userId + "): packages=" + suid.packages);
2959 }
2960 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002961
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002962 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002963 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002964 Log.w(TAG, "WAITING FOR DEBUGGER");
2965 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002966 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2967 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002968 }
2969 }
2970
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002971 // Check if we are renaming from an original package name.
2972 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002974 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 // This package may need to be renamed to a previously
2976 // installed name. Let's check on that...
2977 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002978 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002979 // This package had originally been installed as the
2980 // original name, and we have already taken care of
2981 // transitioning to the new one. Just update the new
2982 // one to continue using the old name.
2983 realName = pkg.mRealPackage;
2984 if (!pkg.packageName.equals(renamed)) {
2985 // Callers into this function may have already taken
2986 // care of renaming the package; only do it here if
2987 // it is not already done.
2988 pkg.setPackageName(renamed);
2989 }
2990
Dianne Hackbornc1552392010-03-03 16:19:01 -08002991 } else {
2992 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2993 if ((origPackage=mSettings.peekPackageLP(
2994 pkg.mOriginalPackages.get(i))) != null) {
2995 // We do have the package already installed under its
2996 // original name... should we use it?
2997 if (!verifyPackageUpdate(origPackage, pkg)) {
2998 // New package is not compatible with original.
2999 origPackage = null;
3000 continue;
3001 } else if (origPackage.sharedUser != null) {
3002 // Make sure uid is compatible between packages.
3003 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003004 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003005 + " to " + pkg.packageName + ": old uid "
3006 + origPackage.sharedUser.name
3007 + " differs from " + pkg.mSharedUserId);
3008 origPackage = null;
3009 continue;
3010 }
3011 } else {
3012 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3013 + pkg.packageName + " to old name " + origPackage.name);
3014 }
3015 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003016 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003017 }
3018 }
3019 }
3020
3021 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003022 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003023 + " was transferred to another, but its .apk remains");
3024 }
3025
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003026 // Just create the setting, don't add it yet. For already existing packages
3027 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003028 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 destResourceFile, pkg.applicationInfo.flags, true, false);
3030 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003031 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3033 return null;
3034 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003035
3036 if (pkgSetting.origPackage != null) {
3037 // If we are first transitioning from an original package,
3038 // fix up the new package's name now. We need to do this after
3039 // looking up the package under its new name, so getPackageLP
3040 // can take care of fiddling things correctly.
3041 pkg.setPackageName(origPackage.name);
3042
3043 // File a report about this.
3044 String msg = "New package " + pkgSetting.realName
3045 + " renamed to replace old package " + pkgSetting.name;
3046 reportSettingsProblem(Log.WARN, msg);
3047
3048 // Make a note of it.
3049 mTransferedPackages.add(origPackage.name);
3050
3051 // No longer need to retain this.
3052 pkgSetting.origPackage = null;
3053 }
3054
3055 if (realName != null) {
3056 // Make a note of it.
3057 mTransferedPackages.add(pkg.packageName);
3058 }
3059
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003060 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003061 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3062 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 pkg.applicationInfo.uid = pkgSetting.userId;
3065 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003066
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003067 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003068 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069 return null;
3070 }
3071 // The signature has changed, but this package is in the system
3072 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003073 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003074 // However... if this package is part of a shared user, but it
3075 // doesn't match the signature of the shared user, let's fail.
3076 // What this means is that you can't change the signatures
3077 // associated with an overall shared user, which doesn't seem all
3078 // that unreasonable.
3079 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003080 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3081 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3082 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3084 return null;
3085 }
3086 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003087 // File a report about this.
3088 String msg = "System package " + pkg.packageName
3089 + " signature changed; retaining data.";
3090 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003092
The Android Open Source Project10592532009-03-18 17:39:46 -07003093 // Verify that this new package doesn't have any content providers
3094 // that conflict with existing packages. Only do this if the
3095 // package isn't already installed, since we don't want to break
3096 // things that are installed.
3097 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3098 int N = pkg.providers.size();
3099 int i;
3100 for (i=0; i<N; i++) {
3101 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003102 if (p.info.authority != null) {
3103 String names[] = p.info.authority.split(";");
3104 for (int j = 0; j < names.length; j++) {
3105 if (mProviders.containsKey(names[j])) {
3106 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003107 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003108 " (in package " + pkg.applicationInfo.packageName +
3109 ") is already used by "
3110 + ((other != null && other.getComponentName() != null)
3111 ? other.getComponentName().getPackageName() : "?"));
3112 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3113 return null;
3114 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003115 }
3116 }
3117 }
3118 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 }
3120
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003121 final String pkgName = pkg.packageName;
3122
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003123 if (pkg.mAdoptPermissions != null) {
3124 // This package wants to adopt ownership of permissions from
3125 // another package.
3126 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3127 String origName = pkg.mAdoptPermissions.get(i);
3128 PackageSetting orig = mSettings.peekPackageLP(origName);
3129 if (orig != null) {
3130 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003131 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003132 + origName + " to " + pkg.packageName);
3133 mSettings.transferPermissions(origName, pkg.packageName);
3134 }
3135 }
3136 }
3137 }
3138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003139 long scanFileTime = scanFile.lastModified();
3140 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3141 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3142 pkg.applicationInfo.processName = fixProcessName(
3143 pkg.applicationInfo.packageName,
3144 pkg.applicationInfo.processName,
3145 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146
3147 File dataPath;
3148 if (mPlatformPackage == pkg) {
3149 // The system package is special.
3150 dataPath = new File (Environment.getDataDirectory(), "system");
3151 pkg.applicationInfo.dataDir = dataPath.getPath();
3152 } else {
3153 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003154 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003155 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003156
3157 boolean uidError = false;
3158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003159 if (dataPath.exists()) {
3160 mOutPermissions[1] = 0;
3161 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003162
3163 // If we have mismatched owners for the data path, we have a
3164 // problem (unless we're running in the simulator.)
3165 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 boolean recovered = false;
3167 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3168 // If this is a system app, we can at least delete its
3169 // current data so the application will still work.
3170 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003171 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003172 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003173 // Old data gone!
3174 String msg = "System package " + pkg.packageName
3175 + " has changed from uid: "
3176 + mOutPermissions[1] + " to "
3177 + pkg.applicationInfo.uid + "; old data erased";
3178 reportSettingsProblem(Log.WARN, msg);
3179 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003180
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003182 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183 pkg.applicationInfo.uid);
3184 if (ret == -1) {
3185 // Ack should not happen!
3186 msg = "System package " + pkg.packageName
3187 + " could not have data directory re-created after delete.";
3188 reportSettingsProblem(Log.WARN, msg);
3189 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3190 return null;
3191 }
3192 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003194 if (!recovered) {
3195 mHasSystemUidErrors = true;
3196 }
3197 }
3198 if (!recovered) {
3199 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3200 + pkg.applicationInfo.uid + "/fs_"
3201 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003202 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003203 String msg = "Package " + pkg.packageName
3204 + " has mismatched uid: "
3205 + mOutPermissions[1] + " on disk, "
3206 + pkg.applicationInfo.uid + " in settings";
3207 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003208 mSettings.mReadMessages.append(msg);
3209 mSettings.mReadMessages.append('\n');
3210 uidError = true;
3211 if (!pkgSetting.uidError) {
3212 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 }
3215 }
3216 }
3217 pkg.applicationInfo.dataDir = dataPath.getPath();
3218 } else {
3219 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3220 Log.v(TAG, "Want this data dir: " + dataPath);
3221 //invoke installer to do the actual installation
3222 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003223 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 pkg.applicationInfo.uid);
3225 if(ret < 0) {
3226 // Error from installer
3227 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3228 return null;
3229 }
3230 } else {
3231 dataPath.mkdirs();
3232 if (dataPath.exists()) {
3233 FileUtils.setPermissions(
3234 dataPath.toString(),
3235 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3236 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3237 }
3238 }
3239 if (dataPath.exists()) {
3240 pkg.applicationInfo.dataDir = dataPath.getPath();
3241 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003242 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003243 pkg.applicationInfo.dataDir = null;
3244 }
3245 }
Kenny Root85387d72010-08-26 10:13:11 -07003246
3247 /*
3248 * Set the data dir to the default "/data/data/<package name>/lib"
3249 * if we got here without anyone telling us different (e.g., apps
3250 * stored on SD card have their native libraries stored in the ASEC
3251 * container with the APK).
3252 */
3253 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3254 pkg.applicationInfo.nativeLibraryDir = new File(dataPath, LIB_DIR_NAME).getPath();
3255 }
3256
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003257 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 }
3259
Kenny Root85387d72010-08-26 10:13:11 -07003260 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 if (mInstaller != null) {
3262 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003263 /* Note: We don't want to unpack the native binaries for
3264 * system applications, unless they have been updated
3265 * (the binaries are already under /system/lib).
3266 * Also, don't unpack libs for apps on the external card
3267 * since they should have their libraries in the ASEC
3268 * container already.
3269 *
3270 * In other words, we're going to unpack the binaries
3271 * only for non-system apps and system app upgrades.
3272 */
3273 if ((!isSystemApp(pkg) || isUpdatedSystemApp(pkg)) && !isExternal(pkg)) {
3274 Log.i(TAG, path + " changed; unpacking");
3275 File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3276 sharedLibraryDir.mkdir();
3277 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003279 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003280
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003281 if ((scanMode&SCAN_NO_DEX) == 0) {
3282 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003283 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3284 return null;
3285 }
3286 }
3287 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 if (mFactoryTest && pkg.requestedPermissions.contains(
3290 android.Manifest.permission.FACTORY_TEST)) {
3291 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3292 }
3293
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003294 // Request the ActivityManager to kill the process(only for existing packages)
3295 // so that we do not end up in a confused state while the user is still using the older
3296 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003297 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003298 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003299 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003300 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003303 // We don't expect installation to fail beyond this point,
3304 if ((scanMode&SCAN_MONITOR) != 0) {
3305 mAppDirs.put(pkg.mPath, pkg);
3306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003308 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003310 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003311 // Make sure we don't accidentally delete its data.
3312 mSettings.mPackagesToBeCleaned.remove(pkgName);
3313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 int N = pkg.providers.size();
3315 StringBuilder r = null;
3316 int i;
3317 for (i=0; i<N; i++) {
3318 PackageParser.Provider p = pkg.providers.get(i);
3319 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3320 p.info.processName, pkg.applicationInfo.uid);
3321 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3322 p.info.name), p);
3323 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003324 if (p.info.authority != null) {
3325 String names[] = p.info.authority.split(";");
3326 p.info.authority = null;
3327 for (int j = 0; j < names.length; j++) {
3328 if (j == 1 && p.syncable) {
3329 // We only want the first authority for a provider to possibly be
3330 // syncable, so if we already added this provider using a different
3331 // authority clear the syncable flag. We copy the provider before
3332 // changing it because the mProviders object contains a reference
3333 // to a provider that we don't want to change.
3334 // Only do this for the second authority since the resulting provider
3335 // object can be the same for all future authorities for this provider.
3336 p = new PackageParser.Provider(p);
3337 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003338 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003339 if (!mProviders.containsKey(names[j])) {
3340 mProviders.put(names[j], p);
3341 if (p.info.authority == null) {
3342 p.info.authority = names[j];
3343 } else {
3344 p.info.authority = p.info.authority + ";" + names[j];
3345 }
3346 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3347 Log.d(TAG, "Registered content provider: " + names[j] +
3348 ", className = " + p.info.name +
3349 ", isSyncable = " + p.info.isSyncable);
3350 } else {
3351 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003352 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003353 " (in package " + pkg.applicationInfo.packageName +
3354 "): name already used by "
3355 + ((other != null && other.getComponentName() != null)
3356 ? other.getComponentName().getPackageName() : "?"));
3357 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 }
3359 }
3360 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3361 if (r == null) {
3362 r = new StringBuilder(256);
3363 } else {
3364 r.append(' ');
3365 }
3366 r.append(p.info.name);
3367 }
3368 }
3369 if (r != null) {
3370 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3371 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 N = pkg.services.size();
3374 r = null;
3375 for (i=0; i<N; i++) {
3376 PackageParser.Service s = pkg.services.get(i);
3377 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3378 s.info.processName, pkg.applicationInfo.uid);
3379 mServices.addService(s);
3380 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3381 if (r == null) {
3382 r = new StringBuilder(256);
3383 } else {
3384 r.append(' ');
3385 }
3386 r.append(s.info.name);
3387 }
3388 }
3389 if (r != null) {
3390 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3391 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 N = pkg.receivers.size();
3394 r = null;
3395 for (i=0; i<N; i++) {
3396 PackageParser.Activity a = pkg.receivers.get(i);
3397 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3398 a.info.processName, pkg.applicationInfo.uid);
3399 mReceivers.addActivity(a, "receiver");
3400 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3401 if (r == null) {
3402 r = new StringBuilder(256);
3403 } else {
3404 r.append(' ');
3405 }
3406 r.append(a.info.name);
3407 }
3408 }
3409 if (r != null) {
3410 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3411 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 N = pkg.activities.size();
3414 r = null;
3415 for (i=0; i<N; i++) {
3416 PackageParser.Activity a = pkg.activities.get(i);
3417 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3418 a.info.processName, pkg.applicationInfo.uid);
3419 mActivities.addActivity(a, "activity");
3420 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3421 if (r == null) {
3422 r = new StringBuilder(256);
3423 } else {
3424 r.append(' ');
3425 }
3426 r.append(a.info.name);
3427 }
3428 }
3429 if (r != null) {
3430 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3431 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 N = pkg.permissionGroups.size();
3434 r = null;
3435 for (i=0; i<N; i++) {
3436 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3437 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3438 if (cur == null) {
3439 mPermissionGroups.put(pg.info.name, pg);
3440 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3441 if (r == null) {
3442 r = new StringBuilder(256);
3443 } else {
3444 r.append(' ');
3445 }
3446 r.append(pg.info.name);
3447 }
3448 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003449 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 + pg.info.packageName + " ignored: original from "
3451 + cur.info.packageName);
3452 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3453 if (r == null) {
3454 r = new StringBuilder(256);
3455 } else {
3456 r.append(' ');
3457 }
3458 r.append("DUP:");
3459 r.append(pg.info.name);
3460 }
3461 }
3462 }
3463 if (r != null) {
3464 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3465 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 N = pkg.permissions.size();
3468 r = null;
3469 for (i=0; i<N; i++) {
3470 PackageParser.Permission p = pkg.permissions.get(i);
3471 HashMap<String, BasePermission> permissionMap =
3472 p.tree ? mSettings.mPermissionTrees
3473 : mSettings.mPermissions;
3474 p.group = mPermissionGroups.get(p.info.group);
3475 if (p.info.group == null || p.group != null) {
3476 BasePermission bp = permissionMap.get(p.info.name);
3477 if (bp == null) {
3478 bp = new BasePermission(p.info.name, p.info.packageName,
3479 BasePermission.TYPE_NORMAL);
3480 permissionMap.put(p.info.name, bp);
3481 }
3482 if (bp.perm == null) {
3483 if (bp.sourcePackage == null
3484 || bp.sourcePackage.equals(p.info.packageName)) {
3485 BasePermission tree = findPermissionTreeLP(p.info.name);
3486 if (tree == null
3487 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003488 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 bp.perm = p;
3490 bp.uid = pkg.applicationInfo.uid;
3491 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3492 if (r == null) {
3493 r = new StringBuilder(256);
3494 } else {
3495 r.append(' ');
3496 }
3497 r.append(p.info.name);
3498 }
3499 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003500 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 + p.info.packageName + " ignored: base tree "
3502 + tree.name + " is from package "
3503 + tree.sourcePackage);
3504 }
3505 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003506 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 + p.info.packageName + " ignored: original from "
3508 + bp.sourcePackage);
3509 }
3510 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3511 if (r == null) {
3512 r = new StringBuilder(256);
3513 } else {
3514 r.append(' ');
3515 }
3516 r.append("DUP:");
3517 r.append(p.info.name);
3518 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003519 if (bp.perm == p) {
3520 bp.protectionLevel = p.info.protectionLevel;
3521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003523 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 + p.info.packageName + " ignored: no group "
3525 + p.group);
3526 }
3527 }
3528 if (r != null) {
3529 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 N = pkg.instrumentation.size();
3533 r = null;
3534 for (i=0; i<N; i++) {
3535 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3536 a.info.packageName = pkg.applicationInfo.packageName;
3537 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3538 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3539 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003540 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003541 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3543 if (r == null) {
3544 r = new StringBuilder(256);
3545 } else {
3546 r.append(' ');
3547 }
3548 r.append(a.info.name);
3549 }
3550 }
3551 if (r != null) {
3552 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3553 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003554
Dianne Hackborn854060af2009-07-09 18:14:31 -07003555 if (pkg.protectedBroadcasts != null) {
3556 N = pkg.protectedBroadcasts.size();
3557 for (i=0; i<N; i++) {
3558 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3559 }
3560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 pkgSetting.setTimeStamp(scanFileTime);
3563 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565 return pkg;
3566 }
3567
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003568 private void killApplication(String pkgName, int uid) {
3569 // Request the ActivityManager to kill the process(only for existing packages)
3570 // so that we do not end up in a confused state while the user is still using the older
3571 // version of the application while the new one gets installed.
3572 IActivityManager am = ActivityManagerNative.getDefault();
3573 if (am != null) {
3574 try {
3575 am.killApplicationWithUid(pkgName, uid);
3576 } catch (RemoteException e) {
3577 }
3578 }
3579 }
3580
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003581 // Return the path of the directory that will contain the native binaries
3582 // of a given installed package. This is relative to the data path.
3583 //
Kenny Root85387d72010-08-26 10:13:11 -07003584 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3585 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3586 if (nativeLibraryDir != null) {
3587 return new File(nativeLibraryDir);
3588 } else {
3589 // Fall back for old packages
3590 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3591 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003592 }
3593
Kenny Root85387d72010-08-26 10:13:11 -07003594 // Convenience call for removeNativeBinariesLI(File)
3595 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3596 File nativeLibraryDir = getNativeBinaryDirForPackage(pkg);
3597 removeNativeBinariesLI(nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598 }
3599
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003600 // Remove the native binaries of a given package. This simply
3601 // gets rid of the files in the 'lib' sub-directory.
Kenny Root85387d72010-08-26 10:13:11 -07003602 public void removeNativeBinariesLI(File binaryDir) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003603 if (DEBUG_NATIVE) {
Kenny Root85387d72010-08-26 10:13:11 -07003604 Slog.w(TAG, "Deleting native binaries from: " + binaryDir.getPath());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003605 }
3606
3607 // Just remove any file in the directory. Since the directory
3608 // is owned by the 'system' UID, the application is not supposed
3609 // to have written anything there.
3610 //
3611 if (binaryDir.exists()) {
Kenny Root85387d72010-08-26 10:13:11 -07003612 File[] binaries = binaryDir.listFiles();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003613 if (binaries != null) {
Kenny Root85387d72010-08-26 10:13:11 -07003614 for (int nn = 0; nn < binaries.length; nn++) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003615 if (DEBUG_NATIVE) {
Kenny Root85387d72010-08-26 10:13:11 -07003616 Slog.d(TAG, " Deleting " + binaries[nn].getName());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003617 }
3618 if (!binaries[nn].delete()) {
Kenny Root85387d72010-08-26 10:13:11 -07003619 Slog.w(TAG, "Could not delete native binary: " + binaries[nn].getPath());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003620 }
3621 }
3622 }
3623 // Do not delete 'lib' directory itself, or this will prevent
3624 // installation of future updates.
3625 }
3626 }
3627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3629 if (chatty && Config.LOGD) Log.d(
3630 TAG, "Removing package " + pkg.applicationInfo.packageName );
3631
3632 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 mPackages.remove(pkg.applicationInfo.packageName);
3636 if (pkg.mPath != null) {
3637 mAppDirs.remove(pkg.mPath);
3638 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003640 PackageSetting ps = (PackageSetting)pkg.mExtras;
3641 if (ps != null && ps.sharedUser != null) {
3642 // XXX don't do this until the data is removed.
3643 if (false) {
3644 ps.sharedUser.packages.remove(ps);
3645 if (ps.sharedUser.packages.size() == 0) {
3646 // Remove.
3647 }
3648 }
3649 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 int N = pkg.providers.size();
3652 StringBuilder r = null;
3653 int i;
3654 for (i=0; i<N; i++) {
3655 PackageParser.Provider p = pkg.providers.get(i);
3656 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3657 p.info.name));
3658 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 /* The is another ContentProvider with this authority when
3661 * this app was installed so this authority is null,
3662 * Ignore it as we don't have to unregister the provider.
3663 */
3664 continue;
3665 }
3666 String names[] = p.info.authority.split(";");
3667 for (int j = 0; j < names.length; j++) {
3668 if (mProviders.get(names[j]) == p) {
3669 mProviders.remove(names[j]);
3670 if (chatty && Config.LOGD) Log.d(
3671 TAG, "Unregistered content provider: " + names[j] +
3672 ", className = " + p.info.name +
3673 ", isSyncable = " + p.info.isSyncable);
3674 }
3675 }
3676 if (chatty) {
3677 if (r == null) {
3678 r = new StringBuilder(256);
3679 } else {
3680 r.append(' ');
3681 }
3682 r.append(p.info.name);
3683 }
3684 }
3685 if (r != null) {
3686 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3687 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003688
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 N = pkg.services.size();
3690 r = null;
3691 for (i=0; i<N; i++) {
3692 PackageParser.Service s = pkg.services.get(i);
3693 mServices.removeService(s);
3694 if (chatty) {
3695 if (r == null) {
3696 r = new StringBuilder(256);
3697 } else {
3698 r.append(' ');
3699 }
3700 r.append(s.info.name);
3701 }
3702 }
3703 if (r != null) {
3704 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3705 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 N = pkg.receivers.size();
3708 r = null;
3709 for (i=0; i<N; i++) {
3710 PackageParser.Activity a = pkg.receivers.get(i);
3711 mReceivers.removeActivity(a, "receiver");
3712 if (chatty) {
3713 if (r == null) {
3714 r = new StringBuilder(256);
3715 } else {
3716 r.append(' ');
3717 }
3718 r.append(a.info.name);
3719 }
3720 }
3721 if (r != null) {
3722 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003725 N = pkg.activities.size();
3726 r = null;
3727 for (i=0; i<N; i++) {
3728 PackageParser.Activity a = pkg.activities.get(i);
3729 mActivities.removeActivity(a, "activity");
3730 if (chatty) {
3731 if (r == null) {
3732 r = new StringBuilder(256);
3733 } else {
3734 r.append(' ');
3735 }
3736 r.append(a.info.name);
3737 }
3738 }
3739 if (r != null) {
3740 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3741 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 N = pkg.permissions.size();
3744 r = null;
3745 for (i=0; i<N; i++) {
3746 PackageParser.Permission p = pkg.permissions.get(i);
3747 boolean tree = false;
3748 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3749 if (bp == null) {
3750 tree = true;
3751 bp = mSettings.mPermissionTrees.get(p.info.name);
3752 }
3753 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003754 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 if (chatty) {
3756 if (r == null) {
3757 r = new StringBuilder(256);
3758 } else {
3759 r.append(' ');
3760 }
3761 r.append(p.info.name);
3762 }
3763 }
3764 }
3765 if (r != null) {
3766 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3767 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003769 N = pkg.instrumentation.size();
3770 r = null;
3771 for (i=0; i<N; i++) {
3772 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003773 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003774 if (chatty) {
3775 if (r == null) {
3776 r = new StringBuilder(256);
3777 } else {
3778 r.append(' ');
3779 }
3780 r.append(a.info.name);
3781 }
3782 }
3783 if (r != null) {
3784 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3785 }
3786 }
3787 }
3788
3789 private static final boolean isPackageFilename(String name) {
3790 return name != null && name.endsWith(".apk");
3791 }
3792
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003793 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3794 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3795 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3796 return true;
3797 }
3798 }
3799 return false;
3800 }
3801
3802 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003803 PackageParser.Package pkgInfo, boolean grantPermissions,
3804 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 // Make sure there are no dangling permission trees.
3806 Iterator<BasePermission> it = mSettings.mPermissionTrees
3807 .values().iterator();
3808 while (it.hasNext()) {
3809 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003810 if (bp.packageSetting == null) {
3811 // We may not yet have parsed the package, so just see if
3812 // we still know about its settings.
3813 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3814 }
3815 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003816 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 + " from package " + bp.sourcePackage);
3818 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003819 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3820 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3821 Slog.i(TAG, "Removing old permission tree: " + bp.name
3822 + " from package " + bp.sourcePackage);
3823 grantPermissions = true;
3824 it.remove();
3825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 }
3827 }
3828
3829 // Make sure all dynamic permissions have been assigned to a package,
3830 // and make sure there are no dangling permissions.
3831 it = mSettings.mPermissions.values().iterator();
3832 while (it.hasNext()) {
3833 BasePermission bp = it.next();
3834 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3835 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3836 + bp.name + " pkg=" + bp.sourcePackage
3837 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003838 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 BasePermission tree = findPermissionTreeLP(bp.name);
3840 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003841 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003842 bp.perm = new PackageParser.Permission(tree.perm.owner,
3843 new PermissionInfo(bp.pendingInfo));
3844 bp.perm.info.packageName = tree.perm.info.packageName;
3845 bp.perm.info.name = bp.name;
3846 bp.uid = tree.uid;
3847 }
3848 }
3849 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003850 if (bp.packageSetting == null) {
3851 // We may not yet have parsed the package, so just see if
3852 // we still know about its settings.
3853 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3854 }
3855 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003856 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 + " from package " + bp.sourcePackage);
3858 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003859 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3860 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3861 Slog.i(TAG, "Removing old permission: " + bp.name
3862 + " from package " + bp.sourcePackage);
3863 grantPermissions = true;
3864 it.remove();
3865 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 }
3867 }
3868
3869 // Now update the permissions for all packages, in particular
3870 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003871 if (grantPermissions) {
3872 for (PackageParser.Package pkg : mPackages.values()) {
3873 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003874 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003875 }
3876 }
3877 }
3878
3879 if (pkgInfo != null) {
3880 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 }
3882 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003883
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3885 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3886 if (ps == null) {
3887 return;
3888 }
3889 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003890 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003891
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003892 if (replace) {
3893 ps.permissionsFixed = false;
3894 if (gp == ps) {
3895 gp.grantedPermissions.clear();
3896 gp.gids = mGlobalGids;
3897 }
3898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 if (gp.gids == null) {
3901 gp.gids = mGlobalGids;
3902 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 final int N = pkg.requestedPermissions.size();
3905 for (int i=0; i<N; i++) {
3906 String name = pkg.requestedPermissions.get(i);
3907 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 if (false) {
3909 if (gp != ps) {
3910 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003911 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 }
3913 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003914 if (bp != null && bp.packageSetting != null) {
3915 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003917 boolean allowedSig = false;
3918 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3919 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003921 } else if (bp.packageSetting == null) {
3922 // This permission is invalid; skip it.
3923 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003924 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3925 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3926 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003927 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003928 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003929 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003930 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003931 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003932 // For updated system applications, the signatureOrSystem permission
3933 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003934 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003935 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3936 if(sysPs.grantedPermissions.contains(perm)) {
3937 allowed = true;
3938 } else {
3939 allowed = false;
3940 }
3941 } else {
3942 allowed = true;
3943 }
3944 }
3945 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003946 if (allowed) {
3947 allowedSig = true;
3948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 } else {
3950 allowed = false;
3951 }
3952 if (false) {
3953 if (gp != ps) {
3954 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3955 }
3956 }
3957 if (allowed) {
3958 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3959 && ps.permissionsFixed) {
3960 // If this is an existing, non-system package, then
3961 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003962 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003963 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003964 // Except... if this is a permission that was added
3965 // to the platform (note: need to only do this when
3966 // updating the platform).
3967 final int NP = PackageParser.NEW_PERMISSIONS.length;
3968 for (int ip=0; ip<NP; ip++) {
3969 final PackageParser.NewPermissionInfo npi
3970 = PackageParser.NEW_PERMISSIONS[ip];
3971 if (npi.name.equals(perm)
3972 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3973 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003974 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003975 + pkg.packageName);
3976 break;
3977 }
3978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003979 }
3980 }
3981 if (allowed) {
3982 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003983 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 gp.grantedPermissions.add(perm);
3985 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003986 } else if (!ps.haveGids) {
3987 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003988 }
3989 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003990 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003991 + " to package " + pkg.packageName
3992 + " because it was previously installed without");
3993 }
3994 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003995 if (gp.grantedPermissions.remove(perm)) {
3996 changedPermission = true;
3997 gp.gids = removeInts(gp.gids, bp.gids);
3998 Slog.i(TAG, "Un-granting permission " + perm
3999 + " from package " + pkg.packageName
4000 + " (protectionLevel=" + bp.protectionLevel
4001 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4002 + ")");
4003 } else {
4004 Slog.w(TAG, "Not granting permission " + perm
4005 + " to package " + pkg.packageName
4006 + " (protectionLevel=" + bp.protectionLevel
4007 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4008 + ")");
4009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004010 }
4011 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004012 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 + " in package " + pkg.packageName);
4014 }
4015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004016
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004017 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004018 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4019 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 // This is the first that we have heard about this package, so the
4021 // permissions we have now selected are fixed until explicitly
4022 // changed.
4023 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004025 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004026 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 private final class ActivityIntentResolver
4029 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004030 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004032 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004033 }
4034
Mihai Preda074edef2009-05-18 17:13:31 +02004035 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004036 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004037 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4039 }
4040
Mihai Predaeae850c2009-05-13 10:13:48 +02004041 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4042 ArrayList<PackageParser.Activity> packageActivities) {
4043 if (packageActivities == null) {
4044 return null;
4045 }
4046 mFlags = flags;
4047 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4048 int N = packageActivities.size();
4049 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4050 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004051
4052 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004053 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004054 intentFilters = packageActivities.get(i).intents;
4055 if (intentFilters != null && intentFilters.size() > 0) {
4056 listCut.add(intentFilters);
4057 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004058 }
4059 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4060 }
4061
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004062 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004063 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004064 if (SHOW_INFO || Config.LOGV) Log.v(
4065 TAG, " " + type + " " +
4066 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4067 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4068 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004069 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004070 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4071 if (SHOW_INFO || Config.LOGV) {
4072 Log.v(TAG, " IntentFilter:");
4073 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4074 }
4075 if (!intent.debugCheck()) {
4076 Log.w(TAG, "==> For Activity " + a.info.name);
4077 }
4078 addFilter(intent);
4079 }
4080 }
4081
4082 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004083 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 if (SHOW_INFO || Config.LOGV) Log.v(
4085 TAG, " " + type + " " +
4086 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4087 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4088 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004089 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4091 if (SHOW_INFO || Config.LOGV) {
4092 Log.v(TAG, " IntentFilter:");
4093 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4094 }
4095 removeFilter(intent);
4096 }
4097 }
4098
4099 @Override
4100 protected boolean allowFilterResult(
4101 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4102 ActivityInfo filterAi = filter.activity.info;
4103 for (int i=dest.size()-1; i>=0; i--) {
4104 ActivityInfo destAi = dest.get(i).activityInfo;
4105 if (destAi.name == filterAi.name
4106 && destAi.packageName == filterAi.packageName) {
4107 return false;
4108 }
4109 }
4110 return true;
4111 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004114 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4115 return info.activity.owner.packageName;
4116 }
4117
4118 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004119 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4120 int match) {
4121 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4122 return null;
4123 }
4124 final PackageParser.Activity activity = info.activity;
4125 if (mSafeMode && (activity.info.applicationInfo.flags
4126 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4127 return null;
4128 }
4129 final ResolveInfo res = new ResolveInfo();
4130 res.activityInfo = PackageParser.generateActivityInfo(activity,
4131 mFlags);
4132 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4133 res.filter = info;
4134 }
4135 res.priority = info.getPriority();
4136 res.preferredOrder = activity.owner.mPreferredOrder;
4137 //System.out.println("Result: " + res.activityInfo.className +
4138 // " = " + res.priority);
4139 res.match = match;
4140 res.isDefault = info.hasDefault;
4141 res.labelRes = info.labelRes;
4142 res.nonLocalizedLabel = info.nonLocalizedLabel;
4143 res.icon = info.icon;
4144 return res;
4145 }
4146
4147 @Override
4148 protected void sortResults(List<ResolveInfo> results) {
4149 Collections.sort(results, mResolvePrioritySorter);
4150 }
4151
4152 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004153 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004154 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004155 out.print(prefix); out.print(
4156 Integer.toHexString(System.identityHashCode(filter.activity)));
4157 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004158 out.print(filter.activity.getComponentShortName());
4159 out.print(" filter ");
4160 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004161 }
4162
4163// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4164// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4165// final List<ResolveInfo> retList = Lists.newArrayList();
4166// while (i.hasNext()) {
4167// final ResolveInfo resolveInfo = i.next();
4168// if (isEnabledLP(resolveInfo.activityInfo)) {
4169// retList.add(resolveInfo);
4170// }
4171// }
4172// return retList;
4173// }
4174
4175 // Keys are String (activity class name), values are Activity.
4176 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4177 = new HashMap<ComponentName, PackageParser.Activity>();
4178 private int mFlags;
4179 }
4180
4181 private final class ServiceIntentResolver
4182 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004183 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004184 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004185 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 }
4187
Mihai Preda074edef2009-05-18 17:13:31 +02004188 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004189 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004190 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4192 }
4193
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004194 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4195 ArrayList<PackageParser.Service> packageServices) {
4196 if (packageServices == null) {
4197 return null;
4198 }
4199 mFlags = flags;
4200 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4201 int N = packageServices.size();
4202 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4203 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4204
4205 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4206 for (int i = 0; i < N; ++i) {
4207 intentFilters = packageServices.get(i).intents;
4208 if (intentFilters != null && intentFilters.size() > 0) {
4209 listCut.add(intentFilters);
4210 }
4211 }
4212 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4213 }
4214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004215 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004216 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 if (SHOW_INFO || Config.LOGV) Log.v(
4218 TAG, " " + (s.info.nonLocalizedLabel != null
4219 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4220 if (SHOW_INFO || Config.LOGV) Log.v(
4221 TAG, " Class=" + s.info.name);
4222 int NI = s.intents.size();
4223 int j;
4224 for (j=0; j<NI; j++) {
4225 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4226 if (SHOW_INFO || Config.LOGV) {
4227 Log.v(TAG, " IntentFilter:");
4228 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4229 }
4230 if (!intent.debugCheck()) {
4231 Log.w(TAG, "==> For Service " + s.info.name);
4232 }
4233 addFilter(intent);
4234 }
4235 }
4236
4237 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004238 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004239 if (SHOW_INFO || Config.LOGV) Log.v(
4240 TAG, " " + (s.info.nonLocalizedLabel != null
4241 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4242 if (SHOW_INFO || Config.LOGV) Log.v(
4243 TAG, " Class=" + s.info.name);
4244 int NI = s.intents.size();
4245 int j;
4246 for (j=0; j<NI; j++) {
4247 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4248 if (SHOW_INFO || Config.LOGV) {
4249 Log.v(TAG, " IntentFilter:");
4250 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4251 }
4252 removeFilter(intent);
4253 }
4254 }
4255
4256 @Override
4257 protected boolean allowFilterResult(
4258 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4259 ServiceInfo filterSi = filter.service.info;
4260 for (int i=dest.size()-1; i>=0; i--) {
4261 ServiceInfo destAi = dest.get(i).serviceInfo;
4262 if (destAi.name == filterSi.name
4263 && destAi.packageName == filterSi.packageName) {
4264 return false;
4265 }
4266 }
4267 return true;
4268 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004269
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004270 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004271 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4272 return info.service.owner.packageName;
4273 }
4274
4275 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004276 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4277 int match) {
4278 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4279 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4280 return null;
4281 }
4282 final PackageParser.Service service = info.service;
4283 if (mSafeMode && (service.info.applicationInfo.flags
4284 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4285 return null;
4286 }
4287 final ResolveInfo res = new ResolveInfo();
4288 res.serviceInfo = PackageParser.generateServiceInfo(service,
4289 mFlags);
4290 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4291 res.filter = filter;
4292 }
4293 res.priority = info.getPriority();
4294 res.preferredOrder = service.owner.mPreferredOrder;
4295 //System.out.println("Result: " + res.activityInfo.className +
4296 // " = " + res.priority);
4297 res.match = match;
4298 res.isDefault = info.hasDefault;
4299 res.labelRes = info.labelRes;
4300 res.nonLocalizedLabel = info.nonLocalizedLabel;
4301 res.icon = info.icon;
4302 return res;
4303 }
4304
4305 @Override
4306 protected void sortResults(List<ResolveInfo> results) {
4307 Collections.sort(results, mResolvePrioritySorter);
4308 }
4309
4310 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004311 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004312 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004313 out.print(prefix); out.print(
4314 Integer.toHexString(System.identityHashCode(filter.service)));
4315 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004316 out.print(filter.service.getComponentShortName());
4317 out.print(" filter ");
4318 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004319 }
4320
4321// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4322// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4323// final List<ResolveInfo> retList = Lists.newArrayList();
4324// while (i.hasNext()) {
4325// final ResolveInfo resolveInfo = (ResolveInfo) i;
4326// if (isEnabledLP(resolveInfo.serviceInfo)) {
4327// retList.add(resolveInfo);
4328// }
4329// }
4330// return retList;
4331// }
4332
4333 // Keys are String (activity class name), values are Activity.
4334 private final HashMap<ComponentName, PackageParser.Service> mServices
4335 = new HashMap<ComponentName, PackageParser.Service>();
4336 private int mFlags;
4337 };
4338
4339 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4340 new Comparator<ResolveInfo>() {
4341 public int compare(ResolveInfo r1, ResolveInfo r2) {
4342 int v1 = r1.priority;
4343 int v2 = r2.priority;
4344 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4345 if (v1 != v2) {
4346 return (v1 > v2) ? -1 : 1;
4347 }
4348 v1 = r1.preferredOrder;
4349 v2 = r2.preferredOrder;
4350 if (v1 != v2) {
4351 return (v1 > v2) ? -1 : 1;
4352 }
4353 if (r1.isDefault != r2.isDefault) {
4354 return r1.isDefault ? -1 : 1;
4355 }
4356 v1 = r1.match;
4357 v2 = r2.match;
4358 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4359 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4360 }
4361 };
4362
4363 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4364 new Comparator<ProviderInfo>() {
4365 public int compare(ProviderInfo p1, ProviderInfo p2) {
4366 final int v1 = p1.initOrder;
4367 final int v2 = p2.initOrder;
4368 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4369 }
4370 };
4371
Kenny Root93565c4b2010-06-18 15:46:06 -07004372 private static final boolean DEBUG_OBB = false;
4373
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004374 private static final void sendPackageBroadcast(String action, String pkg,
4375 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004376 IActivityManager am = ActivityManagerNative.getDefault();
4377 if (am != null) {
4378 try {
4379 final Intent intent = new Intent(action,
4380 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4381 if (extras != null) {
4382 intent.putExtras(extras);
4383 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004384 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004385 am.broadcastIntent(null, intent, null, finishedReceiver,
4386 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004387 } catch (RemoteException ex) {
4388 }
4389 }
4390 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004391
4392 public String nextPackageToClean(String lastPackage) {
4393 synchronized (mPackages) {
4394 if (!mMediaMounted) {
4395 // If the external storage is no longer mounted at this point,
4396 // the caller may not have been able to delete all of this
4397 // packages files and can not delete any more. Bail.
4398 return null;
4399 }
4400 if (lastPackage != null) {
4401 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4402 }
4403 return mSettings.mPackagesToBeCleaned.size() > 0
4404 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4405 }
4406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004407
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004408 void schedulePackageCleaning(String packageName) {
4409 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4410 }
4411
4412 void startCleaningPackages() {
4413 synchronized (mPackages) {
4414 if (!mMediaMounted) {
4415 return;
4416 }
4417 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4418 return;
4419 }
4420 }
4421 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4422 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4423 IActivityManager am = ActivityManagerNative.getDefault();
4424 if (am != null) {
4425 try {
4426 am.startService(null, intent, null);
4427 } catch (RemoteException e) {
4428 }
4429 }
4430 }
4431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004432 private final class AppDirObserver extends FileObserver {
4433 public AppDirObserver(String path, int mask, boolean isrom) {
4434 super(path, mask);
4435 mRootDir = path;
4436 mIsRom = isrom;
4437 }
4438
4439 public void onEvent(int event, String path) {
4440 String removedPackage = null;
4441 int removedUid = -1;
4442 String addedPackage = null;
4443 int addedUid = -1;
4444
4445 synchronized (mInstallLock) {
4446 String fullPathStr = null;
4447 File fullPath = null;
4448 if (path != null) {
4449 fullPath = new File(mRootDir, path);
4450 fullPathStr = fullPath.getPath();
4451 }
4452
4453 if (Config.LOGV) Log.v(
4454 TAG, "File " + fullPathStr + " changed: "
4455 + Integer.toHexString(event));
4456
4457 if (!isPackageFilename(path)) {
4458 if (Config.LOGV) Log.v(
4459 TAG, "Ignoring change of non-package file: " + fullPathStr);
4460 return;
4461 }
4462
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004463 // Ignore packages that are being installed or
4464 // have just been installed.
4465 if (ignoreCodePath(fullPathStr)) {
4466 return;
4467 }
4468 PackageParser.Package p = null;
4469 synchronized (mPackages) {
4470 p = mAppDirs.get(fullPathStr);
4471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004472 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004473 if (p != null) {
4474 removePackageLI(p, true);
4475 removedPackage = p.applicationInfo.packageName;
4476 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 }
4478 }
4479
4480 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004482 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004483 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4484 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004485 PackageParser.PARSE_CHATTY |
4486 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004487 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 if (p != null) {
4489 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004490 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004491 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004492 }
4493 addedPackage = p.applicationInfo.packageName;
4494 addedUid = p.applicationInfo.uid;
4495 }
4496 }
4497 }
4498
4499 synchronized (mPackages) {
4500 mSettings.writeLP();
4501 }
4502 }
4503
4504 if (removedPackage != null) {
4505 Bundle extras = new Bundle(1);
4506 extras.putInt(Intent.EXTRA_UID, removedUid);
4507 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004508 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4509 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004510 }
4511 if (addedPackage != null) {
4512 Bundle extras = new Bundle(1);
4513 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004514 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4515 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004516 }
4517 }
4518
4519 private final String mRootDir;
4520 private final boolean mIsRom;
4521 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004523 /* Called when a downloaded package installation has been confirmed by the user */
4524 public void installPackage(
4525 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004526 installPackage(packageURI, observer, flags, null);
4527 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004528
Jacek Surazski65e13172009-04-28 15:26:38 +02004529 /* Called when a downloaded package installation has been confirmed by the user */
4530 public void installPackage(
4531 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4532 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004533 mContext.enforceCallingOrSelfPermission(
4534 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004535
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004536 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004537 msg.obj = new InstallParams(packageURI, observer, flags,
4538 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004539 mHandler.sendMessage(msg);
4540 }
4541
Christopher Tate1bb69062010-02-19 17:02:12 -08004542 public void finishPackageInstall(int token) {
4543 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4544 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4545 mHandler.sendMessage(msg);
4546 }
4547
Kenny Root93565c4b2010-06-18 15:46:06 -07004548 public void setPackageObbPath(String packageName, String path) {
4549 if (DEBUG_OBB)
4550 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4551 PackageSetting pkgSetting;
4552 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004553 final int permission = mContext.checkCallingPermission(
4554 android.Manifest.permission.INSTALL_PACKAGES);
4555 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004556 synchronized (mPackages) {
4557 pkgSetting = mSettings.mPackages.get(packageName);
4558 if (pkgSetting == null) {
4559 throw new IllegalArgumentException("Unknown package: " + packageName);
4560 }
4561 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4562 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4563 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4564 + pkgSetting.userId);
4565 }
4566 pkgSetting.obbPathString = path;
4567 mSettings.writeLP();
4568 }
4569 }
4570
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004571 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004572 // Queue up an async operation since the package installation may take a little while.
4573 mHandler.post(new Runnable() {
4574 public void run() {
4575 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004576 // Result object to be returned
4577 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004578 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004579 res.uid = -1;
4580 res.pkg = null;
4581 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004582 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004583 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004584 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004585 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004586 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004587 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004589
4590 // A restore should be performed at this point if (a) the install
4591 // succeeded, (b) the operation is not an update, and (c) the new
4592 // package has a backupAgent defined.
4593 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004594 boolean doRestore = (!update
4595 && res.pkg != null
4596 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004597
4598 // Set up the post-install work request bookkeeping. This will be used
4599 // and cleaned up by the post-install event handling regardless of whether
4600 // there's a restore pass performed. Token values are >= 1.
4601 int token;
4602 if (mNextInstallToken < 0) mNextInstallToken = 1;
4603 token = mNextInstallToken++;
4604
4605 PostInstallData data = new PostInstallData(args, res);
4606 mRunningInstalls.put(token, data);
4607 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4608
4609 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4610 // Pass responsibility to the Backup Manager. It will perform a
4611 // restore if appropriate, then pass responsibility back to the
4612 // Package Manager to run the post-install observer callbacks
4613 // and broadcasts.
4614 IBackupManager bm = IBackupManager.Stub.asInterface(
4615 ServiceManager.getService(Context.BACKUP_SERVICE));
4616 if (bm != null) {
4617 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4618 + " to BM for possible restore");
4619 try {
4620 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4621 } catch (RemoteException e) {
4622 // can't happen; the backup manager is local
4623 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004624 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004625 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004626 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004627 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004628 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004629 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004630 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004631 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004632
4633 if (!doRestore) {
4634 // No restore possible, or the Backup Manager was mysteriously not
4635 // available -- just fire the post-install work request directly.
4636 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4637 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4638 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004640 }
4641 });
4642 }
4643
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004644 abstract class HandlerParams {
4645 final static int MAX_RETRIES = 4;
4646 int retry = 0;
4647 final void startCopy() {
4648 try {
4649 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4650 retry++;
4651 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004652 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004653 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4654 handleServiceError();
4655 return;
4656 } else {
4657 handleStartCopy();
4658 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4659 mHandler.sendEmptyMessage(MCS_UNBIND);
4660 }
4661 } catch (RemoteException e) {
4662 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4663 mHandler.sendEmptyMessage(MCS_RECONNECT);
4664 }
4665 handleReturnCode();
4666 }
4667
4668 final void serviceError() {
4669 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4670 handleServiceError();
4671 handleReturnCode();
4672 }
4673 abstract void handleStartCopy() throws RemoteException;
4674 abstract void handleServiceError();
4675 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004676 }
4677
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004678 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004679 final IPackageInstallObserver observer;
4680 int flags;
4681 final Uri packageURI;
4682 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004683 private InstallArgs mArgs;
4684 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004685 InstallParams(Uri packageURI,
4686 IPackageInstallObserver observer, int flags,
4687 String installerPackageName) {
4688 this.packageURI = packageURI;
4689 this.flags = flags;
4690 this.observer = observer;
4691 this.installerPackageName = installerPackageName;
4692 }
4693
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004694 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4695 String packageName = pkgLite.packageName;
4696 int installLocation = pkgLite.installLocation;
4697 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4698 synchronized (mPackages) {
4699 PackageParser.Package pkg = mPackages.get(packageName);
4700 if (pkg != null) {
4701 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4702 // Check for updated system application.
4703 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4704 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004705 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004706 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4707 }
4708 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4709 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004710 if (onSd) {
4711 // Install flag overrides everything.
4712 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4713 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004714 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004715 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4716 // Application explicitly specified internal.
4717 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4718 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4719 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004720 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004721 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004722 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004723 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4724 }
4725 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004726 }
4727 }
4728 } else {
4729 // Invalid install. Return error code
4730 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4731 }
4732 }
4733 }
4734 // All the special cases have been taken care of.
4735 // Return result based on recommended install location.
4736 if (onSd) {
4737 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4738 }
4739 return pkgLite.recommendedInstallLocation;
4740 }
4741
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004742 /*
4743 * Invoke remote method to get package information and install
4744 * location values. Override install location based on default
4745 * policy if needed and then create install arguments based
4746 * on the install location.
4747 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004748 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004749 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004750 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4751 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004752 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4753 if (onInt && onSd) {
4754 // Check if both bits are set.
4755 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4756 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4757 } else if (fwdLocked && onSd) {
4758 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004759 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004760 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004761 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004762 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004763 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004764 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004765 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4766 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4767 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4768 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4769 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004770 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4771 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4772 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004773 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4774 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004775 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004776 // Override with defaults if needed.
4777 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004778 if (!onSd && !onInt) {
4779 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004780 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4781 // Set the flag to install on external media.
4782 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004783 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004784 } else {
4785 // Make sure the flag for installing on external
4786 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004787 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004788 flags &= ~PackageManager.INSTALL_EXTERNAL;
4789 }
4790 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004791 }
4792 }
4793 // Create the file args now.
4794 mArgs = createInstallArgs(this);
4795 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4796 // Create copy only if we are not in an erroneous state.
4797 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004798 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004799 }
4800 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004801 }
4802
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004803 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004804 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004805 // If mArgs is null, then MCS couldn't be reached. When it
4806 // reconnects, it will try again to install. At that point, this
4807 // will succeed.
4808 if (mArgs != null) {
4809 processPendingInstall(mArgs, mRet);
4810 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004811 }
4812
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004813 @Override
4814 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004815 mArgs = createInstallArgs(this);
4816 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004817 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004818 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004819
4820 /*
4821 * Utility class used in movePackage api.
4822 * srcArgs and targetArgs are not set for invalid flags and make
4823 * sure to do null checks when invoking methods on them.
4824 * We probably want to return ErrorPrams for both failed installs
4825 * and moves.
4826 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004827 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004828 final IPackageMoveObserver observer;
4829 final int flags;
4830 final String packageName;
4831 final InstallArgs srcArgs;
4832 final InstallArgs targetArgs;
4833 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004834
4835 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4836 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004837 this.srcArgs = srcArgs;
4838 this.observer = observer;
4839 this.flags = flags;
4840 this.packageName = packageName;
4841 if (srcArgs != null) {
4842 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004843 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004844 } else {
4845 targetArgs = null;
4846 }
4847 }
4848
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004849 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004850 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4851 // Check for storage space on target medium
4852 if (!targetArgs.checkFreeStorage(mContainerService)) {
4853 Log.w(TAG, "Insufficient storage to install");
4854 return;
4855 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004856 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004857 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004858 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004859 if (DEBUG_SD_INSTALL) {
4860 StringBuilder builder = new StringBuilder();
4861 if (srcArgs != null) {
4862 builder.append("src: ");
4863 builder.append(srcArgs.getCodePath());
4864 }
4865 if (targetArgs != null) {
4866 builder.append(" target : ");
4867 builder.append(targetArgs.getCodePath());
4868 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004869 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004870 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004871 }
4872
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004873 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004874 void handleReturnCode() {
4875 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004876 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4877 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4878 currentStatus = PackageManager.MOVE_SUCCEEDED;
4879 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4880 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4881 }
4882 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004883 }
4884
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004885 @Override
4886 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004887 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004888 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004889 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004890
4891 private InstallArgs createInstallArgs(InstallParams params) {
4892 if (installOnSd(params.flags)) {
4893 return new SdInstallArgs(params);
4894 } else {
4895 return new FileInstallArgs(params);
4896 }
4897 }
4898
Kenny Root85387d72010-08-26 10:13:11 -07004899 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4900 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004901 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004902 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004903 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004904 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004905 }
4906 }
4907
Kenny Root85387d72010-08-26 10:13:11 -07004908 // Used by package mover
4909 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004910 if (installOnSd(flags)) {
4911 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4912 return new SdInstallArgs(packageURI, cid);
4913 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004914 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004915 }
4916 }
4917
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004918 static abstract class InstallArgs {
4919 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004920 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004921 final int flags;
4922 final Uri packageURI;
4923 final String installerPackageName;
4924
4925 InstallArgs(Uri packageURI,
4926 IPackageInstallObserver observer, int flags,
4927 String installerPackageName) {
4928 this.packageURI = packageURI;
4929 this.flags = flags;
4930 this.observer = observer;
4931 this.installerPackageName = installerPackageName;
4932 }
4933
4934 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004935 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004936 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004937 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004938 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004939 abstract String getCodePath();
4940 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004941 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004942 // Need installer lock especially for dex file removal.
4943 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004944 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004945 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004946 }
4947
4948 class FileInstallArgs extends InstallArgs {
4949 File installDir;
4950 String codeFileName;
4951 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004952 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004953 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004954
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004955 FileInstallArgs(InstallParams params) {
4956 super(params.packageURI, params.observer,
4957 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004958 }
4959
Kenny Root85387d72010-08-26 10:13:11 -07004960 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004961 super(null, null, 0, null);
4962 File codeFile = new File(fullCodePath);
4963 installDir = codeFile.getParentFile();
4964 codeFileName = fullCodePath;
4965 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004966 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004967 }
4968
Kenny Root85387d72010-08-26 10:13:11 -07004969 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004970 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004971 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004972 String apkName = getNextCodePath(null, pkgName, ".apk");
4973 codeFileName = new File(installDir, apkName + ".apk").getPath();
4974 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004975 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004976 }
4977
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004978 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4979 return imcs.checkFreeStorage(false, packageURI);
4980 }
4981
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004982 String getCodePath() {
4983 return codeFileName;
4984 }
4985
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004986 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004987 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004988 codeFileName = createTempPackageFile(installDir).getPath();
4989 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004991 }
4992
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004993 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004994 if (temp) {
4995 // Generate temp file name
4996 createCopyFile();
4997 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004998 // Get a ParcelFileDescriptor to write to the output file
4999 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005000 if (!created) {
5001 try {
5002 codeFile.createNewFile();
5003 // Set permissions
5004 if (!setPermissions()) {
5005 // Failed setting permissions.
5006 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5007 }
5008 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005009 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005010 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5011 }
5012 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005013 ParcelFileDescriptor out = null;
5014 try {
Kenny Root85387d72010-08-26 10:13:11 -07005015 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005016 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005017 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005018 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5019 }
5020 // Copy the resource now
5021 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5022 try {
5023 if (imcs.copyResource(packageURI, out)) {
5024 ret = PackageManager.INSTALL_SUCCEEDED;
5025 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005026 } finally {
5027 try { if (out != null) out.close(); } catch (IOException e) {}
5028 }
Kenny Root85387d72010-08-26 10:13:11 -07005029
5030 if (!temp) {
5031 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5032 }
5033
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005034 return ret;
5035 }
5036
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005037 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005038 if (status != PackageManager.INSTALL_SUCCEEDED) {
5039 cleanUp();
5040 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005041 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005042 }
5043
5044 boolean doRename(int status, final String pkgName, String oldCodePath) {
5045 if (status != PackageManager.INSTALL_SUCCEEDED) {
5046 cleanUp();
5047 return false;
5048 } else {
5049 // Rename based on packageName
5050 File codeFile = new File(getCodePath());
5051 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5052 File desFile = new File(installDir, apkName + ".apk");
5053 if (!codeFile.renameTo(desFile)) {
5054 return false;
5055 }
5056 // Reset paths since the file has been renamed.
5057 codeFileName = desFile.getPath();
5058 resourceFileName = getResourcePathFromCodePath();
5059 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005060 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005061 // Failed setting permissions.
5062 return false;
5063 }
5064 return true;
5065 }
5066 }
5067
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005068 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005069 if (status != PackageManager.INSTALL_SUCCEEDED) {
5070 cleanUp();
5071 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005072 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005073 }
5074
5075 String getResourcePath() {
5076 return resourceFileName;
5077 }
5078
5079 String getResourcePathFromCodePath() {
5080 String codePath = getCodePath();
5081 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5082 String apkNameOnly = getApkName(codePath);
5083 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5084 } else {
5085 return codePath;
5086 }
5087 }
5088
Kenny Root85387d72010-08-26 10:13:11 -07005089 @Override
5090 String getNativeLibraryPath() {
5091 return libraryPath;
5092 }
5093
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005094 private boolean cleanUp() {
5095 boolean ret = true;
5096 String sourceDir = getCodePath();
5097 String publicSourceDir = getResourcePath();
5098 if (sourceDir != null) {
5099 File sourceFile = new File(sourceDir);
5100 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005101 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005102 ret = false;
5103 }
5104 // Delete application's code and resources
5105 sourceFile.delete();
5106 }
5107 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5108 final File publicSourceFile = new File(publicSourceDir);
5109 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005110 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005111 }
5112 if (publicSourceFile.exists()) {
5113 publicSourceFile.delete();
5114 }
5115 }
5116 return ret;
5117 }
5118
5119 void cleanUpResourcesLI() {
5120 String sourceDir = getCodePath();
5121 if (cleanUp() && mInstaller != null) {
5122 int retCode = mInstaller.rmdex(sourceDir);
5123 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005124 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005125 + " at location "
5126 + sourceDir + ", retcode=" + retCode);
5127 // we don't consider this to be a failure of the core package deletion
5128 }
5129 }
Kenny Root85387d72010-08-26 10:13:11 -07005130 if (libraryPath != null) {
5131 removeNativeBinariesLI(new File(libraryPath));
5132 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005133 }
5134
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005135 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005136 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005137 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005138 final int filePermissions =
5139 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5140 |FileUtils.S_IROTH;
5141 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5142 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005143 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005144 getCodePath()
5145 + ". The return code was: " + retCode);
5146 // TODO Define new internal error
5147 return false;
5148 }
5149 return true;
5150 }
5151 return true;
5152 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005153
5154 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005155 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005156 cleanUpResourcesLI();
5157 return true;
5158 }
Kenny Root85387d72010-08-26 10:13:11 -07005159
5160 private boolean isFwdLocked() {
5161 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5162 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005163 }
5164
5165 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005166 static final String RES_FILE_NAME = "pkg.apk";
5167
Kenny Root85387d72010-08-26 10:13:11 -07005168 String cid;
5169 String packagePath;
5170 String libraryPath;
5171
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005172 SdInstallArgs(InstallParams params) {
5173 super(params.packageURI, params.observer,
5174 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005175 }
5176
Kenny Root85387d72010-08-26 10:13:11 -07005177 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005178 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005179 // Extract cid from fullCodePath
5180 int eidx = fullCodePath.lastIndexOf("/");
5181 String subStr1 = fullCodePath.substring(0, eidx);
5182 int sidx = subStr1.lastIndexOf("/");
5183 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005184 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005185 }
5186
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005187 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005188 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5189 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005190 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005191 }
5192
5193 SdInstallArgs(Uri packageURI, String cid) {
5194 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005195 this.cid = cid;
5196 }
5197
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005198 void createCopyFile() {
5199 cid = getTempContainerId();
5200 }
5201
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005202 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5203 return imcs.checkFreeStorage(true, packageURI);
5204 }
5205
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005206 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005207 if (temp) {
5208 createCopyFile();
5209 }
Kenny Root85387d72010-08-26 10:13:11 -07005210 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005211 packageURI, cid,
5212 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005213 if (newCachePath != null) {
5214 setCachePath(newCachePath);
5215 return PackageManager.INSTALL_SUCCEEDED;
5216 } else {
5217 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5218 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005219 }
5220
5221 @Override
5222 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005223 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005224 }
5225
5226 @Override
5227 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005228 return packagePath;
5229 }
5230
5231 @Override
5232 String getNativeLibraryPath() {
5233 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005234 }
5235
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005236 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005237 if (status != PackageManager.INSTALL_SUCCEEDED) {
5238 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005239 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005240 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005241 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005242 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005243 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5244 Process.SYSTEM_UID);
5245 if (newCachePath != null) {
5246 setCachePath(newCachePath);
5247 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005248 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5249 }
5250 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005251 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005252 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005253 }
5254
5255 boolean doRename(int status, final String pkgName,
5256 String oldCodePath) {
5257 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005258 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005259 if (PackageHelper.isContainerMounted(cid)) {
5260 // Unmount the container
5261 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005262 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005263 return false;
5264 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005265 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005266 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005267 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5268 " which might be stale. Will try to clean up.");
5269 // Clean up the stale container and proceed to recreate.
5270 if (!PackageHelper.destroySdDir(newCacheId)) {
5271 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5272 return false;
5273 }
5274 // Successfully cleaned up stale container. Try to rename again.
5275 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5276 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5277 + " inspite of cleaning it up.");
5278 return false;
5279 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005280 }
5281 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005282 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005283 newCachePath = PackageHelper.mountSdDir(newCacheId,
5284 getEncryptKey(), Process.SYSTEM_UID);
5285 } else {
5286 newCachePath = PackageHelper.getSdDir(newCacheId);
5287 }
5288 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005289 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005290 return false;
5291 }
5292 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005293 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005294 " at new path: " + newCachePath);
5295 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005296 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005297 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005298 }
5299
Kenny Root85387d72010-08-26 10:13:11 -07005300 private void setCachePath(String newCachePath) {
5301 File cachePath = new File(newCachePath);
5302 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5303 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5304 }
5305
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005306 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005307 if (status != PackageManager.INSTALL_SUCCEEDED) {
5308 cleanUp();
5309 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005310 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005311 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005312 PackageHelper.mountSdDir(cid,
5313 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005314 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005315 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005316 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005317 }
5318
5319 private void cleanUp() {
5320 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005321 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005322 }
5323
5324 void cleanUpResourcesLI() {
5325 String sourceFile = getCodePath();
5326 // Remove dex file
5327 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005328 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005329 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005330 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005331 + " at location "
5332 + sourceFile.toString() + ", retcode=" + retCode);
5333 // we don't consider this to be a failure of the core package deletion
5334 }
5335 }
5336 cleanUp();
5337 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005338
5339 boolean matchContainer(String app) {
5340 if (cid.startsWith(app)) {
5341 return true;
5342 }
5343 return false;
5344 }
5345
5346 String getPackageName() {
5347 int idx = cid.lastIndexOf("-");
5348 if (idx == -1) {
5349 return cid;
5350 }
5351 return cid.substring(0, idx);
5352 }
5353
5354 boolean doPostDeleteLI(boolean delete) {
5355 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005356 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005357 if (mounted) {
5358 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005359 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005360 }
5361 if (ret && delete) {
5362 cleanUpResourcesLI();
5363 }
5364 return ret;
5365 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005366 };
5367
5368 // Utility method used to create code paths based on package name and available index.
5369 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5370 String idxStr = "";
5371 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005372 // Fall back to default value of idx=1 if prefix is not
5373 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005374 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005375 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005376 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005377 if (subStr.endsWith(suffix)) {
5378 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005379 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005380 // If oldCodePath already contains prefix find out the
5381 // ending index to either increment or decrement.
5382 int sidx = subStr.lastIndexOf(prefix);
5383 if (sidx != -1) {
5384 subStr = subStr.substring(sidx + prefix.length());
5385 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005386 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5387 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005388 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005389 try {
5390 idx = Integer.parseInt(subStr);
5391 if (idx <= 1) {
5392 idx++;
5393 } else {
5394 idx--;
5395 }
5396 } catch(NumberFormatException e) {
5397 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005398 }
5399 }
5400 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005401 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005402 return prefix + idxStr;
5403 }
5404
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005405 // Utility method used to ignore ADD/REMOVE events
5406 // by directory observer.
5407 private static boolean ignoreCodePath(String fullPathStr) {
5408 String apkName = getApkName(fullPathStr);
5409 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5410 if (idx != -1 && ((idx+1) < apkName.length())) {
5411 // Make sure the package ends with a numeral
5412 String version = apkName.substring(idx+1);
5413 try {
5414 Integer.parseInt(version);
5415 return true;
5416 } catch (NumberFormatException e) {}
5417 }
5418 return false;
5419 }
5420
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005421 // Utility method that returns the relative package path with respect
5422 // to the installation directory. Like say for /data/data/com.test-1.apk
5423 // string com.test-1 is returned.
5424 static String getApkName(String codePath) {
5425 if (codePath == null) {
5426 return null;
5427 }
5428 int sidx = codePath.lastIndexOf("/");
5429 int eidx = codePath.lastIndexOf(".");
5430 if (eidx == -1) {
5431 eidx = codePath.length();
5432 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005433 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005434 return null;
5435 }
5436 return codePath.substring(sidx+1, eidx);
5437 }
5438
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005439 class PackageInstalledInfo {
5440 String name;
5441 int uid;
5442 PackageParser.Package pkg;
5443 int returnCode;
5444 PackageRemovedInfo removedInfo;
5445 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 /*
5448 * Install a non-existing package.
5449 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005450 private void installNewPackageLI(PackageParser.Package pkg,
5451 int parseFlags,
5452 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005453 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005455 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005456
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005457 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458 res.name = pkgName;
5459 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005460 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5461 // A package with the same name is already installed, though
5462 // it has been renamed to an older name. The package we
5463 // are trying to install should be installed as an update to
5464 // the existing one, but that has not been requested, so bail.
5465 Slog.w(TAG, "Attempt to re-install " + pkgName
5466 + " without first uninstalling package running as "
5467 + mSettings.mRenamedPackages.get(pkgName));
5468 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5469 return;
5470 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005471 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005473 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005474 + " without first uninstalling.");
5475 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5476 return;
5477 }
5478 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005480 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005481 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005482 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005483 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5484 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5485 }
5486 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005487 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005488 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005489 res);
5490 // delete the partially installed application. the data directory will have to be
5491 // restored if it was already existing
5492 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5493 // remove package from internal structures. Note that we want deletePackageX to
5494 // delete the package data and cache directories that it created in
5495 // scanPackageLocked, unless those directories existed before we even tried to
5496 // install.
5497 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005498 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5500 res.removedInfo);
5501 }
5502 }
5503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005504
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005505 private void replacePackageLI(PackageParser.Package pkg,
5506 int parseFlags,
5507 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005508 String installerPackageName, PackageInstalledInfo res) {
5509
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005510 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005511 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005512 // First find the old package info and check signatures
5513 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005514 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005515 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005516 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005517 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5518 return;
5519 }
5520 }
Kenny Root85387d72010-08-26 10:13:11 -07005521 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005522 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005523 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005524 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005525 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 }
5527 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005530 PackageParser.Package pkg,
5531 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005532 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005533 PackageParser.Package newPackage = null;
5534 String pkgName = deletedPackage.packageName;
5535 boolean deletedPkg = true;
5536 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005537
Jacek Surazski65e13172009-04-28 15:26:38 +02005538 String oldInstallerPackageName = null;
5539 synchronized (mPackages) {
5540 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5541 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005543 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005544 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005545 res.removedInfo)) {
5546 // If the existing package was'nt successfully deleted
5547 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5548 deletedPkg = false;
5549 } else {
5550 // Successfully deleted the old package. Now proceed with re-installation
5551 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005552 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005553 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005554 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005555 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5556 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005557 }
5558 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005559 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005560 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005561 res);
5562 updatedSettings = true;
5563 }
5564 }
5565
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005566 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005567 // remove package from internal structures. Note that we want deletePackageX to
5568 // delete the package data and cache directories that it created in
5569 // scanPackageLocked, unless those directories existed before we even tried to
5570 // install.
5571 if(updatedSettings) {
5572 deletePackageLI(
5573 pkgName, true,
5574 PackageManager.DONT_DELETE_DATA,
5575 res.removedInfo);
5576 }
5577 // Since we failed to install the new package we need to restore the old
5578 // package that we deleted.
5579 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005580 File restoreFile = new File(deletedPackage.mPath);
5581 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005582 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005583 return;
5584 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005585 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005586 boolean oldOnSd = isExternal(deletedPackage);
5587 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5588 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5589 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5590 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5591 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5592 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5593 return;
5594 }
5595 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005596 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005597 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005598 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005599 mSettings.writeLP();
5600 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005601 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 }
5603 }
5604 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005607 PackageParser.Package pkg,
5608 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005609 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005610 PackageParser.Package newPackage = null;
5611 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005612 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005613 PackageParser.PARSE_IS_SYSTEM;
5614 String packageName = deletedPackage.packageName;
5615 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5616 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005617 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 return;
5619 }
5620 PackageParser.Package oldPkg;
5621 PackageSetting oldPkgSetting;
5622 synchronized (mPackages) {
5623 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005624 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005625 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5626 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005627 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005628 return;
5629 }
5630 }
5631 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5632 res.removedInfo.removedPackage = packageName;
5633 // Remove existing system package
5634 removePackageLI(oldPkg, true);
5635 synchronized (mPackages) {
5636 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5637 }
5638
5639 // Successfully disabled the old package. Now proceed with re-installation
5640 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5641 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005642 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005643 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005644 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005645 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5646 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5647 }
5648 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005649 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 updatedSettings = true;
5651 }
5652
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005653 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005654 // Re installation failed. Restore old information
5655 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005656 if (newPackage != null) {
5657 removePackageLI(newPackage, true);
5658 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005660 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005661 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005662 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005663 // Restore the old system information in Settings
5664 synchronized(mPackages) {
5665 if(updatedSettings) {
5666 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005667 mSettings.setInstallerPackageName(packageName,
5668 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005669 }
5670 mSettings.writeLP();
5671 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005672 } else {
5673 // If this is an update to an existing update, setup
5674 // to remove the existing update.
5675 synchronized (mPackages) {
5676 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5677 if (ps != null && ps.codePathString != null &&
5678 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5679 int installFlags = 0;
5680 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005681 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005682 }
5683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005684 }
5685 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005686
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005687 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005688 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005689 int retCode;
5690 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5691 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5692 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005693 if (mNoDexOpt) {
5694 /*
5695 * If we're in an engineering build, programs are lazily run
5696 * through dexopt. If the .dex file doesn't exist yet, it
5697 * will be created when the program is run next.
5698 */
5699 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5700 } else {
5701 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5702 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5703 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005704 }
5705 }
5706 return PackageManager.INSTALL_SUCCEEDED;
5707 }
5708
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005709 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005710 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005711 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005712 synchronized (mPackages) {
5713 //write settings. the installStatus will be incomplete at this stage.
5714 //note that the new package setting would have already been
5715 //added to mPackages. It hasn't been persisted yet.
5716 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5717 mSettings.writeLP();
5718 }
5719
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005720 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005721 != PackageManager.INSTALL_SUCCEEDED) {
5722 // Discontinue if moving dex files failed.
5723 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005724 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005725 if((res.returnCode = setPermissionsLI(newPackage))
5726 != PackageManager.INSTALL_SUCCEEDED) {
5727 if (mInstaller != null) {
5728 mInstaller.rmdex(newPackage.mScanPath);
5729 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005730 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005731 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005732 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005734 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005735 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005736 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005737 res.name = pkgName;
5738 res.uid = newPackage.applicationInfo.uid;
5739 res.pkg = newPackage;
5740 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005741 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005742 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5743 //to update install status
5744 mSettings.writeLP();
5745 }
5746 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005747
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005748 private void installPackageLI(InstallArgs args,
5749 boolean newInstall, PackageInstalledInfo res) {
5750 int pFlags = args.flags;
5751 String installerPackageName = args.installerPackageName;
5752 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005753 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005754 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005755 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005756 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005757 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005758 // Result object to be returned
5759 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5760
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005761 // Retrieve PackageSettings and parse package
5762 int parseFlags = PackageParser.PARSE_CHATTY |
5763 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5764 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5765 parseFlags |= mDefParseFlags;
5766 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5767 pp.setSeparateProcesses(mSeparateProcesses);
5768 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5769 null, mMetrics, parseFlags);
5770 if (pkg == null) {
5771 res.returnCode = pp.getParseError();
5772 return;
5773 }
5774 String pkgName = res.name = pkg.packageName;
5775 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5776 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5777 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5778 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005780 }
5781 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5782 res.returnCode = pp.getParseError();
5783 return;
5784 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005785 // Get rid of all references to package scan path via parser.
5786 pp = null;
5787 String oldCodePath = null;
5788 boolean systemApp = false;
5789 synchronized (mPackages) {
5790 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005791 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5792 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005793 if (pkg.mOriginalPackages != null
5794 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005795 && mPackages.containsKey(oldName)) {
5796 // This package is derived from an original package,
5797 // and this device has been updating from that original
5798 // name. We must continue using the original name, so
5799 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005800 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005801 pkgName = pkg.packageName;
5802 replace = true;
5803 } else if (mPackages.containsKey(pkgName)) {
5804 // This package, under its official name, already exists
5805 // on the device; we should replace it.
5806 replace = true;
5807 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005808 }
5809 PackageSetting ps = mSettings.mPackages.get(pkgName);
5810 if (ps != null) {
5811 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5812 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5813 systemApp = (ps.pkg.applicationInfo.flags &
5814 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005815 }
5816 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005817 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005818
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005819 if (systemApp && onSd) {
5820 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005821 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005822 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5823 return;
5824 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005825
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005826 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5827 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5828 return;
5829 }
5830 // Set application objects path explicitly after the rename
5831 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005832 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005833 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005834 replacePackageLI(pkg, parseFlags, scanMode,
5835 installerPackageName, res);
5836 } else {
5837 installNewPackageLI(pkg, parseFlags, scanMode,
5838 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005839 }
5840 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005841
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005842 private int setPermissionsLI(PackageParser.Package newPackage) {
5843 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005844 int retCode = 0;
5845 // TODO Gross hack but fix later. Ideally move this to be a post installation
5846 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005847 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005848 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 try {
5850 extractPublicFiles(newPackage, destResourceFile);
5851 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005852 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 -08005853 " forward-locked app.");
5854 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5855 } finally {
5856 //TODO clean up the extracted public files
5857 }
5858 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005859 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005860 newPackage.applicationInfo.uid);
5861 } else {
5862 final int filePermissions =
5863 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005864 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005865 newPackage.applicationInfo.uid);
5866 }
5867 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005868 // The permissions on the resource file was set when it was copied for
5869 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005870 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005872 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005873 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005874 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005875 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005876 // TODO Define new internal error
5877 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005878 }
5879 return PackageManager.INSTALL_SUCCEEDED;
5880 }
5881
Kenny Root85387d72010-08-26 10:13:11 -07005882 private static boolean isForwardLocked(PackageParser.Package pkg) {
5883 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005884 }
5885
Kenny Root85387d72010-08-26 10:13:11 -07005886 private static boolean isExternal(PackageParser.Package pkg) {
5887 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5888 }
5889
5890 private static boolean isSystemApp(PackageParser.Package pkg) {
5891 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5892 }
5893
5894 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5895 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005896 }
5897
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005898 private void extractPublicFiles(PackageParser.Package newPackage,
5899 File publicZipFile) throws IOException {
5900 final ZipOutputStream publicZipOutStream =
5901 new ZipOutputStream(new FileOutputStream(publicZipFile));
5902 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5903
5904 // Copy manifest, resources.arsc and res directory to public zip
5905
5906 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5907 while (privateZipEntries.hasMoreElements()) {
5908 final ZipEntry zipEntry = privateZipEntries.nextElement();
5909 final String zipEntryName = zipEntry.getName();
5910 if ("AndroidManifest.xml".equals(zipEntryName)
5911 || "resources.arsc".equals(zipEntryName)
5912 || zipEntryName.startsWith("res/")) {
5913 try {
5914 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5915 } catch (IOException e) {
5916 try {
5917 publicZipOutStream.close();
5918 throw e;
5919 } finally {
5920 publicZipFile.delete();
5921 }
5922 }
5923 }
5924 }
5925
5926 publicZipOutStream.close();
5927 FileUtils.setPermissions(
5928 publicZipFile.getAbsolutePath(),
5929 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5930 -1, -1);
5931 }
5932
5933 private static void copyZipEntry(ZipEntry zipEntry,
5934 ZipFile inZipFile,
5935 ZipOutputStream outZipStream) throws IOException {
5936 byte[] buffer = new byte[4096];
5937 int num;
5938
5939 ZipEntry newEntry;
5940 if (zipEntry.getMethod() == ZipEntry.STORED) {
5941 // Preserve the STORED method of the input entry.
5942 newEntry = new ZipEntry(zipEntry);
5943 } else {
5944 // Create a new entry so that the compressed len is recomputed.
5945 newEntry = new ZipEntry(zipEntry.getName());
5946 }
5947 outZipStream.putNextEntry(newEntry);
5948
5949 InputStream data = inZipFile.getInputStream(zipEntry);
5950 while ((num = data.read(buffer)) > 0) {
5951 outZipStream.write(buffer, 0, num);
5952 }
5953 outZipStream.flush();
5954 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005956 private void deleteTempPackageFiles() {
5957 FilenameFilter filter = new FilenameFilter() {
5958 public boolean accept(File dir, String name) {
5959 return name.startsWith("vmdl") && name.endsWith(".tmp");
5960 }
5961 };
5962 String tmpFilesList[] = mAppInstallDir.list(filter);
5963 if(tmpFilesList == null) {
5964 return;
5965 }
5966 for(int i = 0; i < tmpFilesList.length; i++) {
5967 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5968 tmpFile.delete();
5969 }
5970 }
5971
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005972 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005973 File tmpPackageFile;
5974 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005975 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005976 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005977 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005978 return null;
5979 }
5980 try {
5981 FileUtils.setPermissions(
5982 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5983 -1, -1);
5984 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005985 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005986 return null;
5987 }
5988 return tmpPackageFile;
5989 }
5990
5991 public void deletePackage(final String packageName,
5992 final IPackageDeleteObserver observer,
5993 final int flags) {
5994 mContext.enforceCallingOrSelfPermission(
5995 android.Manifest.permission.DELETE_PACKAGES, null);
5996 // Queue up an async operation since the package deletion may take a little while.
5997 mHandler.post(new Runnable() {
5998 public void run() {
5999 mHandler.removeCallbacks(this);
6000 final boolean succeded = deletePackageX(packageName, true, true, flags);
6001 if (observer != null) {
6002 try {
6003 observer.packageDeleted(succeded);
6004 } catch (RemoteException e) {
6005 Log.i(TAG, "Observer no longer exists.");
6006 } //end catch
6007 } //end if
6008 } //end run
6009 });
6010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006012 /**
6013 * This method is an internal method that could be get invoked either
6014 * to delete an installed package or to clean up a failed installation.
6015 * After deleting an installed package, a broadcast is sent to notify any
6016 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006017 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006018 * installation wouldn't have sent the initial broadcast either
6019 * The key steps in deleting a package are
6020 * deleting the package information in internal structures like mPackages,
6021 * deleting the packages base directories through installd
6022 * updating mSettings to reflect current status
6023 * persisting settings for later use
6024 * sending a broadcast if necessary
6025 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6027 boolean deleteCodeAndResources, int flags) {
6028 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006029 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006030
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006031 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6032 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6033 try {
6034 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006035 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006036 return false;
6037 }
6038 } catch (RemoteException e) {
6039 }
6040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006041 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006042 res = deletePackageLI(packageName, deleteCodeAndResources,
6043 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006044 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006046 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006047 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006048 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006049
6050 // If the removed package was a system update, the old system packaged
6051 // was re-enabled; we need to broadcast this information
6052 if (systemUpdate) {
6053 Bundle extras = new Bundle(1);
6054 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6055 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6056
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006057 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6058 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006060 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006061 // Force a gc here.
6062 Runtime.getRuntime().gc();
6063 // Delete the resources here after sending the broadcast to let
6064 // other processes clean up before deleting resources.
6065 if (info.args != null) {
6066 synchronized (mInstallLock) {
6067 info.args.doPostDeleteLI(deleteCodeAndResources);
6068 }
6069 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 return res;
6071 }
6072
6073 static class PackageRemovedInfo {
6074 String removedPackage;
6075 int uid = -1;
6076 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006077 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006078 // Clean up resources deleted packages.
6079 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006080
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006081 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006082 Bundle extras = new Bundle(1);
6083 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6084 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6085 if (replacing) {
6086 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6087 }
6088 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006089 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006090 }
6091 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006092 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 }
6094 }
6095 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 /*
6098 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6099 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006100 * 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 -08006101 * delete a partially installed application.
6102 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006103 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 int flags) {
6105 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006106 if (outInfo != null) {
6107 outInfo.removedPackage = packageName;
6108 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006109 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006110 // Retrieve object to delete permissions for shared user later on
6111 PackageSetting deletedPs;
6112 synchronized (mPackages) {
6113 deletedPs = mSettings.mPackages.get(packageName);
6114 }
6115 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006116 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006118 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006119 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006120 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006121 + packageName + ", retcode=" + retCode);
6122 // we don't consider this to be a failure of the core package deletion
6123 }
6124 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006125 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006126 PackageParser.Package pkg = mPackages.get(packageName);
6127 File dataDir = new File(pkg.applicationInfo.dataDir);
6128 dataDir.delete();
6129 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006130 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006131 }
6132 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006133 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006134 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6135 if (outInfo != null) {
6136 outInfo.removedUid = mSettings.removePackageLP(packageName);
6137 }
6138 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006139 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006140 if (deletedPs.sharedUser != null) {
6141 // remove permissions associated with package
6142 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6143 }
6144 }
6145 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006146 // remove from preferred activities.
6147 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6148 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6149 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6150 removed.add(pa);
6151 }
6152 }
6153 for (PreferredActivity pa : removed) {
6154 mSettings.mPreferredActivities.removeFilter(pa);
6155 }
6156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006157 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006158 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006159 }
6160 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006161
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006162 /*
6163 * Tries to delete system package.
6164 */
6165 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006166 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 ApplicationInfo applicationInfo = p.applicationInfo;
6168 //applicable for non-partially installed applications only
6169 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006170 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 return false;
6172 }
6173 PackageSetting ps = null;
6174 // Confirm if the system package has been updated
6175 // An updated system app can be deleted. This will also have to restore
6176 // the system pkg from system partition
6177 synchronized (mPackages) {
6178 ps = mSettings.getDisabledSystemPkg(p.packageName);
6179 }
6180 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006181 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006182 return false;
6183 } else {
6184 Log.i(TAG, "Deleting system pkg from data partition");
6185 }
6186 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006187 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006188 final boolean deleteCodeAndResources;
6189 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006190 // Delete code and resources for downgrades
6191 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006192 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006193 } else {
6194 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006195 deleteCodeAndResources = false;
6196 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006198 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6199 if (!ret) {
6200 return false;
6201 }
6202 synchronized (mPackages) {
6203 // Reinstate the old system package
6204 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07006205 // Remove any native libraries. XXX needed?
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006206 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207 }
6208 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006209 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006210 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006211 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006213 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006214 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 return false;
6216 }
6217 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006218 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006219 mSettings.writeLP();
6220 }
6221 return true;
6222 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006224 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6225 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6226 ApplicationInfo applicationInfo = p.applicationInfo;
6227 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006228 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 return false;
6230 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006231 if (outInfo != null) {
6232 outInfo.uid = applicationInfo.uid;
6233 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006234
6235 // Delete package data from internal structures and also remove data if flag is set
6236 removePackageDataLI(p, outInfo, flags);
6237
6238 // Delete application code and resources
6239 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006240 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006241 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6242 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6243 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6244 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 }
6246 return true;
6247 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006249 /*
6250 * This method handles package deletion in general
6251 */
6252 private boolean deletePackageLI(String packageName,
6253 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6254 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006255 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006256 return false;
6257 }
6258 PackageParser.Package p;
6259 boolean dataOnly = false;
6260 synchronized (mPackages) {
6261 p = mPackages.get(packageName);
6262 if (p == null) {
6263 //this retrieves partially installed apps
6264 dataOnly = true;
6265 PackageSetting ps = mSettings.mPackages.get(packageName);
6266 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006267 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006268 return false;
6269 }
6270 p = ps.pkg;
6271 }
6272 }
6273 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006274 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006275 return false;
6276 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006278 if (dataOnly) {
6279 // Delete application data first
6280 removePackageDataLI(p, outInfo, flags);
6281 return true;
6282 }
6283 // At this point the package should have ApplicationInfo associated with it
6284 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006285 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 return false;
6287 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006288 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006289 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006290 Log.i(TAG, "Removing system package:"+p.packageName);
6291 // When an updated system application is deleted we delete the existing resources as well and
6292 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006293 ret = deleteSystemPackageLI(p, flags, outInfo);
6294 } else {
6295 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006296 // Kill application pre-emptively especially for apps on sd.
6297 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006298 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006300 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006301 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006303 public void clearApplicationUserData(final String packageName,
6304 final IPackageDataObserver observer) {
6305 mContext.enforceCallingOrSelfPermission(
6306 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6307 // Queue up an async operation since the package deletion may take a little while.
6308 mHandler.post(new Runnable() {
6309 public void run() {
6310 mHandler.removeCallbacks(this);
6311 final boolean succeeded;
6312 synchronized (mInstallLock) {
6313 succeeded = clearApplicationUserDataLI(packageName);
6314 }
6315 if (succeeded) {
6316 // invoke DeviceStorageMonitor's update method to clear any notifications
6317 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6318 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6319 if (dsm != null) {
6320 dsm.updateMemory();
6321 }
6322 }
6323 if(observer != null) {
6324 try {
6325 observer.onRemoveCompleted(packageName, succeeded);
6326 } catch (RemoteException e) {
6327 Log.i(TAG, "Observer no longer exists.");
6328 }
6329 } //end if observer
6330 } //end run
6331 });
6332 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006334 private boolean clearApplicationUserDataLI(String packageName) {
6335 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006336 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 return false;
6338 }
6339 PackageParser.Package p;
6340 boolean dataOnly = false;
6341 synchronized (mPackages) {
6342 p = mPackages.get(packageName);
6343 if(p == null) {
6344 dataOnly = true;
6345 PackageSetting ps = mSettings.mPackages.get(packageName);
6346 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006347 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006348 return false;
6349 }
6350 p = ps.pkg;
6351 }
6352 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006353 boolean useEncryptedFSDir = false;
6354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 if(!dataOnly) {
6356 //need to check this only for fully installed applications
6357 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006358 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006359 return false;
6360 }
6361 final ApplicationInfo applicationInfo = p.applicationInfo;
6362 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006363 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006364 return false;
6365 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006366 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006367 }
6368 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006369 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006370 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006371 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006372 + packageName);
6373 return false;
6374 }
6375 }
6376 return true;
6377 }
6378
6379 public void deleteApplicationCacheFiles(final String packageName,
6380 final IPackageDataObserver observer) {
6381 mContext.enforceCallingOrSelfPermission(
6382 android.Manifest.permission.DELETE_CACHE_FILES, null);
6383 // Queue up an async operation since the package deletion may take a little while.
6384 mHandler.post(new Runnable() {
6385 public void run() {
6386 mHandler.removeCallbacks(this);
6387 final boolean succeded;
6388 synchronized (mInstallLock) {
6389 succeded = deleteApplicationCacheFilesLI(packageName);
6390 }
6391 if(observer != null) {
6392 try {
6393 observer.onRemoveCompleted(packageName, succeded);
6394 } catch (RemoteException e) {
6395 Log.i(TAG, "Observer no longer exists.");
6396 }
6397 } //end if observer
6398 } //end run
6399 });
6400 }
6401
6402 private boolean deleteApplicationCacheFilesLI(String packageName) {
6403 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006404 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006405 return false;
6406 }
6407 PackageParser.Package p;
6408 synchronized (mPackages) {
6409 p = mPackages.get(packageName);
6410 }
6411 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006412 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006413 return false;
6414 }
6415 final ApplicationInfo applicationInfo = p.applicationInfo;
6416 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006417 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006418 return false;
6419 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006420 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006422 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006423 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006424 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006425 + packageName);
6426 return false;
6427 }
6428 }
6429 return true;
6430 }
6431
6432 public void getPackageSizeInfo(final String packageName,
6433 final IPackageStatsObserver observer) {
6434 mContext.enforceCallingOrSelfPermission(
6435 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6436 // Queue up an async operation since the package deletion may take a little while.
6437 mHandler.post(new Runnable() {
6438 public void run() {
6439 mHandler.removeCallbacks(this);
6440 PackageStats lStats = new PackageStats(packageName);
6441 final boolean succeded;
6442 synchronized (mInstallLock) {
6443 succeded = getPackageSizeInfoLI(packageName, lStats);
6444 }
6445 if(observer != null) {
6446 try {
6447 observer.onGetStatsCompleted(lStats, succeded);
6448 } catch (RemoteException e) {
6449 Log.i(TAG, "Observer no longer exists.");
6450 }
6451 } //end if observer
6452 } //end run
6453 });
6454 }
6455
6456 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6457 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006458 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006459 return false;
6460 }
6461 PackageParser.Package p;
6462 boolean dataOnly = false;
6463 synchronized (mPackages) {
6464 p = mPackages.get(packageName);
6465 if(p == null) {
6466 dataOnly = true;
6467 PackageSetting ps = mSettings.mPackages.get(packageName);
6468 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006469 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006470 return false;
6471 }
6472 p = ps.pkg;
6473 }
6474 }
6475 String publicSrcDir = null;
6476 if(!dataOnly) {
6477 final ApplicationInfo applicationInfo = p.applicationInfo;
6478 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006479 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006480 return false;
6481 }
6482 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6483 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006484 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006485 if (mInstaller != null) {
6486 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006487 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006488 if (res < 0) {
6489 return false;
6490 } else {
6491 return true;
6492 }
6493 }
6494 return true;
6495 }
6496
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006498 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006499 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 }
6501
6502 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006503 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 }
6505
6506 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006507 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 }
6509
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006510 int getUidTargetSdkVersionLockedLP(int uid) {
6511 Object obj = mSettings.getUserIdLP(uid);
6512 if (obj instanceof SharedUserSetting) {
6513 SharedUserSetting sus = (SharedUserSetting)obj;
6514 final int N = sus.packages.size();
6515 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6516 Iterator<PackageSetting> it = sus.packages.iterator();
6517 int i=0;
6518 while (it.hasNext()) {
6519 PackageSetting ps = it.next();
6520 if (ps.pkg != null) {
6521 int v = ps.pkg.applicationInfo.targetSdkVersion;
6522 if (v < vers) vers = v;
6523 }
6524 }
6525 return vers;
6526 } else if (obj instanceof PackageSetting) {
6527 PackageSetting ps = (PackageSetting)obj;
6528 if (ps.pkg != null) {
6529 return ps.pkg.applicationInfo.targetSdkVersion;
6530 }
6531 }
6532 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6533 }
6534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006535 public void addPreferredActivity(IntentFilter filter, int match,
6536 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006537 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006538 if (mContext.checkCallingOrSelfPermission(
6539 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6540 != PackageManager.PERMISSION_GRANTED) {
6541 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6542 < Build.VERSION_CODES.FROYO) {
6543 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6544 + Binder.getCallingUid());
6545 return;
6546 }
6547 mContext.enforceCallingOrSelfPermission(
6548 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6549 }
6550
6551 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6553 mSettings.mPreferredActivities.addFilter(
6554 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006555 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006556 }
6557 }
6558
Satish Sampath8dbe6122009-06-02 23:35:54 +01006559 public void replacePreferredActivity(IntentFilter filter, int match,
6560 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006561 if (filter.countActions() != 1) {
6562 throw new IllegalArgumentException(
6563 "replacePreferredActivity expects filter to have only 1 action.");
6564 }
6565 if (filter.countCategories() != 1) {
6566 throw new IllegalArgumentException(
6567 "replacePreferredActivity expects filter to have only 1 category.");
6568 }
6569 if (filter.countDataAuthorities() != 0
6570 || filter.countDataPaths() != 0
6571 || filter.countDataSchemes() != 0
6572 || filter.countDataTypes() != 0) {
6573 throw new IllegalArgumentException(
6574 "replacePreferredActivity expects filter to have no data authorities, " +
6575 "paths, schemes or types.");
6576 }
6577 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006578 if (mContext.checkCallingOrSelfPermission(
6579 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6580 != PackageManager.PERMISSION_GRANTED) {
6581 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6582 < Build.VERSION_CODES.FROYO) {
6583 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6584 + Binder.getCallingUid());
6585 return;
6586 }
6587 mContext.enforceCallingOrSelfPermission(
6588 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6589 }
6590
Satish Sampath8dbe6122009-06-02 23:35:54 +01006591 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6592 String action = filter.getAction(0);
6593 String category = filter.getCategory(0);
6594 while (it.hasNext()) {
6595 PreferredActivity pa = it.next();
6596 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6597 it.remove();
6598 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6599 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6600 }
6601 }
6602 addPreferredActivity(filter, match, set, activity);
6603 }
6604 }
6605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006606 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006607 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006608 int uid = Binder.getCallingUid();
6609 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006610 if (pkg == null || pkg.applicationInfo.uid != uid) {
6611 if (mContext.checkCallingOrSelfPermission(
6612 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6613 != PackageManager.PERMISSION_GRANTED) {
6614 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6615 < Build.VERSION_CODES.FROYO) {
6616 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6617 + Binder.getCallingUid());
6618 return;
6619 }
6620 mContext.enforceCallingOrSelfPermission(
6621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6622 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006623 }
6624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006625 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006626 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006627 }
6628 }
6629 }
6630
6631 boolean clearPackagePreferredActivitiesLP(String packageName) {
6632 boolean changed = false;
6633 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6634 while (it.hasNext()) {
6635 PreferredActivity pa = it.next();
6636 if (pa.mActivity.getPackageName().equals(packageName)) {
6637 it.remove();
6638 changed = true;
6639 }
6640 }
6641 return changed;
6642 }
6643
6644 public int getPreferredActivities(List<IntentFilter> outFilters,
6645 List<ComponentName> outActivities, String packageName) {
6646
6647 int num = 0;
6648 synchronized (mPackages) {
6649 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6650 while (it.hasNext()) {
6651 PreferredActivity pa = it.next();
6652 if (packageName == null
6653 || pa.mActivity.getPackageName().equals(packageName)) {
6654 if (outFilters != null) {
6655 outFilters.add(new IntentFilter(pa));
6656 }
6657 if (outActivities != null) {
6658 outActivities.add(pa.mActivity);
6659 }
6660 }
6661 }
6662 }
6663
6664 return num;
6665 }
6666
6667 public void setApplicationEnabledSetting(String appPackageName,
6668 int newState, int flags) {
6669 setEnabledSetting(appPackageName, null, newState, flags);
6670 }
6671
6672 public void setComponentEnabledSetting(ComponentName componentName,
6673 int newState, int flags) {
6674 setEnabledSetting(componentName.getPackageName(),
6675 componentName.getClassName(), newState, flags);
6676 }
6677
6678 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006679 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006680 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6681 || newState == COMPONENT_ENABLED_STATE_ENABLED
6682 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6683 throw new IllegalArgumentException("Invalid new component state: "
6684 + newState);
6685 }
6686 PackageSetting pkgSetting;
6687 final int uid = Binder.getCallingUid();
6688 final int permission = mContext.checkCallingPermission(
6689 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6690 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006691 boolean sendNow = false;
6692 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006693 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006695 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006697 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006699 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006700 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006701 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 }
6703 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006704 "Unknown component: " + packageName
6705 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 }
6707 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6708 throw new SecurityException(
6709 "Permission Denial: attempt to change component state from pid="
6710 + Binder.getCallingPid()
6711 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6712 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006713 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006714 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006715 if (pkgSetting.enabled == newState) {
6716 // Nothing to do
6717 return;
6718 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006719 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006720 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006721 } else {
6722 // We're dealing with a component level state change
6723 switch (newState) {
6724 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006725 if (!pkgSetting.enableComponentLP(className)) {
6726 return;
6727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006728 break;
6729 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006730 if (!pkgSetting.disableComponentLP(className)) {
6731 return;
6732 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006733 break;
6734 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006735 if (!pkgSetting.restoreComponentLP(className)) {
6736 return;
6737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 break;
6739 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006740 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006741 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006742 }
6743 }
6744 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006745 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006746 components = mPendingBroadcasts.get(packageName);
6747 boolean newPackage = components == null;
6748 if (newPackage) {
6749 components = new ArrayList<String>();
6750 }
6751 if (!components.contains(componentName)) {
6752 components.add(componentName);
6753 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006754 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6755 sendNow = true;
6756 // Purge entry from pending broadcast list if another one exists already
6757 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006758 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006759 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006760 if (newPackage) {
6761 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006762 }
6763 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6764 // Schedule a message
6765 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6766 }
6767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006768 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006769
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006770 long callingId = Binder.clearCallingIdentity();
6771 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006772 if (sendNow) {
6773 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006774 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006775 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006776 } finally {
6777 Binder.restoreCallingIdentity(callingId);
6778 }
6779 }
6780
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006781 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006782 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6783 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6784 + " components=" + componentNames);
6785 Bundle extras = new Bundle(4);
6786 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6787 String nameList[] = new String[componentNames.size()];
6788 componentNames.toArray(nameList);
6789 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006790 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6791 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006792 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006793 }
6794
Jacek Surazski65e13172009-04-28 15:26:38 +02006795 public String getInstallerPackageName(String packageName) {
6796 synchronized (mPackages) {
6797 PackageSetting pkg = mSettings.mPackages.get(packageName);
6798 if (pkg == null) {
6799 throw new IllegalArgumentException("Unknown package: " + packageName);
6800 }
6801 return pkg.installerPackageName;
6802 }
6803 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006805 public int getApplicationEnabledSetting(String appPackageName) {
6806 synchronized (mPackages) {
6807 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6808 if (pkg == null) {
6809 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6810 }
6811 return pkg.enabled;
6812 }
6813 }
6814
6815 public int getComponentEnabledSetting(ComponentName componentName) {
6816 synchronized (mPackages) {
6817 final String packageNameStr = componentName.getPackageName();
6818 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6819 if (pkg == null) {
6820 throw new IllegalArgumentException("Unknown component: " + componentName);
6821 }
6822 final String classNameStr = componentName.getClassName();
6823 return pkg.currentEnabledStateLP(classNameStr);
6824 }
6825 }
6826
6827 public void enterSafeMode() {
6828 if (!mSystemReady) {
6829 mSafeMode = true;
6830 }
6831 }
6832
6833 public void systemReady() {
6834 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006835
6836 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006837 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006838 mContext.getContentResolver(),
6839 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006840 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006841 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006842 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006844 }
6845
6846 public boolean isSafeMode() {
6847 return mSafeMode;
6848 }
6849
6850 public boolean hasSystemUidErrors() {
6851 return mHasSystemUidErrors;
6852 }
6853
6854 static String arrayToString(int[] array) {
6855 StringBuffer buf = new StringBuffer(128);
6856 buf.append('[');
6857 if (array != null) {
6858 for (int i=0; i<array.length; i++) {
6859 if (i > 0) buf.append(", ");
6860 buf.append(array[i]);
6861 }
6862 }
6863 buf.append(']');
6864 return buf.toString();
6865 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006867 @Override
6868 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6869 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6870 != PackageManager.PERMISSION_GRANTED) {
6871 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6872 + Binder.getCallingPid()
6873 + ", uid=" + Binder.getCallingUid()
6874 + " without permission "
6875 + android.Manifest.permission.DUMP);
6876 return;
6877 }
6878
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006879 String packageName = null;
6880
6881 int opti = 0;
6882 while (opti < args.length) {
6883 String opt = args[opti];
6884 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6885 break;
6886 }
6887 opti++;
6888 if ("-a".equals(opt)) {
6889 // Right now we only know how to print all.
6890 } else if ("-h".equals(opt)) {
6891 pw.println("Package manager dump options:");
6892 pw.println(" [-h] [cmd] ...");
6893 pw.println(" cmd may be one of:");
6894 pw.println(" [package.name]: info about given package");
6895 return;
6896 } else {
6897 pw.println("Unknown argument: " + opt + "; use -h for help");
6898 }
6899 }
6900
6901 // Is the caller requesting to dump a particular piece of data?
6902 if (opti < args.length) {
6903 String cmd = args[opti];
6904 opti++;
6905 // Is this a package name?
6906 if ("android".equals(cmd) || cmd.contains(".")) {
6907 packageName = cmd;
6908 }
6909 }
6910
6911 boolean printedTitle = false;
6912
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006913 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006914 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6915 printedTitle = true;
6916 }
6917 if (mReceivers.dump(pw, printedTitle
6918 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6919 " ", packageName)) {
6920 printedTitle = true;
6921 }
6922 if (mServices.dump(pw, printedTitle
6923 ? "\nService Resolver Table:" : "Service Resolver Table:",
6924 " ", packageName)) {
6925 printedTitle = true;
6926 }
6927 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6928 ? "\nPreferred Activities:" : "Preferred Activities:",
6929 " ", packageName)) {
6930 printedTitle = true;
6931 }
6932 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006933 {
6934 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006935 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6936 continue;
6937 }
6938 if (!printedSomething) {
6939 if (printedTitle) pw.println(" ");
6940 pw.println("Permissions:");
6941 printedSomething = true;
6942 printedTitle = true;
6943 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006944 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6945 pw.print(Integer.toHexString(System.identityHashCode(p)));
6946 pw.println("):");
6947 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6948 pw.print(" uid="); pw.print(p.uid);
6949 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006950 pw.print(" type="); pw.print(p.type);
6951 pw.print(" prot="); pw.println(p.protectionLevel);
6952 if (p.packageSetting != null) {
6953 pw.print(" packageSetting="); pw.println(p.packageSetting);
6954 }
6955 if (p.perm != null) {
6956 pw.print(" perm="); pw.println(p.perm);
6957 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 }
6959 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006960 printedSomething = false;
6961 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006962 {
6963 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006964 if (packageName != null && !packageName.equals(ps.realName)
6965 && !packageName.equals(ps.name)) {
6966 continue;
6967 }
6968 if (!printedSomething) {
6969 if (printedTitle) pw.println(" ");
6970 pw.println("Packages:");
6971 printedSomething = true;
6972 printedTitle = true;
6973 }
6974 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006975 pw.print(" Package [");
6976 pw.print(ps.realName != null ? ps.realName : ps.name);
6977 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006978 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6979 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006980 if (ps.realName != null) {
6981 pw.print(" compat name="); pw.println(ps.name);
6982 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006983 pw.print(" userId="); pw.print(ps.userId);
6984 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6985 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6986 pw.print(" pkg="); pw.println(ps.pkg);
6987 pw.print(" codePath="); pw.println(ps.codePathString);
6988 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07006989 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07006990 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006991 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006992 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006993 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07006994 if (ps.pkg.mOperationPending) {
6995 pw.println(" mOperationPending=true");
6996 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006997 pw.print(" supportsScreens=[");
6998 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006999 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007000 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
7001 if (!first) pw.print(", ");
7002 first = false;
7003 pw.print("small");
7004 }
7005 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007006 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007007 if (!first) pw.print(", ");
7008 first = false;
7009 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007010 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007011 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007012 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007013 if (!first) pw.print(", ");
7014 first = false;
7015 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007016 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007017 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007018 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007019 if (!first) pw.print(", ");
7020 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007021 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007022 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007023 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007024 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007025 if (!first) pw.print(", ");
7026 first = false;
7027 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007028 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007029 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007030 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7031 if (!first) pw.print(", ");
7032 first = false;
7033 pw.print("anyDensity");
7034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007036 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007037 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7038 pw.print(" signatures="); pw.println(ps.signatures);
7039 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007040 pw.print(" haveGids="); pw.println(ps.haveGids);
7041 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007042 pw.print(" installStatus="); pw.print(ps.installStatus);
7043 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 if (ps.disabledComponents.size() > 0) {
7045 pw.println(" disabledComponents:");
7046 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007047 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007048 }
7049 }
7050 if (ps.enabledComponents.size() > 0) {
7051 pw.println(" enabledComponents:");
7052 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007053 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007054 }
7055 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007056 if (ps.grantedPermissions.size() > 0) {
7057 pw.println(" grantedPermissions:");
7058 for (String s : ps.grantedPermissions) {
7059 pw.print(" "); pw.println(s);
7060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007061 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007062 }
7063 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007064 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007065 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007066 for (HashMap.Entry<String, String> e
7067 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007068 if (packageName != null && !packageName.equals(e.getKey())
7069 && !packageName.equals(e.getValue())) {
7070 continue;
7071 }
7072 if (!printedSomething) {
7073 if (printedTitle) pw.println(" ");
7074 pw.println("Renamed packages:");
7075 printedSomething = true;
7076 printedTitle = true;
7077 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007078 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7079 pw.println(e.getValue());
7080 }
7081 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007082 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007083 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007084 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007085 if (packageName != null && !packageName.equals(ps.realName)
7086 && !packageName.equals(ps.name)) {
7087 continue;
7088 }
7089 if (!printedSomething) {
7090 if (printedTitle) pw.println(" ");
7091 pw.println("Hidden system packages:");
7092 printedSomething = true;
7093 printedTitle = true;
7094 }
7095 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007096 pw.print(ps.realName != null ? ps.realName : ps.name);
7097 pw.print("] (");
7098 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7099 pw.println("):");
7100 if (ps.realName != null) {
7101 pw.print(" compat name="); pw.println(ps.name);
7102 }
7103 pw.print(" userId="); pw.println(ps.userId);
7104 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7105 pw.print(" codePath="); pw.println(ps.codePathString);
7106 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7107 }
7108 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007109 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007110 {
7111 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007112 if (packageName != null && su != packageSharedUser) {
7113 continue;
7114 }
7115 if (!printedSomething) {
7116 if (printedTitle) pw.println(" ");
7117 pw.println("Shared users:");
7118 printedSomething = true;
7119 printedTitle = true;
7120 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007121 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7122 pw.print(Integer.toHexString(System.identityHashCode(su)));
7123 pw.println("):");
7124 pw.print(" userId="); pw.print(su.userId);
7125 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007126 pw.println(" grantedPermissions:");
7127 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007128 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007130 }
7131 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007132
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007133 if (packageName == null) {
7134 if (printedTitle) pw.println(" ");
7135 printedTitle = true;
7136 pw.println("Settings parse messages:");
7137 pw.println(mSettings.mReadMessages.toString());
7138
7139 pw.println(" ");
7140 pw.println("Package warning messages:");
7141 File fname = getSettingsProblemFile();
7142 FileInputStream in;
7143 try {
7144 in = new FileInputStream(fname);
7145 int avail = in.available();
7146 byte[] data = new byte[avail];
7147 in.read(data);
7148 pw.println(new String(data));
7149 } catch (FileNotFoundException e) {
7150 } catch (IOException e) {
7151 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007153 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007154
7155 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007156 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007157 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007158 if (packageName != null && !packageName.equals(p.info.packageName)) {
7159 continue;
7160 }
7161 if (!printedSomething) {
7162 if (printedTitle) pw.println(" ");
7163 pw.println("Registered ContentProviders:");
7164 printedSomething = true;
7165 printedTitle = true;
7166 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007167 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007168 pw.println(p.toString());
7169 }
7170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007171 }
7172
7173 static final class BasePermission {
7174 final static int TYPE_NORMAL = 0;
7175 final static int TYPE_BUILTIN = 1;
7176 final static int TYPE_DYNAMIC = 2;
7177
7178 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007179 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007180 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007181 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007182 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007183 PackageParser.Permission perm;
7184 PermissionInfo pendingInfo;
7185 int uid;
7186 int[] gids;
7187
7188 BasePermission(String _name, String _sourcePackage, int _type) {
7189 name = _name;
7190 sourcePackage = _sourcePackage;
7191 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007192 // Default to most conservative protection level.
7193 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7194 }
7195
7196 public String toString() {
7197 return "BasePermission{"
7198 + Integer.toHexString(System.identityHashCode(this))
7199 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007200 }
7201 }
7202
7203 static class PackageSignatures {
7204 private Signature[] mSignatures;
7205
7206 PackageSignatures(Signature[] sigs) {
7207 assignSignatures(sigs);
7208 }
7209
7210 PackageSignatures() {
7211 }
7212
7213 void writeXml(XmlSerializer serializer, String tagName,
7214 ArrayList<Signature> pastSignatures) throws IOException {
7215 if (mSignatures == null) {
7216 return;
7217 }
7218 serializer.startTag(null, tagName);
7219 serializer.attribute(null, "count",
7220 Integer.toString(mSignatures.length));
7221 for (int i=0; i<mSignatures.length; i++) {
7222 serializer.startTag(null, "cert");
7223 final Signature sig = mSignatures[i];
7224 final int sigHash = sig.hashCode();
7225 final int numPast = pastSignatures.size();
7226 int j;
7227 for (j=0; j<numPast; j++) {
7228 Signature pastSig = pastSignatures.get(j);
7229 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7230 serializer.attribute(null, "index", Integer.toString(j));
7231 break;
7232 }
7233 }
7234 if (j >= numPast) {
7235 pastSignatures.add(sig);
7236 serializer.attribute(null, "index", Integer.toString(numPast));
7237 serializer.attribute(null, "key", sig.toCharsString());
7238 }
7239 serializer.endTag(null, "cert");
7240 }
7241 serializer.endTag(null, tagName);
7242 }
7243
7244 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7245 throws IOException, XmlPullParserException {
7246 String countStr = parser.getAttributeValue(null, "count");
7247 if (countStr == null) {
7248 reportSettingsProblem(Log.WARN,
7249 "Error in package manager settings: <signatures> has"
7250 + " no count at " + parser.getPositionDescription());
7251 XmlUtils.skipCurrentTag(parser);
7252 }
7253 final int count = Integer.parseInt(countStr);
7254 mSignatures = new Signature[count];
7255 int pos = 0;
7256
7257 int outerDepth = parser.getDepth();
7258 int type;
7259 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7260 && (type != XmlPullParser.END_TAG
7261 || parser.getDepth() > outerDepth)) {
7262 if (type == XmlPullParser.END_TAG
7263 || type == XmlPullParser.TEXT) {
7264 continue;
7265 }
7266
7267 String tagName = parser.getName();
7268 if (tagName.equals("cert")) {
7269 if (pos < count) {
7270 String index = parser.getAttributeValue(null, "index");
7271 if (index != null) {
7272 try {
7273 int idx = Integer.parseInt(index);
7274 String key = parser.getAttributeValue(null, "key");
7275 if (key == null) {
7276 if (idx >= 0 && idx < pastSignatures.size()) {
7277 Signature sig = pastSignatures.get(idx);
7278 if (sig != null) {
7279 mSignatures[pos] = pastSignatures.get(idx);
7280 pos++;
7281 } else {
7282 reportSettingsProblem(Log.WARN,
7283 "Error in package manager settings: <cert> "
7284 + "index " + index + " is not defined at "
7285 + parser.getPositionDescription());
7286 }
7287 } else {
7288 reportSettingsProblem(Log.WARN,
7289 "Error in package manager settings: <cert> "
7290 + "index " + index + " is out of bounds at "
7291 + parser.getPositionDescription());
7292 }
7293 } else {
7294 while (pastSignatures.size() <= idx) {
7295 pastSignatures.add(null);
7296 }
7297 Signature sig = new Signature(key);
7298 pastSignatures.set(idx, sig);
7299 mSignatures[pos] = sig;
7300 pos++;
7301 }
7302 } catch (NumberFormatException e) {
7303 reportSettingsProblem(Log.WARN,
7304 "Error in package manager settings: <cert> "
7305 + "index " + index + " is not a number at "
7306 + parser.getPositionDescription());
7307 }
7308 } else {
7309 reportSettingsProblem(Log.WARN,
7310 "Error in package manager settings: <cert> has"
7311 + " no index at " + parser.getPositionDescription());
7312 }
7313 } else {
7314 reportSettingsProblem(Log.WARN,
7315 "Error in package manager settings: too "
7316 + "many <cert> tags, expected " + count
7317 + " at " + parser.getPositionDescription());
7318 }
7319 } else {
7320 reportSettingsProblem(Log.WARN,
7321 "Unknown element under <cert>: "
7322 + parser.getName());
7323 }
7324 XmlUtils.skipCurrentTag(parser);
7325 }
7326
7327 if (pos < count) {
7328 // Should never happen -- there is an error in the written
7329 // settings -- but if it does we don't want to generate
7330 // a bad array.
7331 Signature[] newSigs = new Signature[pos];
7332 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7333 mSignatures = newSigs;
7334 }
7335 }
7336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007337 private void assignSignatures(Signature[] sigs) {
7338 if (sigs == null) {
7339 mSignatures = null;
7340 return;
7341 }
7342 mSignatures = new Signature[sigs.length];
7343 for (int i=0; i<sigs.length; i++) {
7344 mSignatures[i] = sigs[i];
7345 }
7346 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007347
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007348 @Override
7349 public String toString() {
7350 StringBuffer buf = new StringBuffer(128);
7351 buf.append("PackageSignatures{");
7352 buf.append(Integer.toHexString(System.identityHashCode(this)));
7353 buf.append(" [");
7354 if (mSignatures != null) {
7355 for (int i=0; i<mSignatures.length; i++) {
7356 if (i > 0) buf.append(", ");
7357 buf.append(Integer.toHexString(
7358 System.identityHashCode(mSignatures[i])));
7359 }
7360 }
7361 buf.append("]}");
7362 return buf.toString();
7363 }
7364 }
7365
7366 static class PreferredActivity extends IntentFilter {
7367 final int mMatch;
7368 final String[] mSetPackages;
7369 final String[] mSetClasses;
7370 final String[] mSetComponents;
7371 final ComponentName mActivity;
7372 final String mShortActivity;
7373 String mParseError;
7374
7375 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7376 ComponentName activity) {
7377 super(filter);
7378 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7379 mActivity = activity;
7380 mShortActivity = activity.flattenToShortString();
7381 mParseError = null;
7382 if (set != null) {
7383 final int N = set.length;
7384 String[] myPackages = new String[N];
7385 String[] myClasses = new String[N];
7386 String[] myComponents = new String[N];
7387 for (int i=0; i<N; i++) {
7388 ComponentName cn = set[i];
7389 if (cn == null) {
7390 mSetPackages = null;
7391 mSetClasses = null;
7392 mSetComponents = null;
7393 return;
7394 }
7395 myPackages[i] = cn.getPackageName().intern();
7396 myClasses[i] = cn.getClassName().intern();
7397 myComponents[i] = cn.flattenToShortString().intern();
7398 }
7399 mSetPackages = myPackages;
7400 mSetClasses = myClasses;
7401 mSetComponents = myComponents;
7402 } else {
7403 mSetPackages = null;
7404 mSetClasses = null;
7405 mSetComponents = null;
7406 }
7407 }
7408
7409 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7410 IOException {
7411 mShortActivity = parser.getAttributeValue(null, "name");
7412 mActivity = ComponentName.unflattenFromString(mShortActivity);
7413 if (mActivity == null) {
7414 mParseError = "Bad activity name " + mShortActivity;
7415 }
7416 String matchStr = parser.getAttributeValue(null, "match");
7417 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7418 String setCountStr = parser.getAttributeValue(null, "set");
7419 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7420
7421 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7422 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7423 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7424
7425 int setPos = 0;
7426
7427 int outerDepth = parser.getDepth();
7428 int type;
7429 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7430 && (type != XmlPullParser.END_TAG
7431 || parser.getDepth() > outerDepth)) {
7432 if (type == XmlPullParser.END_TAG
7433 || type == XmlPullParser.TEXT) {
7434 continue;
7435 }
7436
7437 String tagName = parser.getName();
7438 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7439 // + parser.getDepth() + " tag=" + tagName);
7440 if (tagName.equals("set")) {
7441 String name = parser.getAttributeValue(null, "name");
7442 if (name == null) {
7443 if (mParseError == null) {
7444 mParseError = "No name in set tag in preferred activity "
7445 + mShortActivity;
7446 }
7447 } else if (setPos >= setCount) {
7448 if (mParseError == null) {
7449 mParseError = "Too many set tags in preferred activity "
7450 + mShortActivity;
7451 }
7452 } else {
7453 ComponentName cn = ComponentName.unflattenFromString(name);
7454 if (cn == null) {
7455 if (mParseError == null) {
7456 mParseError = "Bad set name " + name + " in preferred activity "
7457 + mShortActivity;
7458 }
7459 } else {
7460 myPackages[setPos] = cn.getPackageName();
7461 myClasses[setPos] = cn.getClassName();
7462 myComponents[setPos] = name;
7463 setPos++;
7464 }
7465 }
7466 XmlUtils.skipCurrentTag(parser);
7467 } else if (tagName.equals("filter")) {
7468 //Log.i(TAG, "Starting to parse filter...");
7469 readFromXml(parser);
7470 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7471 // + parser.getDepth() + " tag=" + parser.getName());
7472 } else {
7473 reportSettingsProblem(Log.WARN,
7474 "Unknown element under <preferred-activities>: "
7475 + parser.getName());
7476 XmlUtils.skipCurrentTag(parser);
7477 }
7478 }
7479
7480 if (setPos != setCount) {
7481 if (mParseError == null) {
7482 mParseError = "Not enough set tags (expected " + setCount
7483 + " but found " + setPos + ") in " + mShortActivity;
7484 }
7485 }
7486
7487 mSetPackages = myPackages;
7488 mSetClasses = myClasses;
7489 mSetComponents = myComponents;
7490 }
7491
7492 public void writeToXml(XmlSerializer serializer) throws IOException {
7493 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7494 serializer.attribute(null, "name", mShortActivity);
7495 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7496 serializer.attribute(null, "set", Integer.toString(NS));
7497 for (int s=0; s<NS; s++) {
7498 serializer.startTag(null, "set");
7499 serializer.attribute(null, "name", mSetComponents[s]);
7500 serializer.endTag(null, "set");
7501 }
7502 serializer.startTag(null, "filter");
7503 super.writeToXml(serializer);
7504 serializer.endTag(null, "filter");
7505 }
7506
7507 boolean sameSet(List<ResolveInfo> query, int priority) {
7508 if (mSetPackages == null) return false;
7509 final int NQ = query.size();
7510 final int NS = mSetPackages.length;
7511 int numMatch = 0;
7512 for (int i=0; i<NQ; i++) {
7513 ResolveInfo ri = query.get(i);
7514 if (ri.priority != priority) continue;
7515 ActivityInfo ai = ri.activityInfo;
7516 boolean good = false;
7517 for (int j=0; j<NS; j++) {
7518 if (mSetPackages[j].equals(ai.packageName)
7519 && mSetClasses[j].equals(ai.name)) {
7520 numMatch++;
7521 good = true;
7522 break;
7523 }
7524 }
7525 if (!good) return false;
7526 }
7527 return numMatch == NS;
7528 }
7529 }
7530
7531 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007532 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007534 HashSet<String> grantedPermissions = new HashSet<String>();
7535 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007536
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007537 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007538 setFlags(pkgFlags);
7539 }
7540
7541 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007542 this.pkgFlags = pkgFlags & (
7543 ApplicationInfo.FLAG_SYSTEM |
7544 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007545 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007546 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007547 }
7548 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007549
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007550 /**
7551 * Settings base class for pending and resolved classes.
7552 */
7553 static class PackageSettingBase extends GrantedPermissions {
7554 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007555 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007556 File codePath;
7557 String codePathString;
7558 File resourcePath;
7559 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007560 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007561 String obbPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007562 private long timeStamp;
7563 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007564 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007565
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007566 boolean uidError;
7567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568 PackageSignatures signatures = new PackageSignatures();
7569
7570 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007571 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007572
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007573 /* Explicitly disabled components */
7574 HashSet<String> disabledComponents = new HashSet<String>(0);
7575 /* Explicitly enabled components */
7576 HashSet<String> enabledComponents = new HashSet<String>(0);
7577 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7578 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007579
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007580 PackageSettingBase origPackage;
7581
Jacek Surazski65e13172009-04-28 15:26:38 +02007582 /* package name of the app that installed this package */
7583 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007585 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007586 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007587 super(pkgFlags);
7588 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007589 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007590 init(codePath, resourcePath, pVersionCode);
7591 }
7592
7593 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007594 this.codePath = codePath;
7595 this.codePathString = codePath.toString();
7596 this.resourcePath = resourcePath;
7597 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007598 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007599 }
Kenny Root85387d72010-08-26 10:13:11 -07007600
Jacek Surazski65e13172009-04-28 15:26:38 +02007601 public void setInstallerPackageName(String packageName) {
7602 installerPackageName = packageName;
7603 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007604
Jacek Surazski65e13172009-04-28 15:26:38 +02007605 String getInstallerPackageName() {
7606 return installerPackageName;
7607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 public void setInstallStatus(int newStatus) {
7610 installStatus = newStatus;
7611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 public int getInstallStatus() {
7614 return installStatus;
7615 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007617 public void setTimeStamp(long newStamp) {
7618 if (newStamp != timeStamp) {
7619 timeStamp = newStamp;
7620 timeStampString = Long.toString(newStamp);
7621 }
7622 }
7623
7624 public void setTimeStamp(long newStamp, String newStampStr) {
7625 timeStamp = newStamp;
7626 timeStampString = newStampStr;
7627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 public long getTimeStamp() {
7630 return timeStamp;
7631 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007633 public String getTimeStampStr() {
7634 return timeStampString;
7635 }
7636
7637 public void copyFrom(PackageSettingBase base) {
7638 grantedPermissions = base.grantedPermissions;
7639 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007641 timeStamp = base.timeStamp;
7642 timeStampString = base.timeStampString;
7643 signatures = base.signatures;
7644 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007645 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007646 disabledComponents = base.disabledComponents;
7647 enabledComponents = base.enabledComponents;
7648 enabled = base.enabled;
7649 installStatus = base.installStatus;
7650 }
7651
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007652 boolean enableComponentLP(String componentClassName) {
7653 boolean changed = disabledComponents.remove(componentClassName);
7654 changed |= enabledComponents.add(componentClassName);
7655 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007656 }
7657
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007658 boolean disableComponentLP(String componentClassName) {
7659 boolean changed = enabledComponents.remove(componentClassName);
7660 changed |= disabledComponents.add(componentClassName);
7661 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007662 }
7663
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007664 boolean restoreComponentLP(String componentClassName) {
7665 boolean changed = enabledComponents.remove(componentClassName);
7666 changed |= disabledComponents.remove(componentClassName);
7667 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 }
7669
7670 int currentEnabledStateLP(String componentName) {
7671 if (enabledComponents.contains(componentName)) {
7672 return COMPONENT_ENABLED_STATE_ENABLED;
7673 } else if (disabledComponents.contains(componentName)) {
7674 return COMPONENT_ENABLED_STATE_DISABLED;
7675 } else {
7676 return COMPONENT_ENABLED_STATE_DEFAULT;
7677 }
7678 }
7679 }
7680
7681 /**
7682 * Settings data for a particular package we know about.
7683 */
7684 static final class PackageSetting extends PackageSettingBase {
7685 int userId;
7686 PackageParser.Package pkg;
7687 SharedUserSetting sharedUser;
7688
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007689 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007690 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007691 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007694 @Override
7695 public String toString() {
7696 return "PackageSetting{"
7697 + Integer.toHexString(System.identityHashCode(this))
7698 + " " + name + "/" + userId + "}";
7699 }
7700 }
7701
7702 /**
7703 * Settings data for a particular shared user ID we know about.
7704 */
7705 static final class SharedUserSetting extends GrantedPermissions {
7706 final String name;
7707 int userId;
7708 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7709 final PackageSignatures signatures = new PackageSignatures();
7710
7711 SharedUserSetting(String _name, int _pkgFlags) {
7712 super(_pkgFlags);
7713 name = _name;
7714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007716 @Override
7717 public String toString() {
7718 return "SharedUserSetting{"
7719 + Integer.toHexString(System.identityHashCode(this))
7720 + " " + name + "/" + userId + "}";
7721 }
7722 }
7723
7724 /**
7725 * Holds information about dynamic settings.
7726 */
7727 private static final class Settings {
7728 private final File mSettingsFilename;
7729 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007730 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007731 private final HashMap<String, PackageSetting> mPackages =
7732 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007733 // List of replaced system applications
7734 final HashMap<String, PackageSetting> mDisabledSysPackages =
7735 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007736
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007737 // These are the last platform API version we were using for
7738 // the apps installed on internal and external storage. It is
7739 // used to grant newer permissions one time during a system upgrade.
7740 int mInternalSdkPlatform;
7741 int mExternalSdkPlatform;
7742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007743 // The user's preferred activities associated with particular intent
7744 // filters.
7745 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7746 new IntentResolver<PreferredActivity, PreferredActivity>() {
7747 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007748 protected String packageForFilter(PreferredActivity filter) {
7749 return filter.mActivity.getPackageName();
7750 }
7751 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007752 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007753 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007754 out.print(prefix); out.print(
7755 Integer.toHexString(System.identityHashCode(filter)));
7756 out.print(' ');
7757 out.print(filter.mActivity.flattenToShortString());
7758 out.print(" match=0x");
7759 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007760 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007761 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007762 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007763 out.print(prefix); out.print(" ");
7764 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007765 }
7766 }
7767 }
7768 };
7769 private final HashMap<String, SharedUserSetting> mSharedUsers =
7770 new HashMap<String, SharedUserSetting>();
7771 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7772 private final SparseArray<Object> mOtherUserIds =
7773 new SparseArray<Object>();
7774
7775 // For reading/writing settings file.
7776 private final ArrayList<Signature> mPastSignatures =
7777 new ArrayList<Signature>();
7778
7779 // Mapping from permission names to info about them.
7780 final HashMap<String, BasePermission> mPermissions =
7781 new HashMap<String, BasePermission>();
7782
7783 // Mapping from permission tree names to info about them.
7784 final HashMap<String, BasePermission> mPermissionTrees =
7785 new HashMap<String, BasePermission>();
7786
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007787 // Packages that have been uninstalled and still need their external
7788 // storage data deleted.
7789 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7790
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007791 // Packages that have been renamed since they were first installed.
7792 // Keys are the new names of the packages, values are the original
7793 // names. The packages appear everwhere else under their original
7794 // names.
7795 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007797 private final StringBuilder mReadMessages = new StringBuilder();
7798
7799 private static final class PendingPackage extends PackageSettingBase {
7800 final int sharedId;
7801
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007802 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007803 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007804 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007805 this.sharedId = sharedId;
7806 }
7807 }
7808 private final ArrayList<PendingPackage> mPendingPackages
7809 = new ArrayList<PendingPackage>();
7810
7811 Settings() {
7812 File dataDir = Environment.getDataDirectory();
7813 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007814 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7815 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007816 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007817 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007818 FileUtils.setPermissions(systemDir.toString(),
7819 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7820 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7821 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007822 FileUtils.setPermissions(systemSecureDir.toString(),
7823 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7824 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7825 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 mSettingsFilename = new File(systemDir, "packages.xml");
7827 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007828 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 }
7830
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007831 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007832 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007833 int pkgFlags, boolean create, boolean add) {
7834 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007835 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007836 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007837 return p;
7838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007839
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007840 PackageSetting peekPackageLP(String name) {
7841 return mPackages.get(name);
7842 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007843 PackageSetting p = mPackages.get(name);
7844 if (p != null && p.codePath.getPath().equals(codePath)) {
7845 return p;
7846 }
7847 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007848 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007849 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007851 void setInstallStatus(String pkgName, int status) {
7852 PackageSetting p = mPackages.get(pkgName);
7853 if(p != null) {
7854 if(p.getInstallStatus() != status) {
7855 p.setInstallStatus(status);
7856 }
7857 }
7858 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007859
Jacek Surazski65e13172009-04-28 15:26:38 +02007860 void setInstallerPackageName(String pkgName,
7861 String installerPkgName) {
7862 PackageSetting p = mPackages.get(pkgName);
7863 if(p != null) {
7864 p.setInstallerPackageName(installerPkgName);
7865 }
7866 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007867
Jacek Surazski65e13172009-04-28 15:26:38 +02007868 String getInstallerPackageName(String pkgName) {
7869 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007870 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007871 }
7872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007873 int getInstallStatus(String pkgName) {
7874 PackageSetting p = mPackages.get(pkgName);
7875 if(p != null) {
7876 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007877 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007878 return -1;
7879 }
7880
7881 SharedUserSetting getSharedUserLP(String name,
7882 int pkgFlags, boolean create) {
7883 SharedUserSetting s = mSharedUsers.get(name);
7884 if (s == null) {
7885 if (!create) {
7886 return null;
7887 }
7888 s = new SharedUserSetting(name, pkgFlags);
7889 if (MULTIPLE_APPLICATION_UIDS) {
7890 s.userId = newUserIdLP(s);
7891 } else {
7892 s.userId = FIRST_APPLICATION_UID;
7893 }
7894 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7895 // < 0 means we couldn't assign a userid; fall out and return
7896 // s, which is currently null
7897 if (s.userId >= 0) {
7898 mSharedUsers.put(name, s);
7899 }
7900 }
7901
7902 return s;
7903 }
7904
7905 int disableSystemPackageLP(String name) {
7906 PackageSetting p = mPackages.get(name);
7907 if(p == null) {
7908 Log.w(TAG, "Package:"+name+" is not an installed package");
7909 return -1;
7910 }
7911 PackageSetting dp = mDisabledSysPackages.get(name);
7912 // always make sure the system package code and resource paths dont change
7913 if(dp == null) {
7914 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7915 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7916 }
7917 mDisabledSysPackages.put(name, p);
7918 }
7919 return removePackageLP(name);
7920 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007922 PackageSetting enableSystemPackageLP(String name) {
7923 PackageSetting p = mDisabledSysPackages.get(name);
7924 if(p == null) {
7925 Log.w(TAG, "Package:"+name+" is not disabled");
7926 return null;
7927 }
7928 // Reset flag in ApplicationInfo object
7929 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7930 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7931 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007932 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007933 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007934 mDisabledSysPackages.remove(name);
7935 return ret;
7936 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007937
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007938 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007939 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007940 PackageSetting p = mPackages.get(name);
7941 if (p != null) {
7942 if (p.userId == uid) {
7943 return p;
7944 }
7945 reportSettingsProblem(Log.ERROR,
7946 "Adding duplicate package, keeping first: " + name);
7947 return null;
7948 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007949 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007950 p.userId = uid;
7951 if (addUserIdLP(uid, p, name)) {
7952 mPackages.put(name, p);
7953 return p;
7954 }
7955 return null;
7956 }
7957
7958 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7959 SharedUserSetting s = mSharedUsers.get(name);
7960 if (s != null) {
7961 if (s.userId == uid) {
7962 return s;
7963 }
7964 reportSettingsProblem(Log.ERROR,
7965 "Adding duplicate shared user, keeping first: " + name);
7966 return null;
7967 }
7968 s = new SharedUserSetting(name, pkgFlags);
7969 s.userId = uid;
7970 if (addUserIdLP(uid, s, name)) {
7971 mSharedUsers.put(name, s);
7972 return s;
7973 }
7974 return null;
7975 }
7976
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007977 // Transfer ownership of permissions from one package to another.
7978 private void transferPermissions(String origPkg, String newPkg) {
7979 // Transfer ownership of permissions to the new package.
7980 for (int i=0; i<2; i++) {
7981 HashMap<String, BasePermission> permissions =
7982 i == 0 ? mPermissionTrees : mPermissions;
7983 for (BasePermission bp : permissions.values()) {
7984 if (origPkg.equals(bp.sourcePackage)) {
7985 if (DEBUG_UPGRADE) Log.v(TAG,
7986 "Moving permission " + bp.name
7987 + " from pkg " + bp.sourcePackage
7988 + " to " + newPkg);
7989 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007990 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007991 bp.perm = null;
7992 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007993 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007994 }
7995 bp.uid = 0;
7996 bp.gids = null;
7997 }
7998 }
7999 }
8000 }
8001
8002 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008003 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008004 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008005 PackageSetting p = mPackages.get(name);
8006 if (p != null) {
8007 if (!p.codePath.equals(codePath)) {
8008 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008009 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008010 // This is an updated system app with versions in both system
8011 // and data partition. Just let the most recent version
8012 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008013 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008014 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008015 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008016 // Just a change in the code path is not an issue, but
8017 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008018 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008019 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008020 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008021 }
8022 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008023 reportSettingsProblem(Log.WARN,
8024 "Package " + name + " shared user changed from "
8025 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8026 + " to "
8027 + (sharedUser != null ? sharedUser.name : "<nothing>")
8028 + "; replacing with new");
8029 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008030 } else {
8031 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8032 // If what we are scanning is a system package, then
8033 // make it so, regardless of whether it was previously
8034 // installed only in the data partition.
8035 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8036 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008037 }
8038 }
8039 if (p == null) {
8040 // Create a new PackageSettings entry. this can end up here because
8041 // of code path mismatch or user id mismatch of an updated system partition
8042 if (!create) {
8043 return null;
8044 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008045 if (origPackage != null) {
8046 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008047 p = new PackageSetting(origPackage.name, name, codePath,
8048 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008049 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8050 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008051 // Note that we will retain the new package's signature so
8052 // that we can keep its data.
8053 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008054 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008055 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008056 p.sharedUser = origPackage.sharedUser;
8057 p.userId = origPackage.userId;
8058 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008059 mRenamedPackages.put(name, origPackage.name);
8060 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008061 // Update new package state.
8062 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008063 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008064 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008065 p.setTimeStamp(codePath.lastModified());
8066 p.sharedUser = sharedUser;
8067 if (sharedUser != null) {
8068 p.userId = sharedUser.userId;
8069 } else if (MULTIPLE_APPLICATION_UIDS) {
8070 // Clone the setting here for disabled system packages
8071 PackageSetting dis = mDisabledSysPackages.get(name);
8072 if (dis != null) {
8073 // For disabled packages a new setting is created
8074 // from the existing user id. This still has to be
8075 // added to list of user id's
8076 // Copy signatures from previous setting
8077 if (dis.signatures.mSignatures != null) {
8078 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8079 }
8080 p.userId = dis.userId;
8081 // Clone permissions
8082 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008083 // Clone component info
8084 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8085 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8086 // Add new setting to list of user ids
8087 addUserIdLP(p.userId, p, name);
8088 } else {
8089 // Assign new user id
8090 p.userId = newUserIdLP(p);
8091 }
8092 } else {
8093 p.userId = FIRST_APPLICATION_UID;
8094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008095 }
8096 if (p.userId < 0) {
8097 reportSettingsProblem(Log.WARN,
8098 "Package " + name + " could not be assigned a valid uid");
8099 return null;
8100 }
8101 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008102 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008103 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008104 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008105 }
8106 }
8107 return p;
8108 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008109
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008110 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008111 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008112 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008113 final String codePath = pkg.applicationInfo.sourceDir;
8114 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008115 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008116 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008117 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008118 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008119 p.codePath = new File(codePath);
8120 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008121 }
8122 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008123 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008124 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008125 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008126 p.resourcePath = new File(resourcePath);
8127 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008128 }
Kenny Root85387d72010-08-26 10:13:11 -07008129 // Update the native library path if needed
8130 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8131 if (nativeLibraryPath != null
8132 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8133 p.nativeLibraryPathString = nativeLibraryPath;
8134 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008135 // Update version code if needed
8136 if (pkg.mVersionCode != p.versionCode) {
8137 p.versionCode = pkg.mVersionCode;
8138 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008139 // Update signatures if needed.
8140 if (p.signatures.mSignatures == null) {
8141 p.signatures.assignSignatures(pkg.mSignatures);
8142 }
8143 // If this app defines a shared user id initialize
8144 // the shared user signatures as well.
8145 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8146 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8147 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008148 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8149 }
8150
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008151 // Utility method that adds a PackageSetting to mPackages and
8152 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008153 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008154 SharedUserSetting sharedUser) {
8155 mPackages.put(name, p);
8156 if (sharedUser != null) {
8157 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8158 reportSettingsProblem(Log.ERROR,
8159 "Package " + p.name + " was user "
8160 + p.sharedUser + " but is now " + sharedUser
8161 + "; I am not changing its files so it will probably fail!");
8162 p.sharedUser.packages.remove(p);
8163 } else if (p.userId != sharedUser.userId) {
8164 reportSettingsProblem(Log.ERROR,
8165 "Package " + p.name + " was user id " + p.userId
8166 + " but is now user " + sharedUser
8167 + " with id " + sharedUser.userId
8168 + "; I am not changing its files so it will probably fail!");
8169 }
8170
8171 sharedUser.packages.add(p);
8172 p.sharedUser = sharedUser;
8173 p.userId = sharedUser.userId;
8174 }
8175 }
8176
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008177 /*
8178 * Update the shared user setting when a package using
8179 * specifying the shared user id is removed. The gids
8180 * associated with each permission of the deleted package
8181 * are removed from the shared user's gid list only if its
8182 * not in use by other permissions of packages in the
8183 * shared user setting.
8184 */
8185 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008186 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008187 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008188 return;
8189 }
8190 // No sharedUserId
8191 if (deletedPs.sharedUser == null) {
8192 return;
8193 }
8194 SharedUserSetting sus = deletedPs.sharedUser;
8195 // Update permissions
8196 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8197 boolean used = false;
8198 if (!sus.grantedPermissions.contains (eachPerm)) {
8199 continue;
8200 }
8201 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008202 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008203 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008204 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008205 used = true;
8206 break;
8207 }
8208 }
8209 if (!used) {
8210 // can safely delete this permission from list
8211 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008212 }
8213 }
8214 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008215 int newGids[] = globalGids;
8216 for (String eachPerm : sus.grantedPermissions) {
8217 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008218 if (bp != null) {
8219 newGids = appendInts(newGids, bp.gids);
8220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008221 }
8222 sus.gids = newGids;
8223 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008225 private int removePackageLP(String name) {
8226 PackageSetting p = mPackages.get(name);
8227 if (p != null) {
8228 mPackages.remove(name);
8229 if (p.sharedUser != null) {
8230 p.sharedUser.packages.remove(p);
8231 if (p.sharedUser.packages.size() == 0) {
8232 mSharedUsers.remove(p.sharedUser.name);
8233 removeUserIdLP(p.sharedUser.userId);
8234 return p.sharedUser.userId;
8235 }
8236 } else {
8237 removeUserIdLP(p.userId);
8238 return p.userId;
8239 }
8240 }
8241 return -1;
8242 }
8243
8244 private boolean addUserIdLP(int uid, Object obj, Object name) {
8245 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8246 return false;
8247 }
8248
8249 if (uid >= FIRST_APPLICATION_UID) {
8250 int N = mUserIds.size();
8251 final int index = uid - FIRST_APPLICATION_UID;
8252 while (index >= N) {
8253 mUserIds.add(null);
8254 N++;
8255 }
8256 if (mUserIds.get(index) != null) {
8257 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008258 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008259 + " name=" + name);
8260 return false;
8261 }
8262 mUserIds.set(index, obj);
8263 } else {
8264 if (mOtherUserIds.get(uid) != null) {
8265 reportSettingsProblem(Log.ERROR,
8266 "Adding duplicate shared id: " + uid
8267 + " name=" + name);
8268 return false;
8269 }
8270 mOtherUserIds.put(uid, obj);
8271 }
8272 return true;
8273 }
8274
8275 public Object getUserIdLP(int uid) {
8276 if (uid >= FIRST_APPLICATION_UID) {
8277 int N = mUserIds.size();
8278 final int index = uid - FIRST_APPLICATION_UID;
8279 return index < N ? mUserIds.get(index) : null;
8280 } else {
8281 return mOtherUserIds.get(uid);
8282 }
8283 }
8284
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008285 private Set<String> findPackagesWithFlag(int flag) {
8286 Set<String> ret = new HashSet<String>();
8287 for (PackageSetting ps : mPackages.values()) {
8288 // Has to match atleast all the flag bits set on flag
8289 if ((ps.pkgFlags & flag) == flag) {
8290 ret.add(ps.name);
8291 }
8292 }
8293 return ret;
8294 }
8295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008296 private void removeUserIdLP(int uid) {
8297 if (uid >= FIRST_APPLICATION_UID) {
8298 int N = mUserIds.size();
8299 final int index = uid - FIRST_APPLICATION_UID;
8300 if (index < N) mUserIds.set(index, null);
8301 } else {
8302 mOtherUserIds.remove(uid);
8303 }
8304 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008306 void writeLP() {
8307 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8308
8309 // Keep the old settings around until we know the new ones have
8310 // been successfully written.
8311 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008312 // Presence of backup settings file indicates that we failed
8313 // to persist settings earlier. So preserve the older
8314 // backup for future reference since the current settings
8315 // might have been corrupted.
8316 if (!mBackupSettingsFilename.exists()) {
8317 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008318 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008319 return;
8320 }
8321 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008322 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008323 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008325 }
8326
8327 mPastSignatures.clear();
8328
8329 try {
8330 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8331
8332 //XmlSerializer serializer = XmlUtils.serializerInstance();
8333 XmlSerializer serializer = new FastXmlSerializer();
8334 serializer.setOutput(str, "utf-8");
8335 serializer.startDocument(null, true);
8336 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8337
8338 serializer.startTag(null, "packages");
8339
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008340 serializer.startTag(null, "last-platform-version");
8341 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8342 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8343 serializer.endTag(null, "last-platform-version");
8344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008345 serializer.startTag(null, "permission-trees");
8346 for (BasePermission bp : mPermissionTrees.values()) {
8347 writePermission(serializer, bp);
8348 }
8349 serializer.endTag(null, "permission-trees");
8350
8351 serializer.startTag(null, "permissions");
8352 for (BasePermission bp : mPermissions.values()) {
8353 writePermission(serializer, bp);
8354 }
8355 serializer.endTag(null, "permissions");
8356
8357 for (PackageSetting pkg : mPackages.values()) {
8358 writePackage(serializer, pkg);
8359 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8362 writeDisabledSysPackage(serializer, pkg);
8363 }
8364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008365 serializer.startTag(null, "preferred-activities");
8366 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8367 serializer.startTag(null, "item");
8368 pa.writeToXml(serializer);
8369 serializer.endTag(null, "item");
8370 }
8371 serializer.endTag(null, "preferred-activities");
8372
8373 for (SharedUserSetting usr : mSharedUsers.values()) {
8374 serializer.startTag(null, "shared-user");
8375 serializer.attribute(null, "name", usr.name);
8376 serializer.attribute(null, "userId",
8377 Integer.toString(usr.userId));
8378 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8379 serializer.startTag(null, "perms");
8380 for (String name : usr.grantedPermissions) {
8381 serializer.startTag(null, "item");
8382 serializer.attribute(null, "name", name);
8383 serializer.endTag(null, "item");
8384 }
8385 serializer.endTag(null, "perms");
8386 serializer.endTag(null, "shared-user");
8387 }
8388
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008389 if (mPackagesToBeCleaned.size() > 0) {
8390 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8391 serializer.startTag(null, "cleaning-package");
8392 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8393 serializer.endTag(null, "cleaning-package");
8394 }
8395 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008396
8397 if (mRenamedPackages.size() > 0) {
8398 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8399 serializer.startTag(null, "renamed-package");
8400 serializer.attribute(null, "new", e.getKey());
8401 serializer.attribute(null, "old", e.getValue());
8402 serializer.endTag(null, "renamed-package");
8403 }
8404 }
8405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008406 serializer.endTag(null, "packages");
8407
8408 serializer.endDocument();
8409
8410 str.flush();
8411 str.close();
8412
8413 // New settings successfully written, old ones are no longer
8414 // needed.
8415 mBackupSettingsFilename.delete();
8416 FileUtils.setPermissions(mSettingsFilename.toString(),
8417 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8418 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8419 |FileUtils.S_IROTH,
8420 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008421
8422 // Write package list file now, use a JournaledFile.
8423 //
8424 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8425 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8426
8427 str = new FileOutputStream(journal.chooseForWrite());
8428 try {
8429 StringBuilder sb = new StringBuilder();
8430 for (PackageSetting pkg : mPackages.values()) {
8431 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008432 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008433 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8434
8435 // Avoid any application that has a space in its path
8436 // or that is handled by the system.
8437 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8438 continue;
8439
8440 // we store on each line the following information for now:
8441 //
8442 // pkgName - package name
8443 // userId - application-specific user id
8444 // debugFlag - 0 or 1 if the package is debuggable.
8445 // dataPath - path to package's data path
8446 //
8447 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8448 //
8449 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8450 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8451 // system/core/run-as/run-as.c
8452 //
8453 sb.setLength(0);
8454 sb.append(ai.packageName);
8455 sb.append(" ");
8456 sb.append((int)ai.uid);
8457 sb.append(isDebug ? " 1 " : " 0 ");
8458 sb.append(dataPath);
8459 sb.append("\n");
8460 str.write(sb.toString().getBytes());
8461 }
8462 str.flush();
8463 str.close();
8464 journal.commit();
8465 }
8466 catch (Exception e) {
8467 journal.rollback();
8468 }
8469
8470 FileUtils.setPermissions(mPackageListFilename.toString(),
8471 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8472 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8473 |FileUtils.S_IROTH,
8474 -1, -1);
8475
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008476 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008477
8478 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008479 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 -08008480 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008481 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 -08008482 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008483 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008484 if (mSettingsFilename.exists()) {
8485 if (!mSettingsFilename.delete()) {
8486 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8487 }
8488 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008489 //Debug.stopMethodTracing();
8490 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008491
8492 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008493 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008494 serializer.startTag(null, "updated-package");
8495 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008496 if (pkg.realName != null) {
8497 serializer.attribute(null, "realName", pkg.realName);
8498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008499 serializer.attribute(null, "codePath", pkg.codePathString);
8500 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008501 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008502 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8503 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8504 }
Kenny Root85387d72010-08-26 10:13:11 -07008505 if (pkg.nativeLibraryPathString != null) {
8506 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008508 if (pkg.sharedUser == null) {
8509 serializer.attribute(null, "userId",
8510 Integer.toString(pkg.userId));
8511 } else {
8512 serializer.attribute(null, "sharedUserId",
8513 Integer.toString(pkg.userId));
8514 }
8515 serializer.startTag(null, "perms");
8516 if (pkg.sharedUser == null) {
8517 // If this is a shared user, the permissions will
8518 // be written there. We still need to write an
8519 // empty permissions list so permissionsFixed will
8520 // be set.
8521 for (final String name : pkg.grantedPermissions) {
8522 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008523 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008524 // We only need to write signature or system permissions but this wont
8525 // match the semantics of grantedPermissions. So write all permissions.
8526 serializer.startTag(null, "item");
8527 serializer.attribute(null, "name", name);
8528 serializer.endTag(null, "item");
8529 }
8530 }
8531 }
8532 serializer.endTag(null, "perms");
8533 serializer.endTag(null, "updated-package");
8534 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008535
8536 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008537 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008538 serializer.startTag(null, "package");
8539 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008540 if (pkg.realName != null) {
8541 serializer.attribute(null, "realName", pkg.realName);
8542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 serializer.attribute(null, "codePath", pkg.codePathString);
8544 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8545 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8546 }
Kenny Root85387d72010-08-26 10:13:11 -07008547 if (pkg.nativeLibraryPathString != null) {
8548 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8549 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008550 serializer.attribute(null, "flags",
8551 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008552 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008553 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008554 if (pkg.sharedUser == null) {
8555 serializer.attribute(null, "userId",
8556 Integer.toString(pkg.userId));
8557 } else {
8558 serializer.attribute(null, "sharedUserId",
8559 Integer.toString(pkg.userId));
8560 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008561 if (pkg.uidError) {
8562 serializer.attribute(null, "uidError", "true");
8563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008564 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8565 serializer.attribute(null, "enabled",
8566 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8567 ? "true" : "false");
8568 }
8569 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8570 serializer.attribute(null, "installStatus", "false");
8571 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008572 if (pkg.installerPackageName != null) {
8573 serializer.attribute(null, "installer", pkg.installerPackageName);
8574 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008575 if (pkg.obbPathString != null) {
8576 serializer.attribute(null, "obbPath", pkg.obbPathString);
8577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008578 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8579 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8580 serializer.startTag(null, "perms");
8581 if (pkg.sharedUser == null) {
8582 // If this is a shared user, the permissions will
8583 // be written there. We still need to write an
8584 // empty permissions list so permissionsFixed will
8585 // be set.
8586 for (final String name : pkg.grantedPermissions) {
8587 serializer.startTag(null, "item");
8588 serializer.attribute(null, "name", name);
8589 serializer.endTag(null, "item");
8590 }
8591 }
8592 serializer.endTag(null, "perms");
8593 }
8594 if (pkg.disabledComponents.size() > 0) {
8595 serializer.startTag(null, "disabled-components");
8596 for (final String name : pkg.disabledComponents) {
8597 serializer.startTag(null, "item");
8598 serializer.attribute(null, "name", name);
8599 serializer.endTag(null, "item");
8600 }
8601 serializer.endTag(null, "disabled-components");
8602 }
8603 if (pkg.enabledComponents.size() > 0) {
8604 serializer.startTag(null, "enabled-components");
8605 for (final String name : pkg.enabledComponents) {
8606 serializer.startTag(null, "item");
8607 serializer.attribute(null, "name", name);
8608 serializer.endTag(null, "item");
8609 }
8610 serializer.endTag(null, "enabled-components");
8611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008613 serializer.endTag(null, "package");
8614 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008616 void writePermission(XmlSerializer serializer, BasePermission bp)
8617 throws XmlPullParserException, java.io.IOException {
8618 if (bp.type != BasePermission.TYPE_BUILTIN
8619 && bp.sourcePackage != null) {
8620 serializer.startTag(null, "item");
8621 serializer.attribute(null, "name", bp.name);
8622 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008623 if (bp.protectionLevel !=
8624 PermissionInfo.PROTECTION_NORMAL) {
8625 serializer.attribute(null, "protection",
8626 Integer.toString(bp.protectionLevel));
8627 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008628 if (DEBUG_SETTINGS) Log.v(TAG,
8629 "Writing perm: name=" + bp.name + " type=" + bp.type);
8630 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8631 PermissionInfo pi = bp.perm != null ? bp.perm.info
8632 : bp.pendingInfo;
8633 if (pi != null) {
8634 serializer.attribute(null, "type", "dynamic");
8635 if (pi.icon != 0) {
8636 serializer.attribute(null, "icon",
8637 Integer.toString(pi.icon));
8638 }
8639 if (pi.nonLocalizedLabel != null) {
8640 serializer.attribute(null, "label",
8641 pi.nonLocalizedLabel.toString());
8642 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008643 }
8644 }
8645 serializer.endTag(null, "item");
8646 }
8647 }
8648
8649 String getReadMessagesLP() {
8650 return mReadMessages.toString();
8651 }
8652
Oscar Montemayora8529f62009-11-18 10:14:20 -08008653 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008654 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8655 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008656 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008657 while(its.hasNext()) {
8658 String key = its.next();
8659 PackageSetting ps = mPackages.get(key);
8660 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008661 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008662 }
8663 }
8664 return ret;
8665 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008667 boolean readLP() {
8668 FileInputStream str = null;
8669 if (mBackupSettingsFilename.exists()) {
8670 try {
8671 str = new FileInputStream(mBackupSettingsFilename);
8672 mReadMessages.append("Reading from backup settings file\n");
8673 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008674 if (mSettingsFilename.exists()) {
8675 // If both the backup and settings file exist, we
8676 // ignore the settings since it might have been
8677 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008678 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008679 mSettingsFilename.delete();
8680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008681 } catch (java.io.IOException e) {
8682 // We'll try for the normal settings file.
8683 }
8684 }
8685
8686 mPastSignatures.clear();
8687
8688 try {
8689 if (str == null) {
8690 if (!mSettingsFilename.exists()) {
8691 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008692 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008693 return false;
8694 }
8695 str = new FileInputStream(mSettingsFilename);
8696 }
8697 XmlPullParser parser = Xml.newPullParser();
8698 parser.setInput(str, null);
8699
8700 int type;
8701 while ((type=parser.next()) != XmlPullParser.START_TAG
8702 && type != XmlPullParser.END_DOCUMENT) {
8703 ;
8704 }
8705
8706 if (type != XmlPullParser.START_TAG) {
8707 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008708 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008709 return false;
8710 }
8711
8712 int outerDepth = parser.getDepth();
8713 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8714 && (type != XmlPullParser.END_TAG
8715 || parser.getDepth() > outerDepth)) {
8716 if (type == XmlPullParser.END_TAG
8717 || type == XmlPullParser.TEXT) {
8718 continue;
8719 }
8720
8721 String tagName = parser.getName();
8722 if (tagName.equals("package")) {
8723 readPackageLP(parser);
8724 } else if (tagName.equals("permissions")) {
8725 readPermissionsLP(mPermissions, parser);
8726 } else if (tagName.equals("permission-trees")) {
8727 readPermissionsLP(mPermissionTrees, parser);
8728 } else if (tagName.equals("shared-user")) {
8729 readSharedUserLP(parser);
8730 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008731 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008732 } else if (tagName.equals("preferred-activities")) {
8733 readPreferredActivitiesLP(parser);
8734 } else if(tagName.equals("updated-package")) {
8735 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008736 } else if (tagName.equals("cleaning-package")) {
8737 String name = parser.getAttributeValue(null, "name");
8738 if (name != null) {
8739 mPackagesToBeCleaned.add(name);
8740 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008741 } else if (tagName.equals("renamed-package")) {
8742 String nname = parser.getAttributeValue(null, "new");
8743 String oname = parser.getAttributeValue(null, "old");
8744 if (nname != null && oname != null) {
8745 mRenamedPackages.put(nname, oname);
8746 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008747 } else if (tagName.equals("last-platform-version")) {
8748 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8749 try {
8750 String internal = parser.getAttributeValue(null, "internal");
8751 if (internal != null) {
8752 mInternalSdkPlatform = Integer.parseInt(internal);
8753 }
8754 String external = parser.getAttributeValue(null, "external");
8755 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008756 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008757 }
8758 } catch (NumberFormatException e) {
8759 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008760 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008761 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008762 + parser.getName());
8763 XmlUtils.skipCurrentTag(parser);
8764 }
8765 }
8766
8767 str.close();
8768
8769 } catch(XmlPullParserException e) {
8770 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008771 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008772
8773 } catch(java.io.IOException e) {
8774 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008775 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008776
8777 }
8778
8779 int N = mPendingPackages.size();
8780 for (int i=0; i<N; i++) {
8781 final PendingPackage pp = mPendingPackages.get(i);
8782 Object idObj = getUserIdLP(pp.sharedId);
8783 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008784 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008786 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008787 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008788 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008789 + pp.name);
8790 continue;
8791 }
8792 p.copyFrom(pp);
8793 } else if (idObj != null) {
8794 String msg = "Bad package setting: package " + pp.name
8795 + " has shared uid " + pp.sharedId
8796 + " that is not a shared uid\n";
8797 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008798 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008799 } else {
8800 String msg = "Bad package setting: package " + pp.name
8801 + " has shared uid " + pp.sharedId
8802 + " that is not defined\n";
8803 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008804 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008805 }
8806 }
8807 mPendingPackages.clear();
8808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008809 mReadMessages.append("Read completed successfully: "
8810 + mPackages.size() + " packages, "
8811 + mSharedUsers.size() + " shared uids\n");
8812
8813 return true;
8814 }
8815
8816 private int readInt(XmlPullParser parser, String ns, String name,
8817 int defValue) {
8818 String v = parser.getAttributeValue(ns, name);
8819 try {
8820 if (v == null) {
8821 return defValue;
8822 }
8823 return Integer.parseInt(v);
8824 } catch (NumberFormatException e) {
8825 reportSettingsProblem(Log.WARN,
8826 "Error in package manager settings: attribute " +
8827 name + " has bad integer value " + v + " at "
8828 + parser.getPositionDescription());
8829 }
8830 return defValue;
8831 }
8832
8833 private void readPermissionsLP(HashMap<String, BasePermission> out,
8834 XmlPullParser parser)
8835 throws IOException, XmlPullParserException {
8836 int outerDepth = parser.getDepth();
8837 int type;
8838 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8839 && (type != XmlPullParser.END_TAG
8840 || parser.getDepth() > outerDepth)) {
8841 if (type == XmlPullParser.END_TAG
8842 || type == XmlPullParser.TEXT) {
8843 continue;
8844 }
8845
8846 String tagName = parser.getName();
8847 if (tagName.equals("item")) {
8848 String name = parser.getAttributeValue(null, "name");
8849 String sourcePackage = parser.getAttributeValue(null, "package");
8850 String ptype = parser.getAttributeValue(null, "type");
8851 if (name != null && sourcePackage != null) {
8852 boolean dynamic = "dynamic".equals(ptype);
8853 BasePermission bp = new BasePermission(name, sourcePackage,
8854 dynamic
8855 ? BasePermission.TYPE_DYNAMIC
8856 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008857 bp.protectionLevel = readInt(parser, null, "protection",
8858 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008859 if (dynamic) {
8860 PermissionInfo pi = new PermissionInfo();
8861 pi.packageName = sourcePackage.intern();
8862 pi.name = name.intern();
8863 pi.icon = readInt(parser, null, "icon", 0);
8864 pi.nonLocalizedLabel = parser.getAttributeValue(
8865 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008866 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008867 bp.pendingInfo = pi;
8868 }
8869 out.put(bp.name, bp);
8870 } else {
8871 reportSettingsProblem(Log.WARN,
8872 "Error in package manager settings: permissions has"
8873 + " no name at " + parser.getPositionDescription());
8874 }
8875 } else {
8876 reportSettingsProblem(Log.WARN,
8877 "Unknown element reading permissions: "
8878 + parser.getName() + " at "
8879 + parser.getPositionDescription());
8880 }
8881 XmlUtils.skipCurrentTag(parser);
8882 }
8883 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008886 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008888 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008889 String codePathStr = parser.getAttributeValue(null, "codePath");
8890 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008891 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008892 resourcePathStr = codePathStr;
8893 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008894 String version = parser.getAttributeValue(null, "version");
8895 int versionCode = 0;
8896 if (version != null) {
8897 try {
8898 versionCode = Integer.parseInt(version);
8899 } catch (NumberFormatException e) {
8900 }
8901 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008903 int pkgFlags = 0;
8904 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008905 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008906 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008907 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008908 String timeStampStr = parser.getAttributeValue(null, "ts");
8909 if (timeStampStr != null) {
8910 try {
8911 long timeStamp = Long.parseLong(timeStampStr);
8912 ps.setTimeStamp(timeStamp, timeStampStr);
8913 } catch (NumberFormatException e) {
8914 }
8915 }
8916 String idStr = parser.getAttributeValue(null, "userId");
8917 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8918 if(ps.userId <= 0) {
8919 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8920 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8921 }
8922 int outerDepth = parser.getDepth();
8923 int type;
8924 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8925 && (type != XmlPullParser.END_TAG
8926 || parser.getDepth() > outerDepth)) {
8927 if (type == XmlPullParser.END_TAG
8928 || type == XmlPullParser.TEXT) {
8929 continue;
8930 }
8931
8932 String tagName = parser.getName();
8933 if (tagName.equals("perms")) {
8934 readGrantedPermissionsLP(parser,
8935 ps.grantedPermissions);
8936 } else {
8937 reportSettingsProblem(Log.WARN,
8938 "Unknown element under <updated-package>: "
8939 + parser.getName());
8940 XmlUtils.skipCurrentTag(parser);
8941 }
8942 }
8943 mDisabledSysPackages.put(name, ps);
8944 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008945
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 private void readPackageLP(XmlPullParser parser)
8947 throws XmlPullParserException, IOException {
8948 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008949 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008950 String idStr = null;
8951 String sharedIdStr = null;
8952 String codePathStr = null;
8953 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07008954 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07008955 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008956 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008957 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008958 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008959 int pkgFlags = 0;
8960 String timeStampStr;
8961 long timeStamp = 0;
8962 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008963 String version = null;
8964 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008965 try {
8966 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008967 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008968 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008969 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008970 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8971 codePathStr = parser.getAttributeValue(null, "codePath");
8972 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07008973 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07008974 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008975 version = parser.getAttributeValue(null, "version");
8976 if (version != null) {
8977 try {
8978 versionCode = Integer.parseInt(version);
8979 } catch (NumberFormatException e) {
8980 }
8981 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008982 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008983
8984 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008986 try {
8987 pkgFlags = Integer.parseInt(systemStr);
8988 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008989 }
8990 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008991 // For backward compatibility
8992 systemStr = parser.getAttributeValue(null, "system");
8993 if (systemStr != null) {
8994 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8995 } else {
8996 // Old settings that don't specify system... just treat
8997 // them as system, good enough.
8998 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009000 }
9001 timeStampStr = parser.getAttributeValue(null, "ts");
9002 if (timeStampStr != null) {
9003 try {
9004 timeStamp = Long.parseLong(timeStampStr);
9005 } catch (NumberFormatException e) {
9006 }
9007 }
9008 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9009 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9010 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9011 if (resourcePathStr == null) {
9012 resourcePathStr = codePathStr;
9013 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009014 if (realName != null) {
9015 realName = realName.intern();
9016 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009017 if (name == null) {
9018 reportSettingsProblem(Log.WARN,
9019 "Error in package manager settings: <package> has no name at "
9020 + parser.getPositionDescription());
9021 } else if (codePathStr == null) {
9022 reportSettingsProblem(Log.WARN,
9023 "Error in package manager settings: <package> has no codePath at "
9024 + parser.getPositionDescription());
9025 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009026 packageSetting = addPackageLP(name.intern(), realName,
9027 new File(codePathStr), new File(resourcePathStr),
9028 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009029 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9030 + ": userId=" + userId + " pkg=" + packageSetting);
9031 if (packageSetting == null) {
9032 reportSettingsProblem(Log.ERROR,
9033 "Failure adding uid " + userId
9034 + " while parsing settings at "
9035 + parser.getPositionDescription());
9036 } else {
9037 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9038 }
9039 } else if (sharedIdStr != null) {
9040 userId = sharedIdStr != null
9041 ? Integer.parseInt(sharedIdStr) : 0;
9042 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009043 packageSetting = new PendingPackage(name.intern(), realName,
9044 new File(codePathStr), new File(resourcePathStr),
9045 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009046 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9047 mPendingPackages.add((PendingPackage) packageSetting);
9048 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9049 + ": sharedUserId=" + userId + " pkg="
9050 + packageSetting);
9051 } else {
9052 reportSettingsProblem(Log.WARN,
9053 "Error in package manager settings: package "
9054 + name + " has bad sharedId " + sharedIdStr
9055 + " at " + parser.getPositionDescription());
9056 }
9057 } else {
9058 reportSettingsProblem(Log.WARN,
9059 "Error in package manager settings: package "
9060 + name + " has bad userId " + idStr + " at "
9061 + parser.getPositionDescription());
9062 }
9063 } catch (NumberFormatException e) {
9064 reportSettingsProblem(Log.WARN,
9065 "Error in package manager settings: package "
9066 + name + " has bad userId " + idStr + " at "
9067 + parser.getPositionDescription());
9068 }
9069 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009070 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009071 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009072 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009073 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009074 final String enabledStr = parser.getAttributeValue(null, "enabled");
9075 if (enabledStr != null) {
9076 if (enabledStr.equalsIgnoreCase("true")) {
9077 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9078 } else if (enabledStr.equalsIgnoreCase("false")) {
9079 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9080 } else if (enabledStr.equalsIgnoreCase("default")) {
9081 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9082 } else {
9083 reportSettingsProblem(Log.WARN,
9084 "Error in package manager settings: package "
9085 + name + " has bad enabled value: " + idStr
9086 + " at " + parser.getPositionDescription());
9087 }
9088 } else {
9089 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9090 }
9091 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9092 if (installStatusStr != null) {
9093 if (installStatusStr.equalsIgnoreCase("false")) {
9094 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9095 } else {
9096 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9097 }
9098 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009099
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009100 int outerDepth = parser.getDepth();
9101 int type;
9102 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9103 && (type != XmlPullParser.END_TAG
9104 || parser.getDepth() > outerDepth)) {
9105 if (type == XmlPullParser.END_TAG
9106 || type == XmlPullParser.TEXT) {
9107 continue;
9108 }
9109
9110 String tagName = parser.getName();
9111 if (tagName.equals("disabled-components")) {
9112 readDisabledComponentsLP(packageSetting, parser);
9113 } else if (tagName.equals("enabled-components")) {
9114 readEnabledComponentsLP(packageSetting, parser);
9115 } else if (tagName.equals("sigs")) {
9116 packageSetting.signatures.readXml(parser, mPastSignatures);
9117 } else if (tagName.equals("perms")) {
9118 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009119 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009120 packageSetting.permissionsFixed = true;
9121 } else {
9122 reportSettingsProblem(Log.WARN,
9123 "Unknown element under <package>: "
9124 + parser.getName());
9125 XmlUtils.skipCurrentTag(parser);
9126 }
9127 }
9128 } else {
9129 XmlUtils.skipCurrentTag(parser);
9130 }
9131 }
9132
9133 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9134 XmlPullParser parser)
9135 throws IOException, XmlPullParserException {
9136 int outerDepth = parser.getDepth();
9137 int type;
9138 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9139 && (type != XmlPullParser.END_TAG
9140 || parser.getDepth() > outerDepth)) {
9141 if (type == XmlPullParser.END_TAG
9142 || type == XmlPullParser.TEXT) {
9143 continue;
9144 }
9145
9146 String tagName = parser.getName();
9147 if (tagName.equals("item")) {
9148 String name = parser.getAttributeValue(null, "name");
9149 if (name != null) {
9150 packageSetting.disabledComponents.add(name.intern());
9151 } else {
9152 reportSettingsProblem(Log.WARN,
9153 "Error in package manager settings: <disabled-components> has"
9154 + " no name at " + parser.getPositionDescription());
9155 }
9156 } else {
9157 reportSettingsProblem(Log.WARN,
9158 "Unknown element under <disabled-components>: "
9159 + parser.getName());
9160 }
9161 XmlUtils.skipCurrentTag(parser);
9162 }
9163 }
9164
9165 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9166 XmlPullParser parser)
9167 throws IOException, XmlPullParserException {
9168 int outerDepth = parser.getDepth();
9169 int type;
9170 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9171 && (type != XmlPullParser.END_TAG
9172 || parser.getDepth() > outerDepth)) {
9173 if (type == XmlPullParser.END_TAG
9174 || type == XmlPullParser.TEXT) {
9175 continue;
9176 }
9177
9178 String tagName = parser.getName();
9179 if (tagName.equals("item")) {
9180 String name = parser.getAttributeValue(null, "name");
9181 if (name != null) {
9182 packageSetting.enabledComponents.add(name.intern());
9183 } else {
9184 reportSettingsProblem(Log.WARN,
9185 "Error in package manager settings: <enabled-components> has"
9186 + " no name at " + parser.getPositionDescription());
9187 }
9188 } else {
9189 reportSettingsProblem(Log.WARN,
9190 "Unknown element under <enabled-components>: "
9191 + parser.getName());
9192 }
9193 XmlUtils.skipCurrentTag(parser);
9194 }
9195 }
9196
9197 private void readSharedUserLP(XmlPullParser parser)
9198 throws XmlPullParserException, IOException {
9199 String name = null;
9200 String idStr = null;
9201 int pkgFlags = 0;
9202 SharedUserSetting su = null;
9203 try {
9204 name = parser.getAttributeValue(null, "name");
9205 idStr = parser.getAttributeValue(null, "userId");
9206 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9207 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9208 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9209 }
9210 if (name == null) {
9211 reportSettingsProblem(Log.WARN,
9212 "Error in package manager settings: <shared-user> has no name at "
9213 + parser.getPositionDescription());
9214 } else if (userId == 0) {
9215 reportSettingsProblem(Log.WARN,
9216 "Error in package manager settings: shared-user "
9217 + name + " has bad userId " + idStr + " at "
9218 + parser.getPositionDescription());
9219 } else {
9220 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9221 reportSettingsProblem(Log.ERROR,
9222 "Occurred while parsing settings at "
9223 + parser.getPositionDescription());
9224 }
9225 }
9226 } catch (NumberFormatException e) {
9227 reportSettingsProblem(Log.WARN,
9228 "Error in package manager settings: package "
9229 + name + " has bad userId " + idStr + " at "
9230 + parser.getPositionDescription());
9231 };
9232
9233 if (su != null) {
9234 int outerDepth = parser.getDepth();
9235 int type;
9236 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9237 && (type != XmlPullParser.END_TAG
9238 || parser.getDepth() > outerDepth)) {
9239 if (type == XmlPullParser.END_TAG
9240 || type == XmlPullParser.TEXT) {
9241 continue;
9242 }
9243
9244 String tagName = parser.getName();
9245 if (tagName.equals("sigs")) {
9246 su.signatures.readXml(parser, mPastSignatures);
9247 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009248 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009249 } else {
9250 reportSettingsProblem(Log.WARN,
9251 "Unknown element under <shared-user>: "
9252 + parser.getName());
9253 XmlUtils.skipCurrentTag(parser);
9254 }
9255 }
9256
9257 } else {
9258 XmlUtils.skipCurrentTag(parser);
9259 }
9260 }
9261
9262 private void readGrantedPermissionsLP(XmlPullParser parser,
9263 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9264 int outerDepth = parser.getDepth();
9265 int type;
9266 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9267 && (type != XmlPullParser.END_TAG
9268 || parser.getDepth() > outerDepth)) {
9269 if (type == XmlPullParser.END_TAG
9270 || type == XmlPullParser.TEXT) {
9271 continue;
9272 }
9273
9274 String tagName = parser.getName();
9275 if (tagName.equals("item")) {
9276 String name = parser.getAttributeValue(null, "name");
9277 if (name != null) {
9278 outPerms.add(name.intern());
9279 } else {
9280 reportSettingsProblem(Log.WARN,
9281 "Error in package manager settings: <perms> has"
9282 + " no name at " + parser.getPositionDescription());
9283 }
9284 } else {
9285 reportSettingsProblem(Log.WARN,
9286 "Unknown element under <perms>: "
9287 + parser.getName());
9288 }
9289 XmlUtils.skipCurrentTag(parser);
9290 }
9291 }
9292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009293 private void readPreferredActivitiesLP(XmlPullParser parser)
9294 throws XmlPullParserException, IOException {
9295 int outerDepth = parser.getDepth();
9296 int type;
9297 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9298 && (type != XmlPullParser.END_TAG
9299 || parser.getDepth() > outerDepth)) {
9300 if (type == XmlPullParser.END_TAG
9301 || type == XmlPullParser.TEXT) {
9302 continue;
9303 }
9304
9305 String tagName = parser.getName();
9306 if (tagName.equals("item")) {
9307 PreferredActivity pa = new PreferredActivity(parser);
9308 if (pa.mParseError == null) {
9309 mPreferredActivities.addFilter(pa);
9310 } else {
9311 reportSettingsProblem(Log.WARN,
9312 "Error in package manager settings: <preferred-activity> "
9313 + pa.mParseError + " at "
9314 + parser.getPositionDescription());
9315 }
9316 } else {
9317 reportSettingsProblem(Log.WARN,
9318 "Unknown element under <preferred-activities>: "
9319 + parser.getName());
9320 XmlUtils.skipCurrentTag(parser);
9321 }
9322 }
9323 }
9324
9325 // Returns -1 if we could not find an available UserId to assign
9326 private int newUserIdLP(Object obj) {
9327 // Let's be stupidly inefficient for now...
9328 final int N = mUserIds.size();
9329 for (int i=0; i<N; i++) {
9330 if (mUserIds.get(i) == null) {
9331 mUserIds.set(i, obj);
9332 return FIRST_APPLICATION_UID + i;
9333 }
9334 }
9335
9336 // None left?
9337 if (N >= MAX_APPLICATION_UIDS) {
9338 return -1;
9339 }
9340
9341 mUserIds.add(obj);
9342 return FIRST_APPLICATION_UID + N;
9343 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009344
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009345 public PackageSetting getDisabledSystemPkg(String name) {
9346 synchronized(mPackages) {
9347 PackageSetting ps = mDisabledSysPackages.get(name);
9348 return ps;
9349 }
9350 }
9351
9352 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009353 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9354 return true;
9355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009356 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9357 if (Config.LOGV) {
9358 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9359 + " componentName = " + componentInfo.name);
9360 Log.v(TAG, "enabledComponents: "
9361 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9362 Log.v(TAG, "disabledComponents: "
9363 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9364 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009365 if (packageSettings == null) {
9366 if (false) {
9367 Log.w(TAG, "WAITING FOR DEBUGGER");
9368 Debug.waitForDebugger();
9369 Log.i(TAG, "We will crash!");
9370 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009371 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009372 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009373 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9374 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9375 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9376 return false;
9377 }
9378 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9379 return true;
9380 }
9381 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9382 return false;
9383 }
9384 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009385 }
9386 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009387
9388 // ------- apps on sdcard specific code -------
9389 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009390 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9391 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9392 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009393 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009394
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009395 private String getEncryptKey() {
9396 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009397 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9398 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009399 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009400 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9401 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009402 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009403 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009404 return null;
9405 }
9406 }
9407 return sdEncKey;
9408 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009409 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009410 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009411 } catch (IOException ioe) {
9412 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9413 + ioe);
9414 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009415 }
Rich Cannings8d578832010-09-09 15:12:40 -07009416
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009417 }
9418
Kenny Rootc78a8072010-07-27 15:18:38 -07009419 /* package */ static String getTempContainerId() {
9420 int tmpIdx = 1;
9421 String list[] = PackageHelper.getSecureContainerList();
9422 if (list != null) {
9423 for (final String name : list) {
9424 // Ignore null and non-temporary container entries
9425 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9426 continue;
9427 }
9428
9429 String subStr = name.substring(mTempContainerPrefix.length());
9430 try {
9431 int cid = Integer.parseInt(subStr);
9432 if (cid >= tmpIdx) {
9433 tmpIdx = cid + 1;
9434 }
9435 } catch (NumberFormatException e) {
9436 }
9437 }
9438 }
9439 return mTempContainerPrefix + tmpIdx;
9440 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009441
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009442 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009443 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009444 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009445 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9446 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9447 throw new SecurityException("Media status can only be updated by the system");
9448 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009449 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009450 Log.i(TAG, "Updating external media status from " +
9451 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9452 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009453 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9454 mediaStatus+", mMediaMounted=" + mMediaMounted);
9455 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009456 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9457 reportStatus ? 1 : 0, -1);
9458 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009459 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009460 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009461 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009462 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009463 // Queue up an async operation since the package installation may take a little while.
9464 mHandler.post(new Runnable() {
9465 public void run() {
9466 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009467 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009468 }
9469 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009470 }
9471
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009472 /*
9473 * Collect information of applications on external media, map them
9474 * against existing containers and update information based on current
9475 * mount status. Please note that we always have to report status
9476 * if reportStatus has been set to true especially when unloading packages.
9477 */
9478 private void updateExternalMediaStatusInner(boolean mediaStatus,
9479 boolean reportStatus) {
9480 // Collection of uids
9481 int uidArr[] = null;
9482 // Collection of stale containers
9483 HashSet<String> removeCids = new HashSet<String>();
9484 // Collection of packages on external media with valid containers.
9485 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9486 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009487 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009488 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009489 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009490 } else {
9491 // Process list of secure containers and categorize them
9492 // as active or stale based on their package internal state.
9493 int uidList[] = new int[list.length];
9494 int num = 0;
9495 synchronized (mPackages) {
9496 for (String cid : list) {
9497 SdInstallArgs args = new SdInstallArgs(cid);
9498 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009499 String pkgName = args.getPackageName();
9500 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009501 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9502 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009503 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009504 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009505 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9506 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009507 // The package status is changed only if the code path
9508 // matches between settings and the container id.
9509 if (ps != null && ps.codePathString != null &&
9510 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009511 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9512 " corresponds to pkg : " + pkgName +
9513 " at code path: " + ps.codePathString);
9514 // We do have a valid package installed on sdcard
9515 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009516 int uid = ps.userId;
9517 if (uid != -1) {
9518 uidList[num++] = uid;
9519 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009520 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009521 // Stale container on sdcard. Just delete
9522 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9523 removeCids.add(cid);
9524 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009525 }
9526 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009527
9528 if (num > 0) {
9529 // Sort uid list
9530 Arrays.sort(uidList, 0, num);
9531 // Throw away duplicates
9532 uidArr = new int[num];
9533 uidArr[0] = uidList[0];
9534 int di = 0;
9535 for (int i = 1; i < num; i++) {
9536 if (uidList[i-1] != uidList[i]) {
9537 uidArr[di++] = uidList[i];
9538 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009539 }
9540 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009541 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009542 // Process packages with valid entries.
9543 if (mediaStatus) {
9544 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009545 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009546 startCleaningPackages();
9547 } else {
9548 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009549 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009550 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009551 }
9552
9553 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009554 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009555 int size = pkgList.size();
9556 if (size > 0) {
9557 // Send broadcasts here
9558 Bundle extras = new Bundle();
9559 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9560 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009561 if (uidArr != null) {
9562 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9563 }
9564 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9565 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009566 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009567 }
9568 }
9569
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009570 /*
9571 * Look at potentially valid container ids from processCids
9572 * If package information doesn't match the one on record
9573 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009574 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009575 */
9576 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009577 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009578 ArrayList<String> pkgList = new ArrayList<String>();
9579 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009580 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009581 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009582 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009583 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9584 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009585 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009586 try {
9587 // Make sure there are no container errors first.
9588 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9589 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009590 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009591 " when installing from sdcard");
9592 continue;
9593 }
9594 // Check code path here.
9595 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009596 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009597 " does not match one in settings " + codePath);
9598 continue;
9599 }
9600 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009601 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009602 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009603 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009604 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9605 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009606 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009607 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009608 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009609 retCode = PackageManager.INSTALL_SUCCEEDED;
9610 pkgList.add(pkg.packageName);
9611 // Post process args
9612 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9613 }
9614 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009615 Slog.i(TAG, "Failed to install pkg from " +
9616 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009617 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009618 }
9619
9620 } finally {
9621 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9622 // Don't destroy container here. Wait till gc clears things up.
9623 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009624 }
9625 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009626 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009627 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009628 // If the platform SDK has changed since the last time we booted,
9629 // we need to re-grant app permission to catch any new ones that
9630 // appear. This is really a hack, and means that apps can in some
9631 // cases get permissions that the user didn't initially explicitly
9632 // allow... it would be nice to have some better way to handle
9633 // this situation.
9634 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9635 != mSdkVersion;
9636 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9637 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9638 + "; regranting permissions for external storage");
9639 mSettings.mExternalSdkPlatform = mSdkVersion;
9640
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009641 // Make sure group IDs have been assigned, and any permission
9642 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009643 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009644 // Persist settings
9645 mSettings.writeLP();
9646 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009647 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009648 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009649 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009650 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009651 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009652 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009653 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009654 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009655 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009656 if (removeCids != null) {
9657 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009658 if (cid.startsWith(mTempContainerPrefix)) {
9659 Log.i(TAG, "Destroying stale temporary container " + cid);
9660 PackageHelper.destroySdDir(cid);
9661 } else {
9662 Log.w(TAG, "Container " + cid + " is stale");
9663 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009664 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009665 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009666 }
9667
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009668 /*
9669 * Utility method to unload a list of specified containers
9670 */
9671 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9672 // Just unmount all valid containers.
9673 for (SdInstallArgs arg : cidArgs) {
9674 synchronized (mInstallLock) {
9675 arg.doPostDeleteLI(false);
9676 }
9677 }
9678 }
9679
9680 /*
9681 * Unload packages mounted on external media. This involves deleting
9682 * package data from internal structures, sending broadcasts about
9683 * diabled packages, gc'ing to free up references, unmounting all
9684 * secure containers corresponding to packages on external media, and
9685 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9686 * Please note that we always have to post this message if status has
9687 * been requested no matter what.
9688 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009689 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009690 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009691 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009692 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009693 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009694 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009695 for (SdInstallArgs args : keys) {
9696 String cid = args.cid;
9697 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009698 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009699 // Delete package internally
9700 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9701 synchronized (mInstallLock) {
9702 boolean res = deletePackageLI(pkgName, false,
9703 PackageManager.DONT_DELETE_DATA, outInfo);
9704 if (res) {
9705 pkgList.add(pkgName);
9706 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009707 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009708 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009709 }
9710 }
9711 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009712 // We have to absolutely send UPDATED_MEDIA_STATUS only
9713 // after confirming that all the receivers processed the ordered
9714 // broadcast when packages get disabled, force a gc to clean things up.
9715 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009716 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009717 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9718 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9719 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009720 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9721 reportStatus ? 1 : 0, 1, keys);
9722 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009723 }
9724 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009725 } else {
9726 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9727 reportStatus ? 1 : 0, -1, keys);
9728 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009729 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009730 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009731
9732 public void movePackage(final String packageName,
9733 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009734 mContext.enforceCallingOrSelfPermission(
9735 android.Manifest.permission.MOVE_PACKAGE, null);
9736 int returnCode = PackageManager.MOVE_SUCCEEDED;
9737 int currFlags = 0;
9738 int newFlags = 0;
9739 synchronized (mPackages) {
9740 PackageParser.Package pkg = mPackages.get(packageName);
9741 if (pkg == null) {
9742 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009743 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009744 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009745 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009746 Slog.w(TAG, "Cannot move system application");
9747 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009748 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009749 Slog.w(TAG, "Cannot move forward locked app.");
9750 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009751 } else if (pkg.mOperationPending) {
9752 Slog.w(TAG, "Attempt to move package which has pending operations");
9753 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009754 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009755 // Find install location first
9756 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9757 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9758 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009759 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009760 } else {
9761 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9762 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009763 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9764 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009765 if (newFlags == currFlags) {
9766 Slog.w(TAG, "No move required. Trying to move to same location");
9767 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9768 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009769 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009770 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9771 pkg.mOperationPending = true;
9772 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009773 }
9774 }
9775 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009776 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009777 } else {
9778 Message msg = mHandler.obtainMessage(INIT_COPY);
9779 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009780 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9781 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9782 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009783 msg.obj = mp;
9784 mHandler.sendMessage(msg);
9785 }
9786 }
9787 }
9788
9789 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9790 // Queue up an async operation since the package deletion may take a little while.
9791 mHandler.post(new Runnable() {
9792 public void run() {
9793 mHandler.removeCallbacks(this);
9794 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009795 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9796 int uidArr[] = null;
9797 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009798 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009799 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009800 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009801 Slog.w(TAG, " Package " + mp.packageName +
9802 " doesn't exist. Aborting move");
9803 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9804 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9805 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9806 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9807 " Aborting move and returning error");
9808 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9809 } else {
9810 uidArr = new int[] { pkg.applicationInfo.uid };
9811 pkgList = new ArrayList<String>();
9812 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009813 }
9814 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009815 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9816 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009817 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009818 // Update package code and resource paths
9819 synchronized (mInstallLock) {
9820 synchronized (mPackages) {
9821 PackageParser.Package pkg = mPackages.get(mp.packageName);
9822 // Recheck for package again.
9823 if (pkg == null ) {
9824 Slog.w(TAG, " Package " + mp.packageName +
9825 " doesn't exist. Aborting move");
9826 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9827 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9828 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9829 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9830 " Aborting move and returning error");
9831 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9832 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009833 final String oldCodePath = pkg.mPath;
9834 final String newCodePath = mp.targetArgs.getCodePath();
9835 final String newResPath = mp.targetArgs.getResourcePath();
9836 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009837 pkg.mPath = newCodePath;
9838 // Move dex files around
9839 if (moveDexFilesLI(pkg)
9840 != PackageManager.INSTALL_SUCCEEDED) {
9841 // Moving of dex files failed. Set
9842 // error code and abort move.
9843 pkg.mPath = pkg.mScanPath;
9844 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9845 } else {
9846 pkg.mScanPath = newCodePath;
9847 pkg.applicationInfo.sourceDir = newCodePath;
9848 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009849 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009850 PackageSetting ps = (PackageSetting) pkg.mExtras;
9851 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9852 ps.codePathString = ps.codePath.getPath();
9853 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9854 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009855 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009856 // Set the application info flag correctly.
9857 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9858 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9859 } else {
9860 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9861 }
9862 ps.setFlags(pkg.applicationInfo.flags);
9863 mAppDirs.remove(oldCodePath);
9864 mAppDirs.put(newCodePath, pkg);
9865 // Persist settings
9866 mSettings.writeLP();
9867 }
9868 }
9869 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009870 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009871 // Send resources available broadcast
9872 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009873 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009874 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009875 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009876 // Clean up failed installation
9877 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009878 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009879 }
9880 } else {
9881 // Force a gc to clear things up.
9882 Runtime.getRuntime().gc();
9883 // Delete older code
9884 synchronized (mInstallLock) {
9885 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009886 }
9887 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009888
9889 // Allow more operations on this file if we didn't fail because
9890 // an operation was already pending for this package.
9891 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9892 synchronized (mPackages) {
9893 PackageParser.Package pkg = mPackages.get(mp.packageName);
9894 if (pkg != null) {
9895 pkg.mOperationPending = false;
9896 }
9897 }
9898 }
9899
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009900 IPackageMoveObserver observer = mp.observer;
9901 if (observer != null) {
9902 try {
9903 observer.packageMoved(mp.packageName, returnCode);
9904 } catch (RemoteException e) {
9905 Log.i(TAG, "Observer no longer exists.");
9906 }
9907 }
9908 }
9909 });
9910 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009911
9912 public boolean setInstallLocation(int loc) {
9913 mContext.enforceCallingOrSelfPermission(
9914 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9915 if (getInstallLocation() == loc) {
9916 return true;
9917 }
9918 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9919 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9920 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9921 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9922 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9923 return true;
9924 }
9925 return false;
9926 }
9927
9928 public int getInstallLocation() {
9929 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9930 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009932}