blob: 1141fdcea7be1a4f1d6d9b071ae4a23001bdfdd4 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
57import android.content.pm.PackageStats;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
94import java.io.File;
95import java.io.FileDescriptor;
96import java.io.FileInputStream;
97import java.io.FileNotFoundException;
98import java.io.FileOutputStream;
99import java.io.FileReader;
100import java.io.FilenameFilter;
101import java.io.IOException;
102import java.io.InputStream;
103import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800104import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800105import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.ArrayList;
107import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700108import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Collections;
110import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800111import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import java.util.Enumeration;
113import java.util.HashMap;
114import java.util.HashSet;
115import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700116import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import java.util.List;
118import java.util.Map;
119import java.util.Set;
120import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800121import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import java.util.zip.ZipFile;
123import java.util.zip.ZipOutputStream;
124
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700125/**
126 * Keep track of all those .apks everywhere.
127 *
128 * This is very central to the platform's security; please run the unit
129 * tests whenever making modifications here:
130 *
131mmm frameworks/base/tests/AndroidTests
132adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
133adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
134 *
135 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136class PackageManagerService extends IPackageManager.Stub {
137 private static final String TAG = "PackageManager";
138 private static final boolean DEBUG_SETTINGS = false;
139 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800140 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800141 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700142 private static final boolean DEBUG_NATIVE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
145 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400146 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 private static final int FIRST_APPLICATION_UID =
148 Process.FIRST_APPLICATION_UID;
149 private static final int MAX_APPLICATION_UIDS = 1000;
150
151 private static final boolean SHOW_INFO = false;
152
153 private static final boolean GET_CERTIFICATES = true;
154
Oscar Montemayora8529f62009-11-18 10:14:20 -0800155 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private static final int REMOVE_EVENTS =
158 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
159 private static final int ADD_EVENTS =
160 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
161
162 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800163 // Suffix used during package installation when copying/moving
164 // package apks to install directory.
165 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800167 /**
168 * Indicates the state of installation. Used by PackageManager to
169 * figure out incomplete installations. Say a package is being installed
170 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
171 * the package installation is successful or unsuccesful lin which case
172 * the PackageManager will no longer maintain state information associated
173 * with the package. If some exception(like device freeze or battery being
174 * pulled out) occurs during installation of a package, the PackageManager
175 * needs this information to clean up the previously failed installation.
176 */
177 private static final int PKG_INSTALL_INCOMPLETE = 0;
178 private static final int PKG_INSTALL_COMPLETE = 1;
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final int SCAN_MONITOR = 1<<0;
181 static final int SCAN_NO_DEX = 1<<1;
182 static final int SCAN_FORCE_DEX = 1<<2;
183 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800184 static final int SCAN_NEW_INSTALL = 1<<4;
185 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700187 static final int REMOVE_CHATTY = 1<<16;
188
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800189 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
190 "com.android.defcontainer",
191 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700192
Kenny Root85387d72010-08-26 10:13:11 -0700193 private static final String LIB_DIR_NAME = "lib";
194
Kenny Rootc78a8072010-07-27 15:18:38 -0700195 static final String mTempContainerPrefix = "smdl2tmp";
196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
198 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700199 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Dianne Hackborn851a5412009-05-08 12:06:44 -0700201 final int mSdkVersion = Build.VERSION.SDK_INT;
202 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
203 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 final Context mContext;
206 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700207 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 final DisplayMetrics mMetrics;
209 final int mDefParseFlags;
210 final String[] mSeparateProcesses;
211
212 // This is where all application persistent data goes.
213 final File mAppDataDir;
214
Oscar Montemayora8529f62009-11-18 10:14:20 -0800215 // If Encrypted File System feature is enabled, all application persistent data
216 // should go here instead.
217 final File mSecureAppDataDir;
218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 // This is the object monitoring the framework dir.
220 final FileObserver mFrameworkInstallObserver;
221
222 // This is the object monitoring the system app dir.
223 final FileObserver mSystemInstallObserver;
224
225 // This is the object monitoring mAppInstallDir.
226 final FileObserver mAppInstallObserver;
227
228 // This is the object monitoring mDrmAppPrivateInstallDir.
229 final FileObserver mDrmAppInstallObserver;
230
231 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
232 // LOCK HELD. Can be called with mInstallLock held.
233 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 final File mFrameworkDir;
236 final File mSystemAppDir;
237 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700238 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
241 // apps.
242 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 // Lock for state used when installing and doing other long running
247 // operations. Methods that must be called with this lock held have
248 // the prefix "LI".
249 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // These are the directories in the 3rd party applications installed dir
252 // that we have currently loaded packages from. Keys are the application's
253 // installed zip file (absolute codePath), and values are Package.
254 final HashMap<String, PackageParser.Package> mAppDirs =
255 new HashMap<String, PackageParser.Package>();
256
257 // Information for the parser to write more useful error messages.
258 File mScanningPath;
259 int mLastScanError;
260
261 final int[] mOutPermissions = new int[3];
262
263 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 // Keys are String (package name), values are Package. This also serves
266 // as the lock for the global state. Methods that must be called with
267 // this lock held have the prefix "LP".
268 final HashMap<String, PackageParser.Package> mPackages =
269 new HashMap<String, PackageParser.Package>();
270
271 final Settings mSettings;
272 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273
274 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
275 int[] mGlobalGids;
276
277 // These are the built-in uid -> permission mappings that were read from the
278 // etc/permissions.xml file.
279 final SparseArray<HashSet<String>> mSystemPermissions =
280 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 // These are the built-in shared libraries that were read from the
283 // etc/permissions.xml file.
284 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800285
Dianne Hackborn49237342009-08-27 20:08:01 -0700286 // Temporary for building the final shared libraries for an .apk.
287 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800288
Dianne Hackborn49237342009-08-27 20:08:01 -0700289 // These are the features this devices supports that were read from the
290 // etc/permissions.xml file.
291 final HashMap<String, FeatureInfo> mAvailableFeatures =
292 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 // All available activities, for your resolving pleasure.
295 final ActivityIntentResolver mActivities =
296 new ActivityIntentResolver();
297
298 // All available receivers, for your resolving pleasure.
299 final ActivityIntentResolver mReceivers =
300 new ActivityIntentResolver();
301
302 // All available services, for your resolving pleasure.
303 final ServiceIntentResolver mServices = new ServiceIntentResolver();
304
305 // Keys are String (provider class name), values are Provider.
306 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
307 new HashMap<ComponentName, PackageParser.Provider>();
308
309 // Mapping from provider base names (first directory in content URI codePath)
310 // to the provider information.
311 final HashMap<String, PackageParser.Provider> mProviders =
312 new HashMap<String, PackageParser.Provider>();
313
314 // Mapping from instrumentation class names to info about them.
315 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
316 new HashMap<ComponentName, PackageParser.Instrumentation>();
317
318 // Mapping from permission names to info about them.
319 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
320 new HashMap<String, PackageParser.PermissionGroup>();
321
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800322 // Packages whose data we have transfered into another package, thus
323 // should no longer exist.
324 final HashSet<String> mTransferedPackages = new HashSet<String>();
325
Dianne Hackborn854060af2009-07-09 18:14:31 -0700326 // Broadcast actions that are only available to the system.
327 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 boolean mSystemReady;
330 boolean mSafeMode;
331 boolean mHasSystemUidErrors;
332
333 ApplicationInfo mAndroidApplication;
334 final ActivityInfo mResolveActivity = new ActivityInfo();
335 final ResolveInfo mResolveInfo = new ResolveInfo();
336 ComponentName mResolveComponentName;
337 PackageParser.Package mPlatformPackage;
338
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700339 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800340 final HashMap<String, ArrayList<String>> mPendingBroadcasts
341 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800342 // Service Connection to remote media container service to copy
343 // package uri's from external media onto secure containers
344 // or internal storage.
345 private IMediaContainerService mContainerService = null;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800348 static final int MCS_BOUND = 3;
349 static final int END_COPY = 4;
350 static final int INIT_COPY = 5;
351 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800352 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800353 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800354 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800355 static final int MCS_RECONNECT = 10;
356 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700357 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700358 static final int WRITE_SETTINGS = 13;
359
360 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800361
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700362 // Delay time in millisecs
363 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800364 final private DefaultContainerConnection mDefContainerConn =
365 new DefaultContainerConnection();
366 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800367 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800368 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800369 IMediaContainerService imcs =
370 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800371 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800372 }
373
374 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 }
377 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378
Christopher Tate1bb69062010-02-19 17:02:12 -0800379 // Recordkeeping of restore-after-install operations that are currently in flight
380 // between the Package Manager and the Backup Manager
381 class PostInstallData {
382 public InstallArgs args;
383 public PackageInstalledInfo res;
384
385 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
386 args = _a;
387 res = _r;
388 }
389 };
390 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
391 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
392
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700393 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800394 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800395 final ArrayList<HandlerParams> mPendingInstalls =
396 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397
398 private boolean connectToService() {
399 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
400 " DefaultContainerService");
401 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700402 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800403 if (mContext.bindService(service, mDefContainerConn,
404 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406 mBound = true;
407 return true;
408 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 return false;
411 }
412
413 private void disconnectService() {
414 mContainerService = null;
415 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700416 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800417 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800419 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800420
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 PackageHandler(Looper looper) {
422 super(looper);
423 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700424
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700425 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700426 try {
427 doHandleMessage(msg);
428 } finally {
429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
430 }
431 }
432
433 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700434 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800435 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800436 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800437 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800438 int idx = mPendingInstalls.size();
439 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
440 // If a bind was already initiated we dont really
441 // need to do anything. The pending install
442 // will be processed later on.
443 if (!mBound) {
444 // If this is the only one pending we might
445 // have to bind to the service again.
446 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800447 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800448 params.serviceError();
449 return;
450 } else {
451 // Once we bind to the service, the first
452 // pending request will be processed.
453 mPendingInstalls.add(idx, params);
454 }
455 } else {
456 mPendingInstalls.add(idx, params);
457 // Already bound to the service. Just make
458 // sure we trigger off processing the first request.
459 if (idx == 0) {
460 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800461 }
462 }
463 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800464 }
465 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800466 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800467 if (msg.obj != null) {
468 mContainerService = (IMediaContainerService) msg.obj;
469 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (mContainerService == null) {
471 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800472 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800473 for (HandlerParams params : mPendingInstalls) {
474 mPendingInstalls.remove(0);
475 // Indicate service bind error
476 params.serviceError();
477 }
478 mPendingInstalls.clear();
479 } else if (mPendingInstalls.size() > 0) {
480 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800481 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800482 params.startCopy();
483 }
484 } else {
485 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800486 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 }
488 break;
489 }
490 case MCS_RECONNECT : {
491 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
492 if (mPendingInstalls.size() > 0) {
493 if (mBound) {
494 disconnectService();
495 }
496 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800497 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800498 for (HandlerParams params : mPendingInstalls) {
499 mPendingInstalls.remove(0);
500 // Indicate service bind error
501 params.serviceError();
502 }
503 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800504 }
505 }
506 break;
507 }
508 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800509 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
510 // Delete pending install
511 if (mPendingInstalls.size() > 0) {
512 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800513 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800514 if (mPendingInstalls.size() == 0) {
515 if (mBound) {
516 disconnectService();
517 }
518 } else {
519 // There are more pending requests in queue.
520 // Just post MCS_BOUND message to trigger processing
521 // of next pending install.
522 mHandler.sendEmptyMessage(MCS_BOUND);
523 }
524 break;
525 }
526 case MCS_GIVE_UP: {
527 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
528 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800529 break;
530 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800532 String packages[];
533 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700534 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700536 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800538 if (mPendingBroadcasts == null) {
539 return;
540 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 size = mPendingBroadcasts.size();
542 if (size <= 0) {
543 // Nothing to be done. Just return
544 return;
545 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800546 packages = new String[size];
547 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700548 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800549 Iterator<HashMap.Entry<String, ArrayList<String>>>
550 it = mPendingBroadcasts.entrySet().iterator();
551 int i = 0;
552 while (it.hasNext() && i < size) {
553 HashMap.Entry<String, ArrayList<String>> ent = it.next();
554 packages[i] = ent.getKey();
555 components[i] = ent.getValue();
556 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700557 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800558 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700559 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800560 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700561 mPendingBroadcasts.clear();
562 }
563 // Send broadcasts
564 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800565 sendPackageChangedBroadcast(packages[i], true,
566 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700567 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700569 break;
570 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800571 case START_CLEANING_PACKAGE: {
572 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800574 synchronized (mPackages) {
575 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
576 mSettings.mPackagesToBeCleaned.add(packageName);
577 }
578 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800580 startCleaningPackages();
581 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800582 case POST_INSTALL: {
583 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
584 PostInstallData data = mRunningInstalls.get(msg.arg1);
585 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700586 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800587
588 if (data != null) {
589 InstallArgs args = data.args;
590 PackageInstalledInfo res = data.res;
591
592 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700593 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 Bundle extras = new Bundle(1);
595 extras.putInt(Intent.EXTRA_UID, res.uid);
596 final boolean update = res.removedInfo.removedPackage != null;
597 if (update) {
598 extras.putBoolean(Intent.EXTRA_REPLACING, true);
599 }
600 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
601 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700602 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800603 if (update) {
604 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
605 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700606 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800607 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700608 if (res.removedInfo.args != null) {
609 // Remove the replaced package's older resources safely now
610 deleteOld = true;
611 }
612 }
613 // Force a gc to clear up things
614 Runtime.getRuntime().gc();
615 // We delete after a gc for applications on sdcard.
616 if (deleteOld) {
617 synchronized (mInstallLock) {
618 res.removedInfo.args.doPostDeleteLI(true);
619 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800620 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800621 if (args.observer != null) {
622 try {
623 args.observer.packageInstalled(res.name, res.returnCode);
624 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800625 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800626 }
627 }
628 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800629 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800630 }
631 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700632 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700633 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
634 boolean reportStatus = msg.arg1 == 1;
635 boolean doGc = msg.arg2 == 1;
636 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
637 if (doGc) {
638 // Force a gc to clear up stale containers.
639 Runtime.getRuntime().gc();
640 }
641 if (msg.obj != null) {
642 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
644 // Unload containers
645 unloadAllContainers(args);
646 }
647 if (reportStatus) {
648 try {
649 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
650 PackageHelper.getMountService().finishMediaUpdate();
651 } catch (RemoteException e) {
652 Log.e(TAG, "MountService not running?");
653 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700654 }
655 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700656 case WRITE_SETTINGS: {
657 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
658 synchronized (mPackages) {
659 removeMessages(WRITE_SETTINGS);
660 mSettings.writeLP();
661 }
662 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
663 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700664 }
665 }
666 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800667
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700668 void scheduleWriteSettingsLocked() {
669 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
670 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
671 }
672 }
673
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800674 static boolean installOnSd(int flags) {
675 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700676 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800677 return false;
678 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700679 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
680 return true;
681 }
682 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800683 }
684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 public static final IPackageManager main(Context context, boolean factoryTest) {
686 PackageManagerService m = new PackageManagerService(context, factoryTest);
687 ServiceManager.addService("package", m);
688 return m;
689 }
690
691 static String[] splitString(String str, char sep) {
692 int count = 1;
693 int i = 0;
694 while ((i=str.indexOf(sep, i)) >= 0) {
695 count++;
696 i++;
697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 String[] res = new String[count];
700 i=0;
701 count = 0;
702 int lastI=0;
703 while ((i=str.indexOf(sep, i)) >= 0) {
704 res[count] = str.substring(lastI, i);
705 count++;
706 i++;
707 lastI = i;
708 }
709 res[count] = str.substring(lastI, str.length());
710 return res;
711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800718 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 mContext = context;
722 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700723 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 mMetrics = new DisplayMetrics();
725 mSettings = new Settings();
726 mSettings.addSharedUserLP("android.uid.system",
727 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
728 mSettings.addSharedUserLP("android.uid.phone",
729 MULTIPLE_APPLICATION_UIDS
730 ? RADIO_UID : FIRST_APPLICATION_UID,
731 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400732 mSettings.addSharedUserLP("android.uid.log",
733 MULTIPLE_APPLICATION_UIDS
734 ? LOG_UID : FIRST_APPLICATION_UID,
735 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736
737 String separateProcesses = SystemProperties.get("debug.separate_processes");
738 if (separateProcesses != null && separateProcesses.length() > 0) {
739 if ("*".equals(separateProcesses)) {
740 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
741 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800742 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 } else {
744 mDefParseFlags = 0;
745 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800746 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 + separateProcesses);
748 }
749 } else {
750 mDefParseFlags = 0;
751 mSeparateProcesses = null;
752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 Installer installer = new Installer();
755 // Little hacky thing to check if installd is here, to determine
756 // whether we are running on the simulator and thus need to take
757 // care of building the /data file structure ourself.
758 // (apparently the sim now has a working installer)
759 if (installer.ping() && Process.supportsProcesses()) {
760 mInstaller = installer;
761 } else {
762 mInstaller = null;
763 }
764
765 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
766 Display d = wm.getDefaultDisplay();
767 d.getMetrics(mMetrics);
768
769 synchronized (mInstallLock) {
770 synchronized (mPackages) {
771 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700772 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 File dataDir = Environment.getDataDirectory();
775 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800776 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
778
779 if (mInstaller == null) {
780 // Make sure these dirs exist, when we are running in
781 // the simulator.
782 // Make a wide-open directory for random misc stuff.
783 File miscDir = new File(dataDir, "misc");
784 miscDir.mkdirs();
785 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800786 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 mDrmAppPrivateInstallDir.mkdirs();
788 }
789
790 readPermissions();
791
792 mRestoredSettings = mSettings.readLP();
793 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800794
795 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800798 // Set flag to monitor and not change apk file paths when
799 // scanning install directories.
800 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700801 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800802 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800803 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700804 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700809 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700812 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 /**
815 * Out of paranoia, ensure that everything in the boot class
816 * path has been dexed.
817 */
818 String bootClassPath = System.getProperty("java.boot.class.path");
819 if (bootClassPath != null) {
820 String[] paths = splitString(bootClassPath, ':');
821 for (int i=0; i<paths.length; i++) {
822 try {
823 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
824 libFiles.add(paths[i]);
825 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700826 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 }
828 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800829 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800831 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833 }
834 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800835 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 /**
839 * Also ensure all external libraries have had dexopt run on them.
840 */
841 if (mSharedLibraries.size() > 0) {
842 Iterator<String> libs = mSharedLibraries.values().iterator();
843 while (libs.hasNext()) {
844 String lib = libs.next();
845 try {
846 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
847 libFiles.add(lib);
848 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700849 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
851 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800852 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800854 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 }
857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 // Gross hack for now: we know this file doesn't contain any
860 // code, so don't dexopt it to avoid the resulting log spew.
861 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 /**
864 * And there are a number of commands implemented in Java, which
865 * we currently need to do the dexopt on so that they can be
866 * run from a non-root shell.
867 */
868 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700869 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 for (int i=0; i<frameworkFiles.length; i++) {
871 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
872 String path = libPath.getPath();
873 // Skip the file if we alrady did it.
874 if (libFiles.contains(path)) {
875 continue;
876 }
877 // Skip the file if it is not a type we want to dexopt.
878 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
879 continue;
880 }
881 try {
882 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
883 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700884 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800887 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800889 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
891 }
892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700894 if (didDexOpt) {
895 // If we had to do a dexopt of one of the previous
896 // things, then something on the system has changed.
897 // Consider this significant, and wipe away all other
898 // existing dexopt files to ensure we don't leave any
899 // dangling around.
900 String[] files = mDalvikCacheDir.list();
901 if (files != null) {
902 for (int i=0; i<files.length; i++) {
903 String fn = files[i];
904 if (fn.startsWith("data@app@")
905 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800906 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700907 (new File(mDalvikCacheDir, fn)).delete();
908 }
909 }
910 }
911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800913
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800914 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 mFrameworkInstallObserver = new AppDirObserver(
916 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
917 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700918 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
919 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800920 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800921
922 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
924 mSystemInstallObserver = new AppDirObserver(
925 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
926 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700927 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
928 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800929
930 if (mInstaller != null) {
931 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
932 mInstaller.moveFiles();
933 }
934
935 // Prune any system packages that no longer exist.
936 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
937 while (psit.hasNext()) {
938 PackageSetting ps = psit.next();
939 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800940 && !mPackages.containsKey(ps.name)
941 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800942 psit.remove();
943 String msg = "System package " + ps.name
944 + " no longer exists; wiping its data";
945 reportSettingsProblem(Log.WARN, msg);
946 if (mInstaller != null) {
947 // XXX how to set useEncryptedFSDir for packages that
948 // are not encrypted?
949 mInstaller.remove(ps.name, true);
950 }
951 }
952 }
953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 mAppInstallDir = new File(dataDir, "app");
955 if (mInstaller == null) {
956 // Make sure these dirs exist, when we are running in
957 // the simulator.
958 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
959 }
960 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800961 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 //clean up list
963 for(int i = 0; i < deletePkgsList.size(); i++) {
964 //clean up here
965 cleanupInstallFailedPackage(deletePkgsList.get(i));
966 }
967 //delete tmp files
968 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800969
970 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 SystemClock.uptimeMillis());
972 mAppInstallObserver = new AppDirObserver(
973 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
974 mAppInstallObserver.startWatching();
975 scanDirLI(mAppInstallDir, 0, scanMode);
976
977 mDrmAppInstallObserver = new AppDirObserver(
978 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
979 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800980 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800984 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 + ((SystemClock.uptimeMillis()-startTime)/1000f)
986 + " seconds");
987
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700988 // If the platform SDK has changed since the last time we booted,
989 // we need to re-grant app permission to catch any new ones that
990 // appear. This is really a hack, and means that apps can in some
991 // cases get permissions that the user didn't initially explicitly
992 // allow... it would be nice to have some better way to handle
993 // this situation.
994 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
995 != mSdkVersion;
996 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
997 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
998 + "; regranting permissions for internal storage");
999 mSettings.mInternalSdkPlatform = mSdkVersion;
1000
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001001 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002
1003 mSettings.writeLP();
1004
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001005 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 // Now after opening every single application zip, make sure they
1009 // are all flushed. Not really needed, but keeps things nice and
1010 // tidy.
1011 Runtime.getRuntime().gc();
1012 } // synchronized (mPackages)
1013 } // synchronized (mInstallLock)
1014 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 @Override
1017 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1018 throws RemoteException {
1019 try {
1020 return super.onTransact(code, data, reply, flags);
1021 } catch (RuntimeException e) {
1022 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001023 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025 throw e;
1026 }
1027 }
1028
Dianne Hackborne6620b22010-01-22 14:46:21 -08001029 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001030 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001032 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1033 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001035 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001036 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038 } else {
1039 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001040 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 File dataDir = new File(pkg.applicationInfo.dataDir);
1042 dataDir.delete();
1043 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001044 if (ps.codePath != null) {
1045 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001046 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001047 }
1048 }
1049 if (ps.resourcePath != null) {
1050 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001052 }
1053 }
1054 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
1056
1057 void readPermissions() {
1058 // Read permissions from .../etc/permission directory.
1059 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1060 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001061 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 return;
1063 }
1064 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001065 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 return;
1067 }
1068
1069 // Iterate over the files in the directory and scan .xml files
1070 for (File f : libraryDir.listFiles()) {
1071 // We'll read platform.xml last
1072 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1073 continue;
1074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001077 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 continue;
1079 }
1080 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001081 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 continue;
1083 }
1084
1085 readPermissionsFromXml(f);
1086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1089 final File permFile = new File(Environment.getRootDirectory(),
1090 "etc/permissions/platform.xml");
1091 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001093 StringBuilder sb = new StringBuilder(128);
1094 sb.append("Libs:");
1095 Iterator<String> it = mSharedLibraries.keySet().iterator();
1096 while (it.hasNext()) {
1097 sb.append(' ');
1098 String name = it.next();
1099 sb.append(name);
1100 sb.append(':');
1101 sb.append(mSharedLibraries.get(name));
1102 }
1103 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001104
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001105 sb.setLength(0);
1106 sb.append("Features:");
1107 it = mAvailableFeatures.keySet().iterator();
1108 while (it.hasNext()) {
1109 sb.append(' ');
1110 sb.append(it.next());
1111 }
1112 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
1115 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 FileReader permReader = null;
1117 try {
1118 permReader = new FileReader(permFile);
1119 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001120 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 return;
1122 }
1123
1124 try {
1125 XmlPullParser parser = Xml.newPullParser();
1126 parser.setInput(permReader);
1127
1128 XmlUtils.beginDocument(parser, "permissions");
1129
1130 while (true) {
1131 XmlUtils.nextElement(parser);
1132 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1133 break;
1134 }
1135
1136 String name = parser.getName();
1137 if ("group".equals(name)) {
1138 String gidStr = parser.getAttributeValue(null, "gid");
1139 if (gidStr != null) {
1140 int gid = Integer.parseInt(gidStr);
1141 mGlobalGids = appendInt(mGlobalGids, gid);
1142 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + parser.getPositionDescription());
1145 }
1146
1147 XmlUtils.skipCurrentTag(parser);
1148 continue;
1149 } else if ("permission".equals(name)) {
1150 String perm = parser.getAttributeValue(null, "name");
1151 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 + parser.getPositionDescription());
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157 perm = perm.intern();
1158 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 } else if ("assign-permission".equals(name)) {
1161 String perm = parser.getAttributeValue(null, "name");
1162 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001163 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 + parser.getPositionDescription());
1165 XmlUtils.skipCurrentTag(parser);
1166 continue;
1167 }
1168 String uidStr = parser.getAttributeValue(null, "uid");
1169 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001170 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 + parser.getPositionDescription());
1172 XmlUtils.skipCurrentTag(parser);
1173 continue;
1174 }
1175 int uid = Process.getUidForName(uidStr);
1176 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 + uidStr + "\" at "
1179 + parser.getPositionDescription());
1180 XmlUtils.skipCurrentTag(parser);
1181 continue;
1182 }
1183 perm = perm.intern();
1184 HashSet<String> perms = mSystemPermissions.get(uid);
1185 if (perms == null) {
1186 perms = new HashSet<String>();
1187 mSystemPermissions.put(uid, perms);
1188 }
1189 perms.add(perm);
1190 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 } else if ("library".equals(name)) {
1193 String lname = parser.getAttributeValue(null, "name");
1194 String lfile = parser.getAttributeValue(null, "file");
1195 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001196 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 + parser.getPositionDescription());
1198 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 + parser.getPositionDescription());
1201 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001202 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 mSharedLibraries.put(lname, lfile);
1204 }
1205 XmlUtils.skipCurrentTag(parser);
1206 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001207
Dianne Hackborn49237342009-08-27 20:08:01 -07001208 } else if ("feature".equals(name)) {
1209 String fname = parser.getAttributeValue(null, "name");
1210 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001211 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001212 + parser.getPositionDescription());
1213 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001214 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 FeatureInfo fi = new FeatureInfo();
1216 fi.name = fname;
1217 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219 XmlUtils.skipCurrentTag(parser);
1220 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } else {
1223 XmlUtils.skipCurrentTag(parser);
1224 continue;
1225 }
1226
1227 }
1228 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001229 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001231 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
1234
1235 void readPermission(XmlPullParser parser, String name)
1236 throws IOException, XmlPullParserException {
1237
1238 name = name.intern();
1239
1240 BasePermission bp = mSettings.mPermissions.get(name);
1241 if (bp == null) {
1242 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1243 mSettings.mPermissions.put(name, bp);
1244 }
1245 int outerDepth = parser.getDepth();
1246 int type;
1247 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1248 && (type != XmlPullParser.END_TAG
1249 || parser.getDepth() > outerDepth)) {
1250 if (type == XmlPullParser.END_TAG
1251 || type == XmlPullParser.TEXT) {
1252 continue;
1253 }
1254
1255 String tagName = parser.getName();
1256 if ("group".equals(tagName)) {
1257 String gidStr = parser.getAttributeValue(null, "gid");
1258 if (gidStr != null) {
1259 int gid = Process.getGidForName(gidStr);
1260 bp.gids = appendInt(bp.gids, gid);
1261 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001262 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 + parser.getPositionDescription());
1264 }
1265 }
1266 XmlUtils.skipCurrentTag(parser);
1267 }
1268 }
1269
1270 static int[] appendInt(int[] cur, int val) {
1271 if (cur == null) {
1272 return new int[] { val };
1273 }
1274 final int N = cur.length;
1275 for (int i=0; i<N; i++) {
1276 if (cur[i] == val) {
1277 return cur;
1278 }
1279 }
1280 int[] ret = new int[N+1];
1281 System.arraycopy(cur, 0, ret, 0, N);
1282 ret[N] = val;
1283 return ret;
1284 }
1285
1286 static int[] appendInts(int[] cur, int[] add) {
1287 if (add == null) return cur;
1288 if (cur == null) return add;
1289 final int N = add.length;
1290 for (int i=0; i<N; i++) {
1291 cur = appendInt(cur, add[i]);
1292 }
1293 return cur;
1294 }
1295
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001296 static int[] removeInt(int[] cur, int val) {
1297 if (cur == null) {
1298 return null;
1299 }
1300 final int N = cur.length;
1301 for (int i=0; i<N; i++) {
1302 if (cur[i] == val) {
1303 int[] ret = new int[N-1];
1304 if (i > 0) {
1305 System.arraycopy(cur, 0, ret, 0, i);
1306 }
1307 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001308 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001309 }
1310 return ret;
1311 }
1312 }
1313 return cur;
1314 }
1315
1316 static int[] removeInts(int[] cur, int[] rem) {
1317 if (rem == null) return cur;
1318 if (cur == null) return cur;
1319 final int N = rem.length;
1320 for (int i=0; i<N; i++) {
1321 cur = removeInt(cur, rem[i]);
1322 }
1323 return cur;
1324 }
1325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001327 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1328 // The package has been uninstalled but has retained data and resources.
1329 return PackageParser.generatePackageInfo(p, null, flags);
1330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 final PackageSetting ps = (PackageSetting)p.mExtras;
1332 if (ps == null) {
1333 return null;
1334 }
1335 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1336 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1337 }
1338
1339 public PackageInfo getPackageInfo(String packageName, int flags) {
1340 synchronized (mPackages) {
1341 PackageParser.Package p = mPackages.get(packageName);
1342 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001343 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 + ": " + p);
1345 if (p != null) {
1346 return generatePackageInfo(p, flags);
1347 }
1348 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1349 return generatePackageInfoFromSettingsLP(packageName, flags);
1350 }
1351 }
1352 return null;
1353 }
1354
Dianne Hackborn47096932010-02-11 15:57:09 -08001355 public String[] currentToCanonicalPackageNames(String[] names) {
1356 String[] out = new String[names.length];
1357 synchronized (mPackages) {
1358 for (int i=names.length-1; i>=0; i--) {
1359 PackageSetting ps = mSettings.mPackages.get(names[i]);
1360 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1361 }
1362 }
1363 return out;
1364 }
1365
1366 public String[] canonicalToCurrentPackageNames(String[] names) {
1367 String[] out = new String[names.length];
1368 synchronized (mPackages) {
1369 for (int i=names.length-1; i>=0; i--) {
1370 String cur = mSettings.mRenamedPackages.get(names[i]);
1371 out[i] = cur != null ? cur : names[i];
1372 }
1373 }
1374 return out;
1375 }
1376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 public int getPackageUid(String packageName) {
1378 synchronized (mPackages) {
1379 PackageParser.Package p = mPackages.get(packageName);
1380 if(p != null) {
1381 return p.applicationInfo.uid;
1382 }
1383 PackageSetting ps = mSettings.mPackages.get(packageName);
1384 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1385 return -1;
1386 }
1387 p = ps.pkg;
1388 return p != null ? p.applicationInfo.uid : -1;
1389 }
1390 }
1391
1392 public int[] getPackageGids(String packageName) {
1393 synchronized (mPackages) {
1394 PackageParser.Package p = mPackages.get(packageName);
1395 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001396 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 + ": " + p);
1398 if (p != null) {
1399 final PackageSetting ps = (PackageSetting)p.mExtras;
1400 final SharedUserSetting suid = ps.sharedUser;
1401 return suid != null ? suid.gids : ps.gids;
1402 }
1403 }
1404 // stupid thing to indicate an error.
1405 return new int[0];
1406 }
1407
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001408 static final PermissionInfo generatePermissionInfo(
1409 BasePermission bp, int flags) {
1410 if (bp.perm != null) {
1411 return PackageParser.generatePermissionInfo(bp.perm, flags);
1412 }
1413 PermissionInfo pi = new PermissionInfo();
1414 pi.name = bp.name;
1415 pi.packageName = bp.sourcePackage;
1416 pi.nonLocalizedLabel = bp.name;
1417 pi.protectionLevel = bp.protectionLevel;
1418 return pi;
1419 }
1420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 public PermissionInfo getPermissionInfo(String name, int flags) {
1422 synchronized (mPackages) {
1423 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001424 if (p != null) {
1425 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427 return null;
1428 }
1429 }
1430
1431 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1432 synchronized (mPackages) {
1433 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1434 for (BasePermission p : mSettings.mPermissions.values()) {
1435 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001436 if (p.perm == null || p.perm.info.group == null) {
1437 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001440 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1442 }
1443 }
1444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 if (out.size() > 0) {
1447 return out;
1448 }
1449 return mPermissionGroups.containsKey(group) ? out : null;
1450 }
1451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1454 synchronized (mPackages) {
1455 return PackageParser.generatePermissionGroupInfo(
1456 mPermissionGroups.get(name), flags);
1457 }
1458 }
1459
1460 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1461 synchronized (mPackages) {
1462 final int N = mPermissionGroups.size();
1463 ArrayList<PermissionGroupInfo> out
1464 = new ArrayList<PermissionGroupInfo>(N);
1465 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1466 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1467 }
1468 return out;
1469 }
1470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1473 PackageSetting ps = mSettings.mPackages.get(packageName);
1474 if(ps != null) {
1475 if(ps.pkg == null) {
1476 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1477 if(pInfo != null) {
1478 return pInfo.applicationInfo;
1479 }
1480 return null;
1481 }
1482 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1483 }
1484 return null;
1485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1488 PackageSetting ps = mSettings.mPackages.get(packageName);
1489 if(ps != null) {
1490 if(ps.pkg == null) {
1491 ps.pkg = new PackageParser.Package(packageName);
1492 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001493 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1494 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1495 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1496 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001497 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001498 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500 return generatePackageInfo(ps.pkg, flags);
1501 }
1502 return null;
1503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1506 synchronized (mPackages) {
1507 PackageParser.Package p = mPackages.get(packageName);
1508 if (Config.LOGV) Log.v(
1509 TAG, "getApplicationInfo " + packageName
1510 + ": " + p);
1511 if (p != null) {
1512 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001513 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
1515 if ("android".equals(packageName)||"system".equals(packageName)) {
1516 return mAndroidApplication;
1517 }
1518 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1519 return generateApplicationInfoFromSettingsLP(packageName, flags);
1520 }
1521 }
1522 return null;
1523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001524
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.CLEAR_APP_CACHE, null);
1529 // Queue up an async operation since clearing cache may take a little while.
1530 mHandler.post(new Runnable() {
1531 public void run() {
1532 mHandler.removeCallbacks(this);
1533 int retCode = -1;
1534 if (mInstaller != null) {
1535 retCode = mInstaller.freeCache(freeStorageSize);
1536 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001537 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 } //end if mInstaller
1540 if (observer != null) {
1541 try {
1542 observer.onRemoveCompleted(null, (retCode >= 0));
1543 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001544 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546 }
1547 }
1548 });
1549 }
1550
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001551 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001552 mContext.enforceCallingOrSelfPermission(
1553 android.Manifest.permission.CLEAR_APP_CACHE, null);
1554 // Queue up an async operation since clearing cache may take a little while.
1555 mHandler.post(new Runnable() {
1556 public void run() {
1557 mHandler.removeCallbacks(this);
1558 int retCode = -1;
1559 if (mInstaller != null) {
1560 retCode = mInstaller.freeCache(freeStorageSize);
1561 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001562 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001563 }
1564 }
1565 if(pi != null) {
1566 try {
1567 // Callback via pending intent
1568 int code = (retCode >= 0) ? 1 : 0;
1569 pi.sendIntent(null, code, null,
1570 null, null);
1571 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001572 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001573 }
1574 }
1575 }
1576 });
1577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1580 synchronized (mPackages) {
1581 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001582
1583 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001585 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587 if (mResolveComponentName.equals(component)) {
1588 return mResolveActivity;
1589 }
1590 }
1591 return null;
1592 }
1593
1594 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1595 synchronized (mPackages) {
1596 PackageParser.Activity a = mReceivers.mActivities.get(component);
1597 if (Config.LOGV) Log.v(
1598 TAG, "getReceiverInfo " + component + ": " + a);
1599 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1600 return PackageParser.generateActivityInfo(a, flags);
1601 }
1602 }
1603 return null;
1604 }
1605
1606 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1607 synchronized (mPackages) {
1608 PackageParser.Service s = mServices.mServices.get(component);
1609 if (Config.LOGV) Log.v(
1610 TAG, "getServiceInfo " + component + ": " + s);
1611 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1612 return PackageParser.generateServiceInfo(s, flags);
1613 }
1614 }
1615 return null;
1616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001617
Dianne Hackborn361199b2010-08-30 17:42:07 -07001618 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1619 synchronized (mPackages) {
1620 PackageParser.Provider p = mProvidersByComponent.get(component);
1621 if (Config.LOGV) Log.v(
1622 TAG, "getProviderInfo " + component + ": " + p);
1623 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1624 return PackageParser.generateProviderInfo(p, flags);
1625 }
1626 }
1627 return null;
1628 }
1629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 public String[] getSystemSharedLibraryNames() {
1631 Set<String> libSet;
1632 synchronized (mPackages) {
1633 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001634 int size = libSet.size();
1635 if (size > 0) {
1636 String[] libs = new String[size];
1637 libSet.toArray(libs);
1638 return libs;
1639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001641 return null;
1642 }
1643
1644 public FeatureInfo[] getSystemAvailableFeatures() {
1645 Collection<FeatureInfo> featSet;
1646 synchronized (mPackages) {
1647 featSet = mAvailableFeatures.values();
1648 int size = featSet.size();
1649 if (size > 0) {
1650 FeatureInfo[] features = new FeatureInfo[size+1];
1651 featSet.toArray(features);
1652 FeatureInfo fi = new FeatureInfo();
1653 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1654 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1655 features[size] = fi;
1656 return features;
1657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
1659 return null;
1660 }
1661
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001662 public boolean hasSystemFeature(String name) {
1663 synchronized (mPackages) {
1664 return mAvailableFeatures.containsKey(name);
1665 }
1666 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 public int checkPermission(String permName, String pkgName) {
1669 synchronized (mPackages) {
1670 PackageParser.Package p = mPackages.get(pkgName);
1671 if (p != null && p.mExtras != null) {
1672 PackageSetting ps = (PackageSetting)p.mExtras;
1673 if (ps.sharedUser != null) {
1674 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1675 return PackageManager.PERMISSION_GRANTED;
1676 }
1677 } else if (ps.grantedPermissions.contains(permName)) {
1678 return PackageManager.PERMISSION_GRANTED;
1679 }
1680 }
1681 }
1682 return PackageManager.PERMISSION_DENIED;
1683 }
1684
1685 public int checkUidPermission(String permName, int uid) {
1686 synchronized (mPackages) {
1687 Object obj = mSettings.getUserIdLP(uid);
1688 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001689 GrantedPermissions gp = (GrantedPermissions)obj;
1690 if (gp.grantedPermissions.contains(permName)) {
1691 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693 } else {
1694 HashSet<String> perms = mSystemPermissions.get(uid);
1695 if (perms != null && perms.contains(permName)) {
1696 return PackageManager.PERMISSION_GRANTED;
1697 }
1698 }
1699 }
1700 return PackageManager.PERMISSION_DENIED;
1701 }
1702
1703 private BasePermission findPermissionTreeLP(String permName) {
1704 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1705 if (permName.startsWith(bp.name) &&
1706 permName.length() > bp.name.length() &&
1707 permName.charAt(bp.name.length()) == '.') {
1708 return bp;
1709 }
1710 }
1711 return null;
1712 }
1713
1714 private BasePermission checkPermissionTreeLP(String permName) {
1715 if (permName != null) {
1716 BasePermission bp = findPermissionTreeLP(permName);
1717 if (bp != null) {
1718 if (bp.uid == Binder.getCallingUid()) {
1719 return bp;
1720 }
1721 throw new SecurityException("Calling uid "
1722 + Binder.getCallingUid()
1723 + " is not allowed to add to permission tree "
1724 + bp.name + " owned by uid " + bp.uid);
1725 }
1726 }
1727 throw new SecurityException("No permission tree found for " + permName);
1728 }
1729
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001730 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1731 if (s1 == null) {
1732 return s2 == null;
1733 }
1734 if (s2 == null) {
1735 return false;
1736 }
1737 if (s1.getClass() != s2.getClass()) {
1738 return false;
1739 }
1740 return s1.equals(s2);
1741 }
1742
1743 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1744 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001745 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001746 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1747 if (!compareStrings(pi1.name, pi2.name)) return false;
1748 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1749 // We'll take care of setting this one.
1750 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1751 // These are not currently stored in settings.
1752 //if (!compareStrings(pi1.group, pi2.group)) return false;
1753 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1754 //if (pi1.labelRes != pi2.labelRes) return false;
1755 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1756 return true;
1757 }
1758
1759 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1760 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1761 throw new SecurityException("Label must be specified in permission");
1762 }
1763 BasePermission tree = checkPermissionTreeLP(info.name);
1764 BasePermission bp = mSettings.mPermissions.get(info.name);
1765 boolean added = bp == null;
1766 boolean changed = true;
1767 if (added) {
1768 bp = new BasePermission(info.name, tree.sourcePackage,
1769 BasePermission.TYPE_DYNAMIC);
1770 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1771 throw new SecurityException(
1772 "Not allowed to modify non-dynamic permission "
1773 + info.name);
1774 } else {
1775 if (bp.protectionLevel == info.protectionLevel
1776 && bp.perm.owner.equals(tree.perm.owner)
1777 && bp.uid == tree.uid
1778 && comparePermissionInfos(bp.perm.info, info)) {
1779 changed = false;
1780 }
1781 }
1782 bp.protectionLevel = info.protectionLevel;
1783 bp.perm = new PackageParser.Permission(tree.perm.owner,
1784 new PermissionInfo(info));
1785 bp.perm.info.packageName = tree.perm.info.packageName;
1786 bp.uid = tree.uid;
1787 if (added) {
1788 mSettings.mPermissions.put(info.name, bp);
1789 }
1790 if (changed) {
1791 if (!async) {
1792 mSettings.writeLP();
1793 } else {
1794 scheduleWriteSettingsLocked();
1795 }
1796 }
1797 return added;
1798 }
1799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 public boolean addPermission(PermissionInfo info) {
1801 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001802 return addPermissionLocked(info, false);
1803 }
1804 }
1805
1806 public boolean addPermissionAsync(PermissionInfo info) {
1807 synchronized (mPackages) {
1808 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
1811
1812 public void removePermission(String name) {
1813 synchronized (mPackages) {
1814 checkPermissionTreeLP(name);
1815 BasePermission bp = mSettings.mPermissions.get(name);
1816 if (bp != null) {
1817 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1818 throw new SecurityException(
1819 "Not allowed to modify non-dynamic permission "
1820 + name);
1821 }
1822 mSettings.mPermissions.remove(name);
1823 mSettings.writeLP();
1824 }
1825 }
1826 }
1827
Dianne Hackborn854060af2009-07-09 18:14:31 -07001828 public boolean isProtectedBroadcast(String actionName) {
1829 synchronized (mPackages) {
1830 return mProtectedBroadcasts.contains(actionName);
1831 }
1832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 public int checkSignatures(String pkg1, String pkg2) {
1835 synchronized (mPackages) {
1836 PackageParser.Package p1 = mPackages.get(pkg1);
1837 PackageParser.Package p2 = mPackages.get(pkg2);
1838 if (p1 == null || p1.mExtras == null
1839 || p2 == null || p2.mExtras == null) {
1840 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1841 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001842 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844 }
1845
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001846 public int checkUidSignatures(int uid1, int uid2) {
1847 synchronized (mPackages) {
1848 Signature[] s1;
1849 Signature[] s2;
1850 Object obj = mSettings.getUserIdLP(uid1);
1851 if (obj != null) {
1852 if (obj instanceof SharedUserSetting) {
1853 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1854 } else if (obj instanceof PackageSetting) {
1855 s1 = ((PackageSetting)obj).signatures.mSignatures;
1856 } else {
1857 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1858 }
1859 } else {
1860 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1861 }
1862 obj = mSettings.getUserIdLP(uid2);
1863 if (obj != null) {
1864 if (obj instanceof SharedUserSetting) {
1865 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1866 } else if (obj instanceof PackageSetting) {
1867 s2 = ((PackageSetting)obj).signatures.mSignatures;
1868 } else {
1869 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1870 }
1871 } else {
1872 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1873 }
1874 return checkSignaturesLP(s1, s2);
1875 }
1876 }
1877
1878 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1879 if (s1 == null) {
1880 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1882 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1883 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001884 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1886 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001887 HashSet<Signature> set1 = new HashSet<Signature>();
1888 for (Signature sig : s1) {
1889 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001891 HashSet<Signature> set2 = new HashSet<Signature>();
1892 for (Signature sig : s2) {
1893 set2.add(sig);
1894 }
1895 // Make sure s2 contains all signatures in s1.
1896 if (set1.equals(set2)) {
1897 return PackageManager.SIGNATURE_MATCH;
1898 }
1899 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
1901
1902 public String[] getPackagesForUid(int uid) {
1903 synchronized (mPackages) {
1904 Object obj = mSettings.getUserIdLP(uid);
1905 if (obj instanceof SharedUserSetting) {
1906 SharedUserSetting sus = (SharedUserSetting)obj;
1907 final int N = sus.packages.size();
1908 String[] res = new String[N];
1909 Iterator<PackageSetting> it = sus.packages.iterator();
1910 int i=0;
1911 while (it.hasNext()) {
1912 res[i++] = it.next().name;
1913 }
1914 return res;
1915 } else if (obj instanceof PackageSetting) {
1916 PackageSetting ps = (PackageSetting)obj;
1917 return new String[] { ps.name };
1918 }
1919 }
1920 return null;
1921 }
1922
1923 public String getNameForUid(int uid) {
1924 synchronized (mPackages) {
1925 Object obj = mSettings.getUserIdLP(uid);
1926 if (obj instanceof SharedUserSetting) {
1927 SharedUserSetting sus = (SharedUserSetting)obj;
1928 return sus.name + ":" + sus.userId;
1929 } else if (obj instanceof PackageSetting) {
1930 PackageSetting ps = (PackageSetting)obj;
1931 return ps.name;
1932 }
1933 }
1934 return null;
1935 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 public int getUidForSharedUser(String sharedUserName) {
1938 if(sharedUserName == null) {
1939 return -1;
1940 }
1941 synchronized (mPackages) {
1942 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1943 if(suid == null) {
1944 return -1;
1945 }
1946 return suid.userId;
1947 }
1948 }
1949
1950 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1951 int flags) {
1952 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001953 return chooseBestActivity(intent, resolvedType, flags, query);
1954 }
1955
Mihai Predaeae850c2009-05-13 10:13:48 +02001956 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1957 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 if (query != null) {
1959 final int N = query.size();
1960 if (N == 1) {
1961 return query.get(0);
1962 } else if (N > 1) {
1963 // If there is more than one activity with the same priority,
1964 // then let the user decide between them.
1965 ResolveInfo r0 = query.get(0);
1966 ResolveInfo r1 = query.get(1);
1967 if (false) {
1968 System.out.println(r0.activityInfo.name +
1969 "=" + r0.priority + " vs " +
1970 r1.activityInfo.name +
1971 "=" + r1.priority);
1972 }
1973 // If the first activity has a higher priority, or a different
1974 // default, then it is always desireable to pick it.
1975 if (r0.priority != r1.priority
1976 || r0.preferredOrder != r1.preferredOrder
1977 || r0.isDefault != r1.isDefault) {
1978 return query.get(0);
1979 }
1980 // If we have saved a preference for a preferred activity for
1981 // this Intent, use that.
1982 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1983 flags, query, r0.priority);
1984 if (ri != null) {
1985 return ri;
1986 }
1987 return mResolveInfo;
1988 }
1989 }
1990 return null;
1991 }
1992
1993 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1994 int flags, List<ResolveInfo> query, int priority) {
1995 synchronized (mPackages) {
1996 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1997 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001998 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2000 if (prefs != null && prefs.size() > 0) {
2001 // First figure out how good the original match set is.
2002 // We will only allow preferred activities that came
2003 // from the same match quality.
2004 int match = 0;
2005 final int N = query.size();
2006 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2007 for (int j=0; j<N; j++) {
2008 ResolveInfo ri = query.get(j);
2009 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2010 + ": 0x" + Integer.toHexString(match));
2011 if (ri.match > match) match = ri.match;
2012 }
2013 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2014 + Integer.toHexString(match));
2015 match &= IntentFilter.MATCH_CATEGORY_MASK;
2016 final int M = prefs.size();
2017 for (int i=0; i<M; i++) {
2018 PreferredActivity pa = prefs.get(i);
2019 if (pa.mMatch != match) {
2020 continue;
2021 }
2022 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2023 if (DEBUG_PREFERRED) {
2024 Log.v(TAG, "Got preferred activity:");
2025 ai.dump(new LogPrinter(Log.INFO, TAG), " ");
2026 }
2027 if (ai != null) {
2028 for (int j=0; j<N; j++) {
2029 ResolveInfo ri = query.get(j);
2030 if (!ri.activityInfo.applicationInfo.packageName
2031 .equals(ai.applicationInfo.packageName)) {
2032 continue;
2033 }
2034 if (!ri.activityInfo.name.equals(ai.name)) {
2035 continue;
2036 }
2037
2038 // Okay we found a previously set preferred app.
2039 // If the result set is different from when this
2040 // was created, we need to clear it and re-ask the
2041 // user their preference.
2042 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002043 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 + intent + " type " + resolvedType);
2045 mSettings.mPreferredActivities.removeFilter(pa);
2046 return null;
2047 }
2048
2049 // Yay!
2050 return ri;
2051 }
2052 }
2053 }
2054 }
2055 }
2056 return null;
2057 }
2058
2059 public List<ResolveInfo> queryIntentActivities(Intent intent,
2060 String resolvedType, int flags) {
2061 ComponentName comp = intent.getComponent();
2062 if (comp != null) {
2063 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2064 ActivityInfo ai = getActivityInfo(comp, flags);
2065 if (ai != null) {
2066 ResolveInfo ri = new ResolveInfo();
2067 ri.activityInfo = ai;
2068 list.add(ri);
2069 }
2070 return list;
2071 }
2072
2073 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002074 String pkgName = intent.getPackage();
2075 if (pkgName == null) {
2076 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2077 resolvedType, flags);
2078 }
2079 PackageParser.Package pkg = mPackages.get(pkgName);
2080 if (pkg != null) {
2081 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2082 resolvedType, flags, pkg.activities);
2083 }
2084 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 }
2086 }
2087
2088 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2089 Intent[] specifics, String[] specificTypes, Intent intent,
2090 String resolvedType, int flags) {
2091 final String resultsAction = intent.getAction();
2092
2093 List<ResolveInfo> results = queryIntentActivities(
2094 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2095 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2096
2097 int specificsPos = 0;
2098 int N;
2099
2100 // todo: note that the algorithm used here is O(N^2). This
2101 // isn't a problem in our current environment, but if we start running
2102 // into situations where we have more than 5 or 10 matches then this
2103 // should probably be changed to something smarter...
2104
2105 // First we go through and resolve each of the specific items
2106 // that were supplied, taking care of removing any corresponding
2107 // duplicate items in the generic resolve list.
2108 if (specifics != null) {
2109 for (int i=0; i<specifics.length; i++) {
2110 final Intent sintent = specifics[i];
2111 if (sintent == null) {
2112 continue;
2113 }
2114
2115 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2116 String action = sintent.getAction();
2117 if (resultsAction != null && resultsAction.equals(action)) {
2118 // If this action was explicitly requested, then don't
2119 // remove things that have it.
2120 action = null;
2121 }
2122 ComponentName comp = sintent.getComponent();
2123 ResolveInfo ri = null;
2124 ActivityInfo ai = null;
2125 if (comp == null) {
2126 ri = resolveIntent(
2127 sintent,
2128 specificTypes != null ? specificTypes[i] : null,
2129 flags);
2130 if (ri == null) {
2131 continue;
2132 }
2133 if (ri == mResolveInfo) {
2134 // ACK! Must do something better with this.
2135 }
2136 ai = ri.activityInfo;
2137 comp = new ComponentName(ai.applicationInfo.packageName,
2138 ai.name);
2139 } else {
2140 ai = getActivityInfo(comp, flags);
2141 if (ai == null) {
2142 continue;
2143 }
2144 }
2145
2146 // Look for any generic query activities that are duplicates
2147 // of this specific one, and remove them from the results.
2148 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2149 N = results.size();
2150 int j;
2151 for (j=specificsPos; j<N; j++) {
2152 ResolveInfo sri = results.get(j);
2153 if ((sri.activityInfo.name.equals(comp.getClassName())
2154 && sri.activityInfo.applicationInfo.packageName.equals(
2155 comp.getPackageName()))
2156 || (action != null && sri.filter.matchAction(action))) {
2157 results.remove(j);
2158 if (Config.LOGV) Log.v(
2159 TAG, "Removing duplicate item from " + j
2160 + " due to specific " + specificsPos);
2161 if (ri == null) {
2162 ri = sri;
2163 }
2164 j--;
2165 N--;
2166 }
2167 }
2168
2169 // Add this specific item to its proper place.
2170 if (ri == null) {
2171 ri = new ResolveInfo();
2172 ri.activityInfo = ai;
2173 }
2174 results.add(specificsPos, ri);
2175 ri.specificIndex = i;
2176 specificsPos++;
2177 }
2178 }
2179
2180 // Now we go through the remaining generic results and remove any
2181 // duplicate actions that are found here.
2182 N = results.size();
2183 for (int i=specificsPos; i<N-1; i++) {
2184 final ResolveInfo rii = results.get(i);
2185 if (rii.filter == null) {
2186 continue;
2187 }
2188
2189 // Iterate over all of the actions of this result's intent
2190 // filter... typically this should be just one.
2191 final Iterator<String> it = rii.filter.actionsIterator();
2192 if (it == null) {
2193 continue;
2194 }
2195 while (it.hasNext()) {
2196 final String action = it.next();
2197 if (resultsAction != null && resultsAction.equals(action)) {
2198 // If this action was explicitly requested, then don't
2199 // remove things that have it.
2200 continue;
2201 }
2202 for (int j=i+1; j<N; j++) {
2203 final ResolveInfo rij = results.get(j);
2204 if (rij.filter != null && rij.filter.hasAction(action)) {
2205 results.remove(j);
2206 if (Config.LOGV) Log.v(
2207 TAG, "Removing duplicate item from " + j
2208 + " due to action " + action + " at " + i);
2209 j--;
2210 N--;
2211 }
2212 }
2213 }
2214
2215 // If the caller didn't request filter information, drop it now
2216 // so we don't have to marshall/unmarshall it.
2217 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2218 rii.filter = null;
2219 }
2220 }
2221
2222 // Filter out the caller activity if so requested.
2223 if (caller != null) {
2224 N = results.size();
2225 for (int i=0; i<N; i++) {
2226 ActivityInfo ainfo = results.get(i).activityInfo;
2227 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2228 && caller.getClassName().equals(ainfo.name)) {
2229 results.remove(i);
2230 break;
2231 }
2232 }
2233 }
2234
2235 // If the caller didn't request filter information,
2236 // drop them now so we don't have to
2237 // marshall/unmarshall it.
2238 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2239 N = results.size();
2240 for (int i=0; i<N; i++) {
2241 results.get(i).filter = null;
2242 }
2243 }
2244
2245 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2246 return results;
2247 }
2248
2249 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2250 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002251 ComponentName comp = intent.getComponent();
2252 if (comp != null) {
2253 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2254 ActivityInfo ai = getReceiverInfo(comp, flags);
2255 if (ai != null) {
2256 ResolveInfo ri = new ResolveInfo();
2257 ri.activityInfo = ai;
2258 list.add(ri);
2259 }
2260 return list;
2261 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002264 String pkgName = intent.getPackage();
2265 if (pkgName == null) {
2266 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2267 resolvedType, flags);
2268 }
2269 PackageParser.Package pkg = mPackages.get(pkgName);
2270 if (pkg != null) {
2271 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2272 resolvedType, flags, pkg.receivers);
2273 }
2274 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 }
2276 }
2277
2278 public ResolveInfo resolveService(Intent intent, String resolvedType,
2279 int flags) {
2280 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2281 flags);
2282 if (query != null) {
2283 if (query.size() >= 1) {
2284 // If there is more than one service with the same priority,
2285 // just arbitrarily pick the first one.
2286 return query.get(0);
2287 }
2288 }
2289 return null;
2290 }
2291
2292 public List<ResolveInfo> queryIntentServices(Intent intent,
2293 String resolvedType, int flags) {
2294 ComponentName comp = intent.getComponent();
2295 if (comp != null) {
2296 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2297 ServiceInfo si = getServiceInfo(comp, flags);
2298 if (si != null) {
2299 ResolveInfo ri = new ResolveInfo();
2300 ri.serviceInfo = si;
2301 list.add(ri);
2302 }
2303 return list;
2304 }
2305
2306 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002307 String pkgName = intent.getPackage();
2308 if (pkgName == null) {
2309 return (List<ResolveInfo>)mServices.queryIntent(intent,
2310 resolvedType, flags);
2311 }
2312 PackageParser.Package pkg = mPackages.get(pkgName);
2313 if (pkg != null) {
2314 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2315 resolvedType, flags, pkg.services);
2316 }
2317 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 }
2319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 public List<PackageInfo> getInstalledPackages(int flags) {
2322 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2323
2324 synchronized (mPackages) {
2325 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2326 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2327 while (i.hasNext()) {
2328 final PackageSetting ps = i.next();
2329 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2330 if(psPkg != null) {
2331 finalList.add(psPkg);
2332 }
2333 }
2334 }
2335 else {
2336 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2337 while (i.hasNext()) {
2338 final PackageParser.Package p = i.next();
2339 if (p.applicationInfo != null) {
2340 PackageInfo pi = generatePackageInfo(p, flags);
2341 if(pi != null) {
2342 finalList.add(pi);
2343 }
2344 }
2345 }
2346 }
2347 }
2348 return finalList;
2349 }
2350
2351 public List<ApplicationInfo> getInstalledApplications(int flags) {
2352 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2353 synchronized(mPackages) {
2354 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2355 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2356 while (i.hasNext()) {
2357 final PackageSetting ps = i.next();
2358 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2359 if(ai != null) {
2360 finalList.add(ai);
2361 }
2362 }
2363 }
2364 else {
2365 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2366 while (i.hasNext()) {
2367 final PackageParser.Package p = i.next();
2368 if (p.applicationInfo != null) {
2369 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2370 if(ai != null) {
2371 finalList.add(ai);
2372 }
2373 }
2374 }
2375 }
2376 }
2377 return finalList;
2378 }
2379
2380 public List<ApplicationInfo> getPersistentApplications(int flags) {
2381 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2382
2383 synchronized (mPackages) {
2384 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2385 while (i.hasNext()) {
2386 PackageParser.Package p = i.next();
2387 if (p.applicationInfo != null
2388 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002389 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002390 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 }
2392 }
2393 }
2394
2395 return finalList;
2396 }
2397
2398 public ProviderInfo resolveContentProvider(String name, int flags) {
2399 synchronized (mPackages) {
2400 final PackageParser.Provider provider = mProviders.get(name);
2401 return provider != null
2402 && mSettings.isEnabledLP(provider.info, flags)
2403 && (!mSafeMode || (provider.info.applicationInfo.flags
2404 &ApplicationInfo.FLAG_SYSTEM) != 0)
2405 ? PackageParser.generateProviderInfo(provider, flags)
2406 : null;
2407 }
2408 }
2409
Fred Quintana718d8a22009-04-29 17:53:20 -07002410 /**
2411 * @deprecated
2412 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 public void querySyncProviders(List outNames, List outInfo) {
2414 synchronized (mPackages) {
2415 Iterator<Map.Entry<String, PackageParser.Provider>> i
2416 = mProviders.entrySet().iterator();
2417
2418 while (i.hasNext()) {
2419 Map.Entry<String, PackageParser.Provider> entry = i.next();
2420 PackageParser.Provider p = entry.getValue();
2421
2422 if (p.syncable
2423 && (!mSafeMode || (p.info.applicationInfo.flags
2424 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2425 outNames.add(entry.getKey());
2426 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2427 }
2428 }
2429 }
2430 }
2431
2432 public List<ProviderInfo> queryContentProviders(String processName,
2433 int uid, int flags) {
2434 ArrayList<ProviderInfo> finalList = null;
2435
2436 synchronized (mPackages) {
2437 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2438 while (i.hasNext()) {
2439 PackageParser.Provider p = i.next();
2440 if (p.info.authority != null
2441 && (processName == null ||
2442 (p.info.processName.equals(processName)
2443 && p.info.applicationInfo.uid == uid))
2444 && mSettings.isEnabledLP(p.info, flags)
2445 && (!mSafeMode || (p.info.applicationInfo.flags
2446 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2447 if (finalList == null) {
2448 finalList = new ArrayList<ProviderInfo>(3);
2449 }
2450 finalList.add(PackageParser.generateProviderInfo(p,
2451 flags));
2452 }
2453 }
2454 }
2455
2456 if (finalList != null) {
2457 Collections.sort(finalList, mProviderInitOrderSorter);
2458 }
2459
2460 return finalList;
2461 }
2462
2463 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2464 int flags) {
2465 synchronized (mPackages) {
2466 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2467 return PackageParser.generateInstrumentationInfo(i, flags);
2468 }
2469 }
2470
2471 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2472 int flags) {
2473 ArrayList<InstrumentationInfo> finalList =
2474 new ArrayList<InstrumentationInfo>();
2475
2476 synchronized (mPackages) {
2477 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2478 while (i.hasNext()) {
2479 PackageParser.Instrumentation p = i.next();
2480 if (targetPackage == null
2481 || targetPackage.equals(p.info.targetPackage)) {
2482 finalList.add(PackageParser.generateInstrumentationInfo(p,
2483 flags));
2484 }
2485 }
2486 }
2487
2488 return finalList;
2489 }
2490
2491 private void scanDirLI(File dir, int flags, int scanMode) {
2492 Log.d(TAG, "Scanning app dir " + dir);
2493
2494 String[] files = dir.list();
2495
2496 int i;
2497 for (i=0; i<files.length; i++) {
2498 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002499 if (!isPackageFilename(files[i])) {
2500 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002501 continue;
2502 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002503 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002505 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002506 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2507 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002508 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002509 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002510 file.delete();
2511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 }
2513 }
2514
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002515 private static File getSettingsProblemFile() {
2516 File dataDir = Environment.getDataDirectory();
2517 File systemDir = new File(dataDir, "system");
2518 File fname = new File(systemDir, "uiderrors.txt");
2519 return fname;
2520 }
2521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 private static void reportSettingsProblem(int priority, String msg) {
2523 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002524 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 FileOutputStream out = new FileOutputStream(fname, true);
2526 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002527 SimpleDateFormat formatter = new SimpleDateFormat();
2528 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2529 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 pw.close();
2531 FileUtils.setPermissions(
2532 fname.toString(),
2533 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2534 -1, -1);
2535 } catch (java.io.IOException e) {
2536 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002537 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 }
2539
2540 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2541 PackageParser.Package pkg, File srcFile, int parseFlags) {
2542 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002543 if (ps != null
2544 && ps.codePath.equals(srcFile)
2545 && ps.getTimeStamp() == srcFile.lastModified()) {
2546 if (ps.signatures.mSignatures != null
2547 && ps.signatures.mSignatures.length != 0) {
2548 // Optimization: reuse the existing cached certificates
2549 // if the package appears to be unchanged.
2550 pkg.mSignatures = ps.signatures.mSignatures;
2551 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 }
Jeff Browne7600722010-04-07 18:28:23 -07002553
2554 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002555 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002556 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2557 }
2558
2559 if (!pp.collectCertificates(pkg, parseFlags)) {
2560 mLastScanError = pp.getParseError();
2561 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 }
2563 }
2564 return true;
2565 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002566
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 /*
2568 * Scan a package and return the newly parsed package.
2569 * Returns null in case of errors and the error code is stored in mLastScanError
2570 */
2571 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002572 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002574 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002576 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002579 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 if (pkg == null) {
2581 mLastScanError = pp.getParseError();
2582 return null;
2583 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002584 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 PackageSetting updatedPkg;
2586 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002587 // Look to see if we already know about this package.
2588 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002589 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002590 // This package has been renamed to its original name. Let's
2591 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002592 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002593 }
2594 // If there was no original package, see one for the real package name.
2595 if (ps == null) {
2596 ps = mSettings.peekPackageLP(pkg.packageName);
2597 }
2598 // Check to see if this package could be hiding/updating a system
2599 // package. Must look for it either under the original or real
2600 // package name depending on our state.
2601 updatedPkg = mSettings.mDisabledSysPackages.get(
2602 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002604 // First check if this is a system package that may involve an update
2605 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002606 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002607 // The path has changed from what was last scanned... check the
2608 // version of the new path against what we have stored to determine
2609 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002610 if (pkg.mVersionCode < ps.versionCode) {
2611 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002612 // Ignore entry. Skip it.
2613 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2614 + "ignored: updated version " + ps.versionCode
2615 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002616 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2617 return null;
2618 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002619 // The current app on the system partion is better than
2620 // what we have updated to on the data partition; switch
2621 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002622 // At this point, its safely assumed that package installation for
2623 // apps in system partition will go through. If not there won't be a working
2624 // version of the app
2625 synchronized (mPackages) {
2626 // Just remove the loaded entries from package lists.
2627 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002628 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002629 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002630 + "reverting from " + ps.codePathString
2631 + ": new version " + pkg.mVersionCode
2632 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002633 InstallArgs args = new FileInstallArgs(ps.codePathString,
2634 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002635 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002636 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002638 }
2639 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002640 if (updatedPkg != null) {
2641 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2642 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2643 }
2644 // Verify certificates against what was last scanned
2645 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002646 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002647 return null;
2648 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002649 // The apk is forward locked (not public) if its code and resources
2650 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002651 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002652 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002653 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002654 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002655
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002656 String codePath = null;
2657 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002658 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2659 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002660 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002661 } else {
2662 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002663 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002664 }
2665 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002666 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002667 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002668 codePath = pkg.mScanPath;
2669 // Set application objects path explicitly.
2670 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002672 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 }
2674
Kenny Root85387d72010-08-26 10:13:11 -07002675 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2676 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002677 pkg.mPath = pkg.mScanPath = destCodePath;
2678 pkg.applicationInfo.sourceDir = destCodePath;
2679 pkg.applicationInfo.publicSourceDir = destResPath;
2680 }
2681
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002682 private static String fixProcessName(String defProcessName,
2683 String processName, int uid) {
2684 if (processName == null) {
2685 return defProcessName;
2686 }
2687 return processName;
2688 }
2689
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002690 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002691 PackageParser.Package pkg) {
2692 if (pkgSetting.signatures.mSignatures != null) {
2693 // Already existing package. Make sure signatures match
2694 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2695 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002696 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002697 + " signatures do not match the previously installed version; ignoring!");
2698 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002699 return false;
2700 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002701 }
2702 // Check for shared user signatures
2703 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2704 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2705 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2706 Slog.e(TAG, "Package " + pkg.packageName
2707 + " has no signatures that match those in shared user "
2708 + pkgSetting.sharedUser.name + "; ignoring!");
2709 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2710 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 }
2713 return true;
2714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002715
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002716 public boolean performDexOpt(String packageName) {
2717 if (!mNoDexOpt) {
2718 return false;
2719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002720
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002721 PackageParser.Package p;
2722 synchronized (mPackages) {
2723 p = mPackages.get(packageName);
2724 if (p == null || p.mDidDexOpt) {
2725 return false;
2726 }
2727 }
2728 synchronized (mInstallLock) {
2729 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2730 }
2731 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002732
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002733 static final int DEX_OPT_SKIPPED = 0;
2734 static final int DEX_OPT_PERFORMED = 1;
2735 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2738 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002739 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002740 String path = pkg.mScanPath;
2741 int ret = 0;
2742 try {
2743 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002744 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002745 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002746 pkg.mDidDexOpt = true;
2747 performed = true;
2748 }
2749 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002750 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002751 ret = -1;
2752 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002753 Slog.w(TAG, "IOException reading apk: " + path, e);
2754 ret = -1;
2755 } catch (dalvik.system.StaleDexCacheError e) {
2756 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2757 ret = -1;
2758 } catch (Exception e) {
2759 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002760 ret = -1;
2761 }
2762 if (ret < 0) {
2763 //error from installer
2764 return DEX_OPT_FAILED;
2765 }
2766 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002767
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002768 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2769 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002770
2771 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2772 return Environment.isEncryptedFilesystemEnabled() &&
2773 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2774 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002775
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002776 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2777 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002778 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002779 + " to " + newPkg.packageName
2780 + ": old package not in system partition");
2781 return false;
2782 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002783 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002784 + " to " + newPkg.packageName
2785 + ": old package still exists");
2786 return false;
2787 }
2788 return true;
2789 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002790
2791 private File getDataPathForPackage(PackageParser.Package pkg) {
2792 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2793 File dataPath;
2794 if (useEncryptedFSDir) {
2795 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2796 } else {
2797 dataPath = new File(mAppDataDir, pkg.packageName);
2798 }
2799 return dataPath;
2800 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002801
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002802 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2803 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002804 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002805 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2806 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002807 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002808 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002809 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2810 return null;
2811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 mScanningPath = scanFile;
2813 if (pkg == null) {
2814 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2815 return null;
2816 }
2817
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2819 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2820 }
2821
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002822 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 synchronized (mPackages) {
2824 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002825 Slog.w(TAG, "*************************************************");
2826 Slog.w(TAG, "Core android package being redefined. Skipping.");
2827 Slog.w(TAG, " file=" + mScanningPath);
2828 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2830 return null;
2831 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002832
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 // Set up information for our fall-back user intent resolution
2834 // activity.
2835 mPlatformPackage = pkg;
2836 pkg.mVersionCode = mSdkVersion;
2837 mAndroidApplication = pkg.applicationInfo;
2838 mResolveActivity.applicationInfo = mAndroidApplication;
2839 mResolveActivity.name = ResolverActivity.class.getName();
2840 mResolveActivity.packageName = mAndroidApplication.packageName;
2841 mResolveActivity.processName = mAndroidApplication.processName;
2842 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2843 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2844 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2845 mResolveActivity.exported = true;
2846 mResolveActivity.enabled = true;
2847 mResolveInfo.activityInfo = mResolveActivity;
2848 mResolveInfo.priority = 0;
2849 mResolveInfo.preferredOrder = 0;
2850 mResolveInfo.match = 0;
2851 mResolveComponentName = new ComponentName(
2852 mAndroidApplication.packageName, mResolveActivity.name);
2853 }
2854 }
2855
2856 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002857 TAG, "Scanning package " + pkg.packageName);
2858 if (mPackages.containsKey(pkg.packageName)
2859 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002860 Slog.w(TAG, "*************************************************");
2861 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002863 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002864 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2865 return null;
2866 }
2867
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002868 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002869 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2870 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 SharedUserSetting suid = null;
2873 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002874
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002875 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2876 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002877 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002878 pkg.mRealPackage = null;
2879 pkg.mAdoptPermissions = null;
2880 }
2881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 synchronized (mPackages) {
2883 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002884 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2885 if (mTmpSharedLibraries == null ||
2886 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2887 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2888 }
2889 int num = 0;
2890 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2891 for (int i=0; i<N; i++) {
2892 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002894 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002896 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2898 return null;
2899 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002900 mTmpSharedLibraries[num] = file;
2901 num++;
2902 }
2903 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2904 for (int i=0; i<N; i++) {
2905 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2906 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002907 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002908 + " desires unavailable shared library "
2909 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2910 } else {
2911 mTmpSharedLibraries[num] = file;
2912 num++;
2913 }
2914 }
2915 if (num > 0) {
2916 pkg.usesLibraryFiles = new String[num];
2917 System.arraycopy(mTmpSharedLibraries, 0,
2918 pkg.usesLibraryFiles, 0, num);
2919 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002920
Dianne Hackborn49237342009-08-27 20:08:01 -07002921 if (pkg.reqFeatures != null) {
2922 N = pkg.reqFeatures.size();
2923 for (int i=0; i<N; i++) {
2924 FeatureInfo fi = pkg.reqFeatures.get(i);
2925 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2926 // Don't care.
2927 continue;
2928 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002929
Dianne Hackborn49237342009-08-27 20:08:01 -07002930 if (fi.name != null) {
2931 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002932 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002933 + " requires unavailable feature "
2934 + fi.name + "; failing!");
2935 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2936 return null;
2937 }
2938 }
2939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002942
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 if (pkg.mSharedUserId != null) {
2944 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2945 pkg.applicationInfo.flags, true);
2946 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002947 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002948 + " for shared user failed");
2949 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2950 return null;
2951 }
2952 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2953 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2954 + suid.userId + "): packages=" + suid.packages);
2955 }
2956 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002957
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002958 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002959 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002960 Log.w(TAG, "WAITING FOR DEBUGGER");
2961 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002962 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2963 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002964 }
2965 }
2966
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002967 // Check if we are renaming from an original package name.
2968 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002969 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002970 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002971 // This package may need to be renamed to a previously
2972 // installed name. Let's check on that...
2973 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002974 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 // This package had originally been installed as the
2976 // original name, and we have already taken care of
2977 // transitioning to the new one. Just update the new
2978 // one to continue using the old name.
2979 realName = pkg.mRealPackage;
2980 if (!pkg.packageName.equals(renamed)) {
2981 // Callers into this function may have already taken
2982 // care of renaming the package; only do it here if
2983 // it is not already done.
2984 pkg.setPackageName(renamed);
2985 }
2986
Dianne Hackbornc1552392010-03-03 16:19:01 -08002987 } else {
2988 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2989 if ((origPackage=mSettings.peekPackageLP(
2990 pkg.mOriginalPackages.get(i))) != null) {
2991 // We do have the package already installed under its
2992 // original name... should we use it?
2993 if (!verifyPackageUpdate(origPackage, pkg)) {
2994 // New package is not compatible with original.
2995 origPackage = null;
2996 continue;
2997 } else if (origPackage.sharedUser != null) {
2998 // Make sure uid is compatible between packages.
2999 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003000 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003001 + " to " + pkg.packageName + ": old uid "
3002 + origPackage.sharedUser.name
3003 + " differs from " + pkg.mSharedUserId);
3004 origPackage = null;
3005 continue;
3006 }
3007 } else {
3008 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3009 + pkg.packageName + " to old name " + origPackage.name);
3010 }
3011 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003012 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003013 }
3014 }
3015 }
3016
3017 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003018 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003019 + " was transferred to another, but its .apk remains");
3020 }
3021
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003022 // Just create the setting, don't add it yet. For already existing packages
3023 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003024 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 destResourceFile, pkg.applicationInfo.flags, true, false);
3026 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003027 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003028 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3029 return null;
3030 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003031
3032 if (pkgSetting.origPackage != null) {
3033 // If we are first transitioning from an original package,
3034 // fix up the new package's name now. We need to do this after
3035 // looking up the package under its new name, so getPackageLP
3036 // can take care of fiddling things correctly.
3037 pkg.setPackageName(origPackage.name);
3038
3039 // File a report about this.
3040 String msg = "New package " + pkgSetting.realName
3041 + " renamed to replace old package " + pkgSetting.name;
3042 reportSettingsProblem(Log.WARN, msg);
3043
3044 // Make a note of it.
3045 mTransferedPackages.add(origPackage.name);
3046
3047 // No longer need to retain this.
3048 pkgSetting.origPackage = null;
3049 }
3050
3051 if (realName != null) {
3052 // Make a note of it.
3053 mTransferedPackages.add(pkg.packageName);
3054 }
3055
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003056 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3058 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 pkg.applicationInfo.uid = pkgSetting.userId;
3061 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003062
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003063 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003064 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 return null;
3066 }
3067 // The signature has changed, but this package is in the system
3068 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003069 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 // However... if this package is part of a shared user, but it
3071 // doesn't match the signature of the shared user, let's fail.
3072 // What this means is that you can't change the signatures
3073 // associated with an overall shared user, which doesn't seem all
3074 // that unreasonable.
3075 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003076 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3077 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3078 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3080 return null;
3081 }
3082 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003083 // File a report about this.
3084 String msg = "System package " + pkg.packageName
3085 + " signature changed; retaining data.";
3086 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003088
The Android Open Source Project10592532009-03-18 17:39:46 -07003089 // Verify that this new package doesn't have any content providers
3090 // that conflict with existing packages. Only do this if the
3091 // package isn't already installed, since we don't want to break
3092 // things that are installed.
3093 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3094 int N = pkg.providers.size();
3095 int i;
3096 for (i=0; i<N; i++) {
3097 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003098 if (p.info.authority != null) {
3099 String names[] = p.info.authority.split(";");
3100 for (int j = 0; j < names.length; j++) {
3101 if (mProviders.containsKey(names[j])) {
3102 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003103 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003104 " (in package " + pkg.applicationInfo.packageName +
3105 ") is already used by "
3106 + ((other != null && other.getComponentName() != null)
3107 ? other.getComponentName().getPackageName() : "?"));
3108 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3109 return null;
3110 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003111 }
3112 }
3113 }
3114 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 }
3116
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003117 final String pkgName = pkg.packageName;
3118
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003119 if (pkg.mAdoptPermissions != null) {
3120 // This package wants to adopt ownership of permissions from
3121 // another package.
3122 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3123 String origName = pkg.mAdoptPermissions.get(i);
3124 PackageSetting orig = mSettings.peekPackageLP(origName);
3125 if (orig != null) {
3126 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003127 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003128 + origName + " to " + pkg.packageName);
3129 mSettings.transferPermissions(origName, pkg.packageName);
3130 }
3131 }
3132 }
3133 }
3134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003135 long scanFileTime = scanFile.lastModified();
3136 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3137 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3138 pkg.applicationInfo.processName = fixProcessName(
3139 pkg.applicationInfo.packageName,
3140 pkg.applicationInfo.processName,
3141 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142
3143 File dataPath;
3144 if (mPlatformPackage == pkg) {
3145 // The system package is special.
3146 dataPath = new File (Environment.getDataDirectory(), "system");
3147 pkg.applicationInfo.dataDir = dataPath.getPath();
3148 } else {
3149 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003150 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003151 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003152
3153 boolean uidError = false;
3154
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 if (dataPath.exists()) {
3156 mOutPermissions[1] = 0;
3157 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003158
3159 // If we have mismatched owners for the data path, we have a
3160 // problem (unless we're running in the simulator.)
3161 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 boolean recovered = false;
3163 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3164 // If this is a system app, we can at least delete its
3165 // current data so the application will still work.
3166 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003167 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003168 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169 // Old data gone!
3170 String msg = "System package " + pkg.packageName
3171 + " has changed from uid: "
3172 + mOutPermissions[1] + " to "
3173 + pkg.applicationInfo.uid + "; old data erased";
3174 reportSettingsProblem(Log.WARN, msg);
3175 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003178 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003179 pkg.applicationInfo.uid);
3180 if (ret == -1) {
3181 // Ack should not happen!
3182 msg = "System package " + pkg.packageName
3183 + " could not have data directory re-created after delete.";
3184 reportSettingsProblem(Log.WARN, msg);
3185 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3186 return null;
3187 }
3188 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 if (!recovered) {
3191 mHasSystemUidErrors = true;
3192 }
3193 }
3194 if (!recovered) {
3195 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3196 + pkg.applicationInfo.uid + "/fs_"
3197 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003198 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 String msg = "Package " + pkg.packageName
3200 + " has mismatched uid: "
3201 + mOutPermissions[1] + " on disk, "
3202 + pkg.applicationInfo.uid + " in settings";
3203 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003204 mSettings.mReadMessages.append(msg);
3205 mSettings.mReadMessages.append('\n');
3206 uidError = true;
3207 if (!pkgSetting.uidError) {
3208 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 }
3211 }
3212 }
3213 pkg.applicationInfo.dataDir = dataPath.getPath();
3214 } else {
3215 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3216 Log.v(TAG, "Want this data dir: " + dataPath);
3217 //invoke installer to do the actual installation
3218 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003219 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 pkg.applicationInfo.uid);
3221 if(ret < 0) {
3222 // Error from installer
3223 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3224 return null;
3225 }
3226 } else {
3227 dataPath.mkdirs();
3228 if (dataPath.exists()) {
3229 FileUtils.setPermissions(
3230 dataPath.toString(),
3231 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3232 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3233 }
3234 }
3235 if (dataPath.exists()) {
3236 pkg.applicationInfo.dataDir = dataPath.getPath();
3237 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003238 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 pkg.applicationInfo.dataDir = null;
3240 }
3241 }
Kenny Root85387d72010-08-26 10:13:11 -07003242
3243 /*
3244 * Set the data dir to the default "/data/data/<package name>/lib"
3245 * if we got here without anyone telling us different (e.g., apps
3246 * stored on SD card have their native libraries stored in the ASEC
3247 * container with the APK).
3248 */
3249 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
3250 pkg.applicationInfo.nativeLibraryDir = new File(dataPath, LIB_DIR_NAME).getPath();
3251 }
3252
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003253 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 }
3255
Kenny Root85387d72010-08-26 10:13:11 -07003256 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 if (mInstaller != null) {
3258 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003259 /* Note: We don't want to unpack the native binaries for
3260 * system applications, unless they have been updated
3261 * (the binaries are already under /system/lib).
3262 * Also, don't unpack libs for apps on the external card
3263 * since they should have their libraries in the ASEC
3264 * container already.
3265 *
3266 * In other words, we're going to unpack the binaries
3267 * only for non-system apps and system app upgrades.
3268 */
3269 if ((!isSystemApp(pkg) || isUpdatedSystemApp(pkg)) && !isExternal(pkg)) {
3270 Log.i(TAG, path + " changed; unpacking");
3271 File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
3272 sharedLibraryDir.mkdir();
3273 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003275 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003276
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003277 if ((scanMode&SCAN_NO_DEX) == 0) {
3278 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3280 return null;
3281 }
3282 }
3283 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 if (mFactoryTest && pkg.requestedPermissions.contains(
3286 android.Manifest.permission.FACTORY_TEST)) {
3287 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3288 }
3289
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003290 // Request the ActivityManager to kill the process(only for existing packages)
3291 // so that we do not end up in a confused state while the user is still using the older
3292 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003293 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003294 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003295 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003296 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003299 // We don't expect installation to fail beyond this point,
3300 if ((scanMode&SCAN_MONITOR) != 0) {
3301 mAppDirs.put(pkg.mPath, pkg);
3302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003304 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003306 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003307 // Make sure we don't accidentally delete its data.
3308 mSettings.mPackagesToBeCleaned.remove(pkgName);
3309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 int N = pkg.providers.size();
3311 StringBuilder r = null;
3312 int i;
3313 for (i=0; i<N; i++) {
3314 PackageParser.Provider p = pkg.providers.get(i);
3315 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3316 p.info.processName, pkg.applicationInfo.uid);
3317 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3318 p.info.name), p);
3319 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003320 if (p.info.authority != null) {
3321 String names[] = p.info.authority.split(";");
3322 p.info.authority = null;
3323 for (int j = 0; j < names.length; j++) {
3324 if (j == 1 && p.syncable) {
3325 // We only want the first authority for a provider to possibly be
3326 // syncable, so if we already added this provider using a different
3327 // authority clear the syncable flag. We copy the provider before
3328 // changing it because the mProviders object contains a reference
3329 // to a provider that we don't want to change.
3330 // Only do this for the second authority since the resulting provider
3331 // object can be the same for all future authorities for this provider.
3332 p = new PackageParser.Provider(p);
3333 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003335 if (!mProviders.containsKey(names[j])) {
3336 mProviders.put(names[j], p);
3337 if (p.info.authority == null) {
3338 p.info.authority = names[j];
3339 } else {
3340 p.info.authority = p.info.authority + ";" + names[j];
3341 }
3342 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3343 Log.d(TAG, "Registered content provider: " + names[j] +
3344 ", className = " + p.info.name +
3345 ", isSyncable = " + p.info.isSyncable);
3346 } else {
3347 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003348 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003349 " (in package " + pkg.applicationInfo.packageName +
3350 "): name already used by "
3351 + ((other != null && other.getComponentName() != null)
3352 ? other.getComponentName().getPackageName() : "?"));
3353 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003354 }
3355 }
3356 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3357 if (r == null) {
3358 r = new StringBuilder(256);
3359 } else {
3360 r.append(' ');
3361 }
3362 r.append(p.info.name);
3363 }
3364 }
3365 if (r != null) {
3366 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3367 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 N = pkg.services.size();
3370 r = null;
3371 for (i=0; i<N; i++) {
3372 PackageParser.Service s = pkg.services.get(i);
3373 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3374 s.info.processName, pkg.applicationInfo.uid);
3375 mServices.addService(s);
3376 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3377 if (r == null) {
3378 r = new StringBuilder(256);
3379 } else {
3380 r.append(' ');
3381 }
3382 r.append(s.info.name);
3383 }
3384 }
3385 if (r != null) {
3386 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3387 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 N = pkg.receivers.size();
3390 r = null;
3391 for (i=0; i<N; i++) {
3392 PackageParser.Activity a = pkg.receivers.get(i);
3393 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3394 a.info.processName, pkg.applicationInfo.uid);
3395 mReceivers.addActivity(a, "receiver");
3396 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3397 if (r == null) {
3398 r = new StringBuilder(256);
3399 } else {
3400 r.append(' ');
3401 }
3402 r.append(a.info.name);
3403 }
3404 }
3405 if (r != null) {
3406 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3407 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003408
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 N = pkg.activities.size();
3410 r = null;
3411 for (i=0; i<N; i++) {
3412 PackageParser.Activity a = pkg.activities.get(i);
3413 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3414 a.info.processName, pkg.applicationInfo.uid);
3415 mActivities.addActivity(a, "activity");
3416 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3417 if (r == null) {
3418 r = new StringBuilder(256);
3419 } else {
3420 r.append(' ');
3421 }
3422 r.append(a.info.name);
3423 }
3424 }
3425 if (r != null) {
3426 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3427 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 N = pkg.permissionGroups.size();
3430 r = null;
3431 for (i=0; i<N; i++) {
3432 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3433 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3434 if (cur == null) {
3435 mPermissionGroups.put(pg.info.name, pg);
3436 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3437 if (r == null) {
3438 r = new StringBuilder(256);
3439 } else {
3440 r.append(' ');
3441 }
3442 r.append(pg.info.name);
3443 }
3444 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003445 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003446 + pg.info.packageName + " ignored: original from "
3447 + cur.info.packageName);
3448 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3449 if (r == null) {
3450 r = new StringBuilder(256);
3451 } else {
3452 r.append(' ');
3453 }
3454 r.append("DUP:");
3455 r.append(pg.info.name);
3456 }
3457 }
3458 }
3459 if (r != null) {
3460 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3461 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 N = pkg.permissions.size();
3464 r = null;
3465 for (i=0; i<N; i++) {
3466 PackageParser.Permission p = pkg.permissions.get(i);
3467 HashMap<String, BasePermission> permissionMap =
3468 p.tree ? mSettings.mPermissionTrees
3469 : mSettings.mPermissions;
3470 p.group = mPermissionGroups.get(p.info.group);
3471 if (p.info.group == null || p.group != null) {
3472 BasePermission bp = permissionMap.get(p.info.name);
3473 if (bp == null) {
3474 bp = new BasePermission(p.info.name, p.info.packageName,
3475 BasePermission.TYPE_NORMAL);
3476 permissionMap.put(p.info.name, bp);
3477 }
3478 if (bp.perm == null) {
3479 if (bp.sourcePackage == null
3480 || bp.sourcePackage.equals(p.info.packageName)) {
3481 BasePermission tree = findPermissionTreeLP(p.info.name);
3482 if (tree == null
3483 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003484 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 bp.perm = p;
3486 bp.uid = pkg.applicationInfo.uid;
3487 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3488 if (r == null) {
3489 r = new StringBuilder(256);
3490 } else {
3491 r.append(' ');
3492 }
3493 r.append(p.info.name);
3494 }
3495 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003496 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 + p.info.packageName + " ignored: base tree "
3498 + tree.name + " is from package "
3499 + tree.sourcePackage);
3500 }
3501 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003502 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 + p.info.packageName + " ignored: original from "
3504 + bp.sourcePackage);
3505 }
3506 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3507 if (r == null) {
3508 r = new StringBuilder(256);
3509 } else {
3510 r.append(' ');
3511 }
3512 r.append("DUP:");
3513 r.append(p.info.name);
3514 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003515 if (bp.perm == p) {
3516 bp.protectionLevel = p.info.protectionLevel;
3517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003519 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 + p.info.packageName + " ignored: no group "
3521 + p.group);
3522 }
3523 }
3524 if (r != null) {
3525 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3526 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003527
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 N = pkg.instrumentation.size();
3529 r = null;
3530 for (i=0; i<N; i++) {
3531 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3532 a.info.packageName = pkg.applicationInfo.packageName;
3533 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3534 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3535 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003536 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003537 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3539 if (r == null) {
3540 r = new StringBuilder(256);
3541 } else {
3542 r.append(' ');
3543 }
3544 r.append(a.info.name);
3545 }
3546 }
3547 if (r != null) {
3548 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3549 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003550
Dianne Hackborn854060af2009-07-09 18:14:31 -07003551 if (pkg.protectedBroadcasts != null) {
3552 N = pkg.protectedBroadcasts.size();
3553 for (i=0; i<N; i++) {
3554 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3555 }
3556 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003558 pkgSetting.setTimeStamp(scanFileTime);
3559 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003560
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 return pkg;
3562 }
3563
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003564 private void killApplication(String pkgName, int uid) {
3565 // Request the ActivityManager to kill the process(only for existing packages)
3566 // so that we do not end up in a confused state while the user is still using the older
3567 // version of the application while the new one gets installed.
3568 IActivityManager am = ActivityManagerNative.getDefault();
3569 if (am != null) {
3570 try {
3571 am.killApplicationWithUid(pkgName, uid);
3572 } catch (RemoteException e) {
3573 }
3574 }
3575 }
3576
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003577 // Return the path of the directory that will contain the native binaries
3578 // of a given installed package. This is relative to the data path.
3579 //
Kenny Root85387d72010-08-26 10:13:11 -07003580 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3581 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3582 if (nativeLibraryDir != null) {
3583 return new File(nativeLibraryDir);
3584 } else {
3585 // Fall back for old packages
3586 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3587 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003588 }
3589
Kenny Root85387d72010-08-26 10:13:11 -07003590 // Convenience call for removeNativeBinariesLI(File)
3591 private void removeNativeBinariesLI(PackageParser.Package pkg) {
3592 File nativeLibraryDir = getNativeBinaryDirForPackage(pkg);
3593 removeNativeBinariesLI(nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003594 }
3595
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003596 // Remove the native binaries of a given package. This simply
3597 // gets rid of the files in the 'lib' sub-directory.
Kenny Root85387d72010-08-26 10:13:11 -07003598 public void removeNativeBinariesLI(File binaryDir) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003599 if (DEBUG_NATIVE) {
Kenny Root85387d72010-08-26 10:13:11 -07003600 Slog.w(TAG, "Deleting native binaries from: " + binaryDir.getPath());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003601 }
3602
3603 // Just remove any file in the directory. Since the directory
3604 // is owned by the 'system' UID, the application is not supposed
3605 // to have written anything there.
3606 //
3607 if (binaryDir.exists()) {
Kenny Root85387d72010-08-26 10:13:11 -07003608 File[] binaries = binaryDir.listFiles();
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003609 if (binaries != null) {
Kenny Root85387d72010-08-26 10:13:11 -07003610 for (int nn = 0; nn < binaries.length; nn++) {
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003611 if (DEBUG_NATIVE) {
Kenny Root85387d72010-08-26 10:13:11 -07003612 Slog.d(TAG, " Deleting " + binaries[nn].getName());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003613 }
3614 if (!binaries[nn].delete()) {
Kenny Root85387d72010-08-26 10:13:11 -07003615 Slog.w(TAG, "Could not delete native binary: " + binaries[nn].getPath());
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003616 }
3617 }
3618 }
3619 // Do not delete 'lib' directory itself, or this will prevent
3620 // installation of future updates.
3621 }
3622 }
3623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3625 if (chatty && Config.LOGD) Log.d(
3626 TAG, "Removing package " + pkg.applicationInfo.packageName );
3627
3628 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 mPackages.remove(pkg.applicationInfo.packageName);
3632 if (pkg.mPath != null) {
3633 mAppDirs.remove(pkg.mPath);
3634 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 PackageSetting ps = (PackageSetting)pkg.mExtras;
3637 if (ps != null && ps.sharedUser != null) {
3638 // XXX don't do this until the data is removed.
3639 if (false) {
3640 ps.sharedUser.packages.remove(ps);
3641 if (ps.sharedUser.packages.size() == 0) {
3642 // Remove.
3643 }
3644 }
3645 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 int N = pkg.providers.size();
3648 StringBuilder r = null;
3649 int i;
3650 for (i=0; i<N; i++) {
3651 PackageParser.Provider p = pkg.providers.get(i);
3652 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3653 p.info.name));
3654 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 /* The is another ContentProvider with this authority when
3657 * this app was installed so this authority is null,
3658 * Ignore it as we don't have to unregister the provider.
3659 */
3660 continue;
3661 }
3662 String names[] = p.info.authority.split(";");
3663 for (int j = 0; j < names.length; j++) {
3664 if (mProviders.get(names[j]) == p) {
3665 mProviders.remove(names[j]);
3666 if (chatty && Config.LOGD) Log.d(
3667 TAG, "Unregistered content provider: " + names[j] +
3668 ", className = " + p.info.name +
3669 ", isSyncable = " + p.info.isSyncable);
3670 }
3671 }
3672 if (chatty) {
3673 if (r == null) {
3674 r = new StringBuilder(256);
3675 } else {
3676 r.append(' ');
3677 }
3678 r.append(p.info.name);
3679 }
3680 }
3681 if (r != null) {
3682 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3683 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 N = pkg.services.size();
3686 r = null;
3687 for (i=0; i<N; i++) {
3688 PackageParser.Service s = pkg.services.get(i);
3689 mServices.removeService(s);
3690 if (chatty) {
3691 if (r == null) {
3692 r = new StringBuilder(256);
3693 } else {
3694 r.append(' ');
3695 }
3696 r.append(s.info.name);
3697 }
3698 }
3699 if (r != null) {
3700 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3701 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 N = pkg.receivers.size();
3704 r = null;
3705 for (i=0; i<N; i++) {
3706 PackageParser.Activity a = pkg.receivers.get(i);
3707 mReceivers.removeActivity(a, "receiver");
3708 if (chatty) {
3709 if (r == null) {
3710 r = new StringBuilder(256);
3711 } else {
3712 r.append(' ');
3713 }
3714 r.append(a.info.name);
3715 }
3716 }
3717 if (r != null) {
3718 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 N = pkg.activities.size();
3722 r = null;
3723 for (i=0; i<N; i++) {
3724 PackageParser.Activity a = pkg.activities.get(i);
3725 mActivities.removeActivity(a, "activity");
3726 if (chatty) {
3727 if (r == null) {
3728 r = new StringBuilder(256);
3729 } else {
3730 r.append(' ');
3731 }
3732 r.append(a.info.name);
3733 }
3734 }
3735 if (r != null) {
3736 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3737 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 N = pkg.permissions.size();
3740 r = null;
3741 for (i=0; i<N; i++) {
3742 PackageParser.Permission p = pkg.permissions.get(i);
3743 boolean tree = false;
3744 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3745 if (bp == null) {
3746 tree = true;
3747 bp = mSettings.mPermissionTrees.get(p.info.name);
3748 }
3749 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003750 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 if (chatty) {
3752 if (r == null) {
3753 r = new StringBuilder(256);
3754 } else {
3755 r.append(' ');
3756 }
3757 r.append(p.info.name);
3758 }
3759 }
3760 }
3761 if (r != null) {
3762 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3763 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003764
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 N = pkg.instrumentation.size();
3766 r = null;
3767 for (i=0; i<N; i++) {
3768 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003769 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003770 if (chatty) {
3771 if (r == null) {
3772 r = new StringBuilder(256);
3773 } else {
3774 r.append(' ');
3775 }
3776 r.append(a.info.name);
3777 }
3778 }
3779 if (r != null) {
3780 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3781 }
3782 }
3783 }
3784
3785 private static final boolean isPackageFilename(String name) {
3786 return name != null && name.endsWith(".apk");
3787 }
3788
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003789 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3790 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3791 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3792 return true;
3793 }
3794 }
3795 return false;
3796 }
3797
3798 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003799 PackageParser.Package pkgInfo, boolean grantPermissions,
3800 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 // Make sure there are no dangling permission trees.
3802 Iterator<BasePermission> it = mSettings.mPermissionTrees
3803 .values().iterator();
3804 while (it.hasNext()) {
3805 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003806 if (bp.packageSetting == null) {
3807 // We may not yet have parsed the package, so just see if
3808 // we still know about its settings.
3809 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3810 }
3811 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003812 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 + " from package " + bp.sourcePackage);
3814 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003815 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3816 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3817 Slog.i(TAG, "Removing old permission tree: " + bp.name
3818 + " from package " + bp.sourcePackage);
3819 grantPermissions = true;
3820 it.remove();
3821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003822 }
3823 }
3824
3825 // Make sure all dynamic permissions have been assigned to a package,
3826 // and make sure there are no dangling permissions.
3827 it = mSettings.mPermissions.values().iterator();
3828 while (it.hasNext()) {
3829 BasePermission bp = it.next();
3830 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3831 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3832 + bp.name + " pkg=" + bp.sourcePackage
3833 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003834 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 BasePermission tree = findPermissionTreeLP(bp.name);
3836 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003837 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 bp.perm = new PackageParser.Permission(tree.perm.owner,
3839 new PermissionInfo(bp.pendingInfo));
3840 bp.perm.info.packageName = tree.perm.info.packageName;
3841 bp.perm.info.name = bp.name;
3842 bp.uid = tree.uid;
3843 }
3844 }
3845 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003846 if (bp.packageSetting == null) {
3847 // We may not yet have parsed the package, so just see if
3848 // we still know about its settings.
3849 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3850 }
3851 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003852 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 + " from package " + bp.sourcePackage);
3854 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003855 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3856 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3857 Slog.i(TAG, "Removing old permission: " + bp.name
3858 + " from package " + bp.sourcePackage);
3859 grantPermissions = true;
3860 it.remove();
3861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 }
3863 }
3864
3865 // Now update the permissions for all packages, in particular
3866 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003867 if (grantPermissions) {
3868 for (PackageParser.Package pkg : mPackages.values()) {
3869 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003870 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003871 }
3872 }
3873 }
3874
3875 if (pkgInfo != null) {
3876 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 }
3878 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3881 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3882 if (ps == null) {
3883 return;
3884 }
3885 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003886 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003888 if (replace) {
3889 ps.permissionsFixed = false;
3890 if (gp == ps) {
3891 gp.grantedPermissions.clear();
3892 gp.gids = mGlobalGids;
3893 }
3894 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 if (gp.gids == null) {
3897 gp.gids = mGlobalGids;
3898 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 final int N = pkg.requestedPermissions.size();
3901 for (int i=0; i<N; i++) {
3902 String name = pkg.requestedPermissions.get(i);
3903 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 if (false) {
3905 if (gp != ps) {
3906 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003907 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 }
3909 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003910 if (bp != null && bp.packageSetting != null) {
3911 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003912 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003913 boolean allowedSig = false;
3914 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3915 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003917 } else if (bp.packageSetting == null) {
3918 // This permission is invalid; skip it.
3919 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003920 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3921 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3922 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003924 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003925 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003926 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003927 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003928 // For updated system applications, the signatureOrSystem permission
3929 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003930 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003931 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3932 if(sysPs.grantedPermissions.contains(perm)) {
3933 allowed = true;
3934 } else {
3935 allowed = false;
3936 }
3937 } else {
3938 allowed = true;
3939 }
3940 }
3941 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003942 if (allowed) {
3943 allowedSig = true;
3944 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 } else {
3946 allowed = false;
3947 }
3948 if (false) {
3949 if (gp != ps) {
3950 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3951 }
3952 }
3953 if (allowed) {
3954 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3955 && ps.permissionsFixed) {
3956 // If this is an existing, non-system package, then
3957 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003958 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003960 // Except... if this is a permission that was added
3961 // to the platform (note: need to only do this when
3962 // updating the platform).
3963 final int NP = PackageParser.NEW_PERMISSIONS.length;
3964 for (int ip=0; ip<NP; ip++) {
3965 final PackageParser.NewPermissionInfo npi
3966 = PackageParser.NEW_PERMISSIONS[ip];
3967 if (npi.name.equals(perm)
3968 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3969 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003970 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003971 + pkg.packageName);
3972 break;
3973 }
3974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003975 }
3976 }
3977 if (allowed) {
3978 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003979 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 gp.grantedPermissions.add(perm);
3981 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003982 } else if (!ps.haveGids) {
3983 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 }
3985 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003986 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 + " to package " + pkg.packageName
3988 + " because it was previously installed without");
3989 }
3990 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003991 if (gp.grantedPermissions.remove(perm)) {
3992 changedPermission = true;
3993 gp.gids = removeInts(gp.gids, bp.gids);
3994 Slog.i(TAG, "Un-granting permission " + perm
3995 + " from package " + pkg.packageName
3996 + " (protectionLevel=" + bp.protectionLevel
3997 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3998 + ")");
3999 } else {
4000 Slog.w(TAG, "Not granting permission " + perm
4001 + " to package " + pkg.packageName
4002 + " (protectionLevel=" + bp.protectionLevel
4003 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
4004 + ")");
4005 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 }
4007 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004008 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 + " in package " + pkg.packageName);
4010 }
4011 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004012
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004013 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07004014 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
4015 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004016 // This is the first that we have heard about this package, so the
4017 // permissions we have now selected are fixed until explicitly
4018 // changed.
4019 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004020 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07004021 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004022 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004023
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004024 private final class ActivityIntentResolver
4025 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004026 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004028 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 }
4030
Mihai Preda074edef2009-05-18 17:13:31 +02004031 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004033 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004034 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4035 }
4036
Mihai Predaeae850c2009-05-13 10:13:48 +02004037 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4038 ArrayList<PackageParser.Activity> packageActivities) {
4039 if (packageActivities == null) {
4040 return null;
4041 }
4042 mFlags = flags;
4043 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4044 int N = packageActivities.size();
4045 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4046 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004047
4048 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004049 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004050 intentFilters = packageActivities.get(i).intents;
4051 if (intentFilters != null && intentFilters.size() > 0) {
4052 listCut.add(intentFilters);
4053 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004054 }
4055 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4056 }
4057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004058 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004059 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004060 if (SHOW_INFO || Config.LOGV) Log.v(
4061 TAG, " " + type + " " +
4062 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4063 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4064 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004065 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4067 if (SHOW_INFO || Config.LOGV) {
4068 Log.v(TAG, " IntentFilter:");
4069 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4070 }
4071 if (!intent.debugCheck()) {
4072 Log.w(TAG, "==> For Activity " + a.info.name);
4073 }
4074 addFilter(intent);
4075 }
4076 }
4077
4078 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004079 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004080 if (SHOW_INFO || Config.LOGV) Log.v(
4081 TAG, " " + type + " " +
4082 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4083 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4084 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004085 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4087 if (SHOW_INFO || Config.LOGV) {
4088 Log.v(TAG, " IntentFilter:");
4089 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4090 }
4091 removeFilter(intent);
4092 }
4093 }
4094
4095 @Override
4096 protected boolean allowFilterResult(
4097 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4098 ActivityInfo filterAi = filter.activity.info;
4099 for (int i=dest.size()-1; i>=0; i--) {
4100 ActivityInfo destAi = dest.get(i).activityInfo;
4101 if (destAi.name == filterAi.name
4102 && destAi.packageName == filterAi.packageName) {
4103 return false;
4104 }
4105 }
4106 return true;
4107 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004109 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004110 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4111 return info.activity.owner.packageName;
4112 }
4113
4114 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004115 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4116 int match) {
4117 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4118 return null;
4119 }
4120 final PackageParser.Activity activity = info.activity;
4121 if (mSafeMode && (activity.info.applicationInfo.flags
4122 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4123 return null;
4124 }
4125 final ResolveInfo res = new ResolveInfo();
4126 res.activityInfo = PackageParser.generateActivityInfo(activity,
4127 mFlags);
4128 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4129 res.filter = info;
4130 }
4131 res.priority = info.getPriority();
4132 res.preferredOrder = activity.owner.mPreferredOrder;
4133 //System.out.println("Result: " + res.activityInfo.className +
4134 // " = " + res.priority);
4135 res.match = match;
4136 res.isDefault = info.hasDefault;
4137 res.labelRes = info.labelRes;
4138 res.nonLocalizedLabel = info.nonLocalizedLabel;
4139 res.icon = info.icon;
4140 return res;
4141 }
4142
4143 @Override
4144 protected void sortResults(List<ResolveInfo> results) {
4145 Collections.sort(results, mResolvePrioritySorter);
4146 }
4147
4148 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004149 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004151 out.print(prefix); out.print(
4152 Integer.toHexString(System.identityHashCode(filter.activity)));
4153 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004154 out.print(filter.activity.getComponentShortName());
4155 out.print(" filter ");
4156 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 }
4158
4159// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4160// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4161// final List<ResolveInfo> retList = Lists.newArrayList();
4162// while (i.hasNext()) {
4163// final ResolveInfo resolveInfo = i.next();
4164// if (isEnabledLP(resolveInfo.activityInfo)) {
4165// retList.add(resolveInfo);
4166// }
4167// }
4168// return retList;
4169// }
4170
4171 // Keys are String (activity class name), values are Activity.
4172 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4173 = new HashMap<ComponentName, PackageParser.Activity>();
4174 private int mFlags;
4175 }
4176
4177 private final class ServiceIntentResolver
4178 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004179 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004181 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 }
4183
Mihai Preda074edef2009-05-18 17:13:31 +02004184 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004185 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004186 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4188 }
4189
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004190 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4191 ArrayList<PackageParser.Service> packageServices) {
4192 if (packageServices == null) {
4193 return null;
4194 }
4195 mFlags = flags;
4196 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4197 int N = packageServices.size();
4198 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4199 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4200
4201 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4202 for (int i = 0; i < N; ++i) {
4203 intentFilters = packageServices.get(i).intents;
4204 if (intentFilters != null && intentFilters.size() > 0) {
4205 listCut.add(intentFilters);
4206 }
4207 }
4208 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4209 }
4210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004212 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004213 if (SHOW_INFO || Config.LOGV) Log.v(
4214 TAG, " " + (s.info.nonLocalizedLabel != null
4215 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4216 if (SHOW_INFO || Config.LOGV) Log.v(
4217 TAG, " Class=" + s.info.name);
4218 int NI = s.intents.size();
4219 int j;
4220 for (j=0; j<NI; j++) {
4221 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4222 if (SHOW_INFO || Config.LOGV) {
4223 Log.v(TAG, " IntentFilter:");
4224 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4225 }
4226 if (!intent.debugCheck()) {
4227 Log.w(TAG, "==> For Service " + s.info.name);
4228 }
4229 addFilter(intent);
4230 }
4231 }
4232
4233 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004234 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 if (SHOW_INFO || Config.LOGV) Log.v(
4236 TAG, " " + (s.info.nonLocalizedLabel != null
4237 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4238 if (SHOW_INFO || Config.LOGV) Log.v(
4239 TAG, " Class=" + s.info.name);
4240 int NI = s.intents.size();
4241 int j;
4242 for (j=0; j<NI; j++) {
4243 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4244 if (SHOW_INFO || Config.LOGV) {
4245 Log.v(TAG, " IntentFilter:");
4246 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4247 }
4248 removeFilter(intent);
4249 }
4250 }
4251
4252 @Override
4253 protected boolean allowFilterResult(
4254 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4255 ServiceInfo filterSi = filter.service.info;
4256 for (int i=dest.size()-1; i>=0; i--) {
4257 ServiceInfo destAi = dest.get(i).serviceInfo;
4258 if (destAi.name == filterSi.name
4259 && destAi.packageName == filterSi.packageName) {
4260 return false;
4261 }
4262 }
4263 return true;
4264 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004265
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004266 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004267 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4268 return info.service.owner.packageName;
4269 }
4270
4271 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004272 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4273 int match) {
4274 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4275 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4276 return null;
4277 }
4278 final PackageParser.Service service = info.service;
4279 if (mSafeMode && (service.info.applicationInfo.flags
4280 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4281 return null;
4282 }
4283 final ResolveInfo res = new ResolveInfo();
4284 res.serviceInfo = PackageParser.generateServiceInfo(service,
4285 mFlags);
4286 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4287 res.filter = filter;
4288 }
4289 res.priority = info.getPriority();
4290 res.preferredOrder = service.owner.mPreferredOrder;
4291 //System.out.println("Result: " + res.activityInfo.className +
4292 // " = " + res.priority);
4293 res.match = match;
4294 res.isDefault = info.hasDefault;
4295 res.labelRes = info.labelRes;
4296 res.nonLocalizedLabel = info.nonLocalizedLabel;
4297 res.icon = info.icon;
4298 return res;
4299 }
4300
4301 @Override
4302 protected void sortResults(List<ResolveInfo> results) {
4303 Collections.sort(results, mResolvePrioritySorter);
4304 }
4305
4306 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004307 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004308 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004309 out.print(prefix); out.print(
4310 Integer.toHexString(System.identityHashCode(filter.service)));
4311 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004312 out.print(filter.service.getComponentShortName());
4313 out.print(" filter ");
4314 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004315 }
4316
4317// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4318// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4319// final List<ResolveInfo> retList = Lists.newArrayList();
4320// while (i.hasNext()) {
4321// final ResolveInfo resolveInfo = (ResolveInfo) i;
4322// if (isEnabledLP(resolveInfo.serviceInfo)) {
4323// retList.add(resolveInfo);
4324// }
4325// }
4326// return retList;
4327// }
4328
4329 // Keys are String (activity class name), values are Activity.
4330 private final HashMap<ComponentName, PackageParser.Service> mServices
4331 = new HashMap<ComponentName, PackageParser.Service>();
4332 private int mFlags;
4333 };
4334
4335 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4336 new Comparator<ResolveInfo>() {
4337 public int compare(ResolveInfo r1, ResolveInfo r2) {
4338 int v1 = r1.priority;
4339 int v2 = r2.priority;
4340 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4341 if (v1 != v2) {
4342 return (v1 > v2) ? -1 : 1;
4343 }
4344 v1 = r1.preferredOrder;
4345 v2 = r2.preferredOrder;
4346 if (v1 != v2) {
4347 return (v1 > v2) ? -1 : 1;
4348 }
4349 if (r1.isDefault != r2.isDefault) {
4350 return r1.isDefault ? -1 : 1;
4351 }
4352 v1 = r1.match;
4353 v2 = r2.match;
4354 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4355 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4356 }
4357 };
4358
4359 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4360 new Comparator<ProviderInfo>() {
4361 public int compare(ProviderInfo p1, ProviderInfo p2) {
4362 final int v1 = p1.initOrder;
4363 final int v2 = p2.initOrder;
4364 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4365 }
4366 };
4367
Kenny Root93565c4b2010-06-18 15:46:06 -07004368 private static final boolean DEBUG_OBB = false;
4369
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004370 private static final void sendPackageBroadcast(String action, String pkg,
4371 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 IActivityManager am = ActivityManagerNative.getDefault();
4373 if (am != null) {
4374 try {
4375 final Intent intent = new Intent(action,
4376 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4377 if (extras != null) {
4378 intent.putExtras(extras);
4379 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004380 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004381 am.broadcastIntent(null, intent, null, finishedReceiver,
4382 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004383 } catch (RemoteException ex) {
4384 }
4385 }
4386 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004387
4388 public String nextPackageToClean(String lastPackage) {
4389 synchronized (mPackages) {
4390 if (!mMediaMounted) {
4391 // If the external storage is no longer mounted at this point,
4392 // the caller may not have been able to delete all of this
4393 // packages files and can not delete any more. Bail.
4394 return null;
4395 }
4396 if (lastPackage != null) {
4397 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4398 }
4399 return mSettings.mPackagesToBeCleaned.size() > 0
4400 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4401 }
4402 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004403
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004404 void schedulePackageCleaning(String packageName) {
4405 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4406 }
4407
4408 void startCleaningPackages() {
4409 synchronized (mPackages) {
4410 if (!mMediaMounted) {
4411 return;
4412 }
4413 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4414 return;
4415 }
4416 }
4417 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4418 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4419 IActivityManager am = ActivityManagerNative.getDefault();
4420 if (am != null) {
4421 try {
4422 am.startService(null, intent, null);
4423 } catch (RemoteException e) {
4424 }
4425 }
4426 }
4427
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004428 private final class AppDirObserver extends FileObserver {
4429 public AppDirObserver(String path, int mask, boolean isrom) {
4430 super(path, mask);
4431 mRootDir = path;
4432 mIsRom = isrom;
4433 }
4434
4435 public void onEvent(int event, String path) {
4436 String removedPackage = null;
4437 int removedUid = -1;
4438 String addedPackage = null;
4439 int addedUid = -1;
4440
4441 synchronized (mInstallLock) {
4442 String fullPathStr = null;
4443 File fullPath = null;
4444 if (path != null) {
4445 fullPath = new File(mRootDir, path);
4446 fullPathStr = fullPath.getPath();
4447 }
4448
4449 if (Config.LOGV) Log.v(
4450 TAG, "File " + fullPathStr + " changed: "
4451 + Integer.toHexString(event));
4452
4453 if (!isPackageFilename(path)) {
4454 if (Config.LOGV) Log.v(
4455 TAG, "Ignoring change of non-package file: " + fullPathStr);
4456 return;
4457 }
4458
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004459 // Ignore packages that are being installed or
4460 // have just been installed.
4461 if (ignoreCodePath(fullPathStr)) {
4462 return;
4463 }
4464 PackageParser.Package p = null;
4465 synchronized (mPackages) {
4466 p = mAppDirs.get(fullPathStr);
4467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004469 if (p != null) {
4470 removePackageLI(p, true);
4471 removedPackage = p.applicationInfo.packageName;
4472 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004473 }
4474 }
4475
4476 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004477 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004478 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004479 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4480 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004481 PackageParser.PARSE_CHATTY |
4482 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004483 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004484 if (p != null) {
4485 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004486 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004487 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004488 }
4489 addedPackage = p.applicationInfo.packageName;
4490 addedUid = p.applicationInfo.uid;
4491 }
4492 }
4493 }
4494
4495 synchronized (mPackages) {
4496 mSettings.writeLP();
4497 }
4498 }
4499
4500 if (removedPackage != null) {
4501 Bundle extras = new Bundle(1);
4502 extras.putInt(Intent.EXTRA_UID, removedUid);
4503 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004504 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4505 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 }
4507 if (addedPackage != null) {
4508 Bundle extras = new Bundle(1);
4509 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004510 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4511 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004512 }
4513 }
4514
4515 private final String mRootDir;
4516 private final boolean mIsRom;
4517 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004519 /* Called when a downloaded package installation has been confirmed by the user */
4520 public void installPackage(
4521 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004522 installPackage(packageURI, observer, flags, null);
4523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004524
Jacek Surazski65e13172009-04-28 15:26:38 +02004525 /* Called when a downloaded package installation has been confirmed by the user */
4526 public void installPackage(
4527 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4528 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004529 mContext.enforceCallingOrSelfPermission(
4530 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004531
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004532 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004533 msg.obj = new InstallParams(packageURI, observer, flags,
4534 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004535 mHandler.sendMessage(msg);
4536 }
4537
Christopher Tate1bb69062010-02-19 17:02:12 -08004538 public void finishPackageInstall(int token) {
4539 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4540 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4541 mHandler.sendMessage(msg);
4542 }
4543
Kenny Root93565c4b2010-06-18 15:46:06 -07004544 public void setPackageObbPath(String packageName, String path) {
4545 if (DEBUG_OBB)
4546 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4547 PackageSetting pkgSetting;
4548 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004549 final int permission = mContext.checkCallingPermission(
4550 android.Manifest.permission.INSTALL_PACKAGES);
4551 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004552 synchronized (mPackages) {
4553 pkgSetting = mSettings.mPackages.get(packageName);
4554 if (pkgSetting == null) {
4555 throw new IllegalArgumentException("Unknown package: " + packageName);
4556 }
4557 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4558 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4559 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4560 + pkgSetting.userId);
4561 }
4562 pkgSetting.obbPathString = path;
4563 mSettings.writeLP();
4564 }
4565 }
4566
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004567 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004568 // Queue up an async operation since the package installation may take a little while.
4569 mHandler.post(new Runnable() {
4570 public void run() {
4571 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004572 // Result object to be returned
4573 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004574 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004575 res.uid = -1;
4576 res.pkg = null;
4577 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004578 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004579 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004580 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004581 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004582 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004583 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004584 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004585
4586 // A restore should be performed at this point if (a) the install
4587 // succeeded, (b) the operation is not an update, and (c) the new
4588 // package has a backupAgent defined.
4589 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004590 boolean doRestore = (!update
4591 && res.pkg != null
4592 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004593
4594 // Set up the post-install work request bookkeeping. This will be used
4595 // and cleaned up by the post-install event handling regardless of whether
4596 // there's a restore pass performed. Token values are >= 1.
4597 int token;
4598 if (mNextInstallToken < 0) mNextInstallToken = 1;
4599 token = mNextInstallToken++;
4600
4601 PostInstallData data = new PostInstallData(args, res);
4602 mRunningInstalls.put(token, data);
4603 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4604
4605 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4606 // Pass responsibility to the Backup Manager. It will perform a
4607 // restore if appropriate, then pass responsibility back to the
4608 // Package Manager to run the post-install observer callbacks
4609 // and broadcasts.
4610 IBackupManager bm = IBackupManager.Stub.asInterface(
4611 ServiceManager.getService(Context.BACKUP_SERVICE));
4612 if (bm != null) {
4613 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4614 + " to BM for possible restore");
4615 try {
4616 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4617 } catch (RemoteException e) {
4618 // can't happen; the backup manager is local
4619 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004620 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004621 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004622 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004623 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004624 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004625 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004626 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004627 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004628
4629 if (!doRestore) {
4630 // No restore possible, or the Backup Manager was mysteriously not
4631 // available -- just fire the post-install work request directly.
4632 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4633 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4634 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004636 }
4637 });
4638 }
4639
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004640 abstract class HandlerParams {
4641 final static int MAX_RETRIES = 4;
4642 int retry = 0;
4643 final void startCopy() {
4644 try {
4645 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4646 retry++;
4647 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004648 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004649 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4650 handleServiceError();
4651 return;
4652 } else {
4653 handleStartCopy();
4654 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4655 mHandler.sendEmptyMessage(MCS_UNBIND);
4656 }
4657 } catch (RemoteException e) {
4658 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4659 mHandler.sendEmptyMessage(MCS_RECONNECT);
4660 }
4661 handleReturnCode();
4662 }
4663
4664 final void serviceError() {
4665 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4666 handleServiceError();
4667 handleReturnCode();
4668 }
4669 abstract void handleStartCopy() throws RemoteException;
4670 abstract void handleServiceError();
4671 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004672 }
4673
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004674 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004675 final IPackageInstallObserver observer;
4676 int flags;
4677 final Uri packageURI;
4678 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004679 private InstallArgs mArgs;
4680 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004681 InstallParams(Uri packageURI,
4682 IPackageInstallObserver observer, int flags,
4683 String installerPackageName) {
4684 this.packageURI = packageURI;
4685 this.flags = flags;
4686 this.observer = observer;
4687 this.installerPackageName = installerPackageName;
4688 }
4689
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004690 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4691 String packageName = pkgLite.packageName;
4692 int installLocation = pkgLite.installLocation;
4693 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4694 synchronized (mPackages) {
4695 PackageParser.Package pkg = mPackages.get(packageName);
4696 if (pkg != null) {
4697 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4698 // Check for updated system application.
4699 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4700 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004701 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004702 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4703 }
4704 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4705 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004706 if (onSd) {
4707 // Install flag overrides everything.
4708 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4709 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004710 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004711 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4712 // Application explicitly specified internal.
4713 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4714 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4715 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004716 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004717 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004718 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004719 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4720 }
4721 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004722 }
4723 }
4724 } else {
4725 // Invalid install. Return error code
4726 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4727 }
4728 }
4729 }
4730 // All the special cases have been taken care of.
4731 // Return result based on recommended install location.
4732 if (onSd) {
4733 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4734 }
4735 return pkgLite.recommendedInstallLocation;
4736 }
4737
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004738 /*
4739 * Invoke remote method to get package information and install
4740 * location values. Override install location based on default
4741 * policy if needed and then create install arguments based
4742 * on the install location.
4743 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004744 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004745 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004746 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4747 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004748 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4749 if (onInt && onSd) {
4750 // Check if both bits are set.
4751 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4752 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4753 } else if (fwdLocked && onSd) {
4754 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004755 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004756 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004757 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004758 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004759 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004760 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004761 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4762 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4763 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4764 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4765 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004766 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4767 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4768 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004769 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4770 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004771 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004772 // Override with defaults if needed.
4773 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004774 if (!onSd && !onInt) {
4775 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004776 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4777 // Set the flag to install on external media.
4778 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004779 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004780 } else {
4781 // Make sure the flag for installing on external
4782 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004783 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004784 flags &= ~PackageManager.INSTALL_EXTERNAL;
4785 }
4786 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004787 }
4788 }
4789 // Create the file args now.
4790 mArgs = createInstallArgs(this);
4791 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4792 // Create copy only if we are not in an erroneous state.
4793 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004794 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004795 }
4796 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004797 }
4798
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004799 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004800 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004801 // If mArgs is null, then MCS couldn't be reached. When it
4802 // reconnects, it will try again to install. At that point, this
4803 // will succeed.
4804 if (mArgs != null) {
4805 processPendingInstall(mArgs, mRet);
4806 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004807 }
4808
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004809 @Override
4810 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004811 mArgs = createInstallArgs(this);
4812 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004813 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004814 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004815
4816 /*
4817 * Utility class used in movePackage api.
4818 * srcArgs and targetArgs are not set for invalid flags and make
4819 * sure to do null checks when invoking methods on them.
4820 * We probably want to return ErrorPrams for both failed installs
4821 * and moves.
4822 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004823 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004824 final IPackageMoveObserver observer;
4825 final int flags;
4826 final String packageName;
4827 final InstallArgs srcArgs;
4828 final InstallArgs targetArgs;
4829 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004830
4831 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4832 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004833 this.srcArgs = srcArgs;
4834 this.observer = observer;
4835 this.flags = flags;
4836 this.packageName = packageName;
4837 if (srcArgs != null) {
4838 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004839 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004840 } else {
4841 targetArgs = null;
4842 }
4843 }
4844
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004845 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004846 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4847 // Check for storage space on target medium
4848 if (!targetArgs.checkFreeStorage(mContainerService)) {
4849 Log.w(TAG, "Insufficient storage to install");
4850 return;
4851 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004852 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004853 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004854 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004855 if (DEBUG_SD_INSTALL) {
4856 StringBuilder builder = new StringBuilder();
4857 if (srcArgs != null) {
4858 builder.append("src: ");
4859 builder.append(srcArgs.getCodePath());
4860 }
4861 if (targetArgs != null) {
4862 builder.append(" target : ");
4863 builder.append(targetArgs.getCodePath());
4864 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004865 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004866 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004867 }
4868
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004869 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004870 void handleReturnCode() {
4871 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004872 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4873 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4874 currentStatus = PackageManager.MOVE_SUCCEEDED;
4875 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4876 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4877 }
4878 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004879 }
4880
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004881 @Override
4882 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004883 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004884 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004885 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004886
4887 private InstallArgs createInstallArgs(InstallParams params) {
4888 if (installOnSd(params.flags)) {
4889 return new SdInstallArgs(params);
4890 } else {
4891 return new FileInstallArgs(params);
4892 }
4893 }
4894
Kenny Root85387d72010-08-26 10:13:11 -07004895 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4896 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004897 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004898 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004899 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004900 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004901 }
4902 }
4903
Kenny Root85387d72010-08-26 10:13:11 -07004904 // Used by package mover
4905 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004906 if (installOnSd(flags)) {
4907 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4908 return new SdInstallArgs(packageURI, cid);
4909 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004910 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004911 }
4912 }
4913
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004914 static abstract class InstallArgs {
4915 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004916 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004917 final int flags;
4918 final Uri packageURI;
4919 final String installerPackageName;
4920
4921 InstallArgs(Uri packageURI,
4922 IPackageInstallObserver observer, int flags,
4923 String installerPackageName) {
4924 this.packageURI = packageURI;
4925 this.flags = flags;
4926 this.observer = observer;
4927 this.installerPackageName = installerPackageName;
4928 }
4929
4930 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004931 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004932 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004933 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004934 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004935 abstract String getCodePath();
4936 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004937 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004938 // Need installer lock especially for dex file removal.
4939 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004940 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004941 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004942 }
4943
4944 class FileInstallArgs extends InstallArgs {
4945 File installDir;
4946 String codeFileName;
4947 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004948 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004949 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004950
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004951 FileInstallArgs(InstallParams params) {
4952 super(params.packageURI, params.observer,
4953 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004954 }
4955
Kenny Root85387d72010-08-26 10:13:11 -07004956 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004957 super(null, null, 0, null);
4958 File codeFile = new File(fullCodePath);
4959 installDir = codeFile.getParentFile();
4960 codeFileName = fullCodePath;
4961 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004962 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004963 }
4964
Kenny Root85387d72010-08-26 10:13:11 -07004965 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004966 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004967 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004968 String apkName = getNextCodePath(null, pkgName, ".apk");
4969 codeFileName = new File(installDir, apkName + ".apk").getPath();
4970 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004971 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004972 }
4973
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004974 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4975 return imcs.checkFreeStorage(false, packageURI);
4976 }
4977
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004978 String getCodePath() {
4979 return codeFileName;
4980 }
4981
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004982 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004983 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004984 codeFileName = createTempPackageFile(installDir).getPath();
4985 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004986 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004987 }
4988
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004989 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004990 if (temp) {
4991 // Generate temp file name
4992 createCopyFile();
4993 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004994 // Get a ParcelFileDescriptor to write to the output file
4995 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004996 if (!created) {
4997 try {
4998 codeFile.createNewFile();
4999 // Set permissions
5000 if (!setPermissions()) {
5001 // Failed setting permissions.
5002 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5003 }
5004 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005005 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005006 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5007 }
5008 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005009 ParcelFileDescriptor out = null;
5010 try {
Kenny Root85387d72010-08-26 10:13:11 -07005011 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005012 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005013 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005014 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5015 }
5016 // Copy the resource now
5017 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5018 try {
5019 if (imcs.copyResource(packageURI, out)) {
5020 ret = PackageManager.INSTALL_SUCCEEDED;
5021 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005022 } finally {
5023 try { if (out != null) out.close(); } catch (IOException e) {}
5024 }
Kenny Root85387d72010-08-26 10:13:11 -07005025
5026 if (!temp) {
5027 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5028 }
5029
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005030 return ret;
5031 }
5032
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005033 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005034 if (status != PackageManager.INSTALL_SUCCEEDED) {
5035 cleanUp();
5036 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005037 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005038 }
5039
5040 boolean doRename(int status, final String pkgName, String oldCodePath) {
5041 if (status != PackageManager.INSTALL_SUCCEEDED) {
5042 cleanUp();
5043 return false;
5044 } else {
5045 // Rename based on packageName
5046 File codeFile = new File(getCodePath());
5047 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5048 File desFile = new File(installDir, apkName + ".apk");
5049 if (!codeFile.renameTo(desFile)) {
5050 return false;
5051 }
5052 // Reset paths since the file has been renamed.
5053 codeFileName = desFile.getPath();
5054 resourceFileName = getResourcePathFromCodePath();
5055 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005056 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005057 // Failed setting permissions.
5058 return false;
5059 }
5060 return true;
5061 }
5062 }
5063
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005064 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005065 if (status != PackageManager.INSTALL_SUCCEEDED) {
5066 cleanUp();
5067 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005068 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005069 }
5070
5071 String getResourcePath() {
5072 return resourceFileName;
5073 }
5074
5075 String getResourcePathFromCodePath() {
5076 String codePath = getCodePath();
5077 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5078 String apkNameOnly = getApkName(codePath);
5079 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5080 } else {
5081 return codePath;
5082 }
5083 }
5084
Kenny Root85387d72010-08-26 10:13:11 -07005085 @Override
5086 String getNativeLibraryPath() {
5087 return libraryPath;
5088 }
5089
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005090 private boolean cleanUp() {
5091 boolean ret = true;
5092 String sourceDir = getCodePath();
5093 String publicSourceDir = getResourcePath();
5094 if (sourceDir != null) {
5095 File sourceFile = new File(sourceDir);
5096 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005097 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005098 ret = false;
5099 }
5100 // Delete application's code and resources
5101 sourceFile.delete();
5102 }
5103 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5104 final File publicSourceFile = new File(publicSourceDir);
5105 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005106 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005107 }
5108 if (publicSourceFile.exists()) {
5109 publicSourceFile.delete();
5110 }
5111 }
5112 return ret;
5113 }
5114
5115 void cleanUpResourcesLI() {
5116 String sourceDir = getCodePath();
5117 if (cleanUp() && mInstaller != null) {
5118 int retCode = mInstaller.rmdex(sourceDir);
5119 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005120 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005121 + " at location "
5122 + sourceDir + ", retcode=" + retCode);
5123 // we don't consider this to be a failure of the core package deletion
5124 }
5125 }
Kenny Root85387d72010-08-26 10:13:11 -07005126 if (libraryPath != null) {
5127 removeNativeBinariesLI(new File(libraryPath));
5128 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005129 }
5130
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005131 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005132 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005133 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005134 final int filePermissions =
5135 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5136 |FileUtils.S_IROTH;
5137 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5138 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005139 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005140 getCodePath()
5141 + ". The return code was: " + retCode);
5142 // TODO Define new internal error
5143 return false;
5144 }
5145 return true;
5146 }
5147 return true;
5148 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005149
5150 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005151 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005152 cleanUpResourcesLI();
5153 return true;
5154 }
Kenny Root85387d72010-08-26 10:13:11 -07005155
5156 private boolean isFwdLocked() {
5157 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5158 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005159 }
5160
5161 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005162 static final String RES_FILE_NAME = "pkg.apk";
5163
Kenny Root85387d72010-08-26 10:13:11 -07005164 String cid;
5165 String packagePath;
5166 String libraryPath;
5167
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005168 SdInstallArgs(InstallParams params) {
5169 super(params.packageURI, params.observer,
5170 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005171 }
5172
Kenny Root85387d72010-08-26 10:13:11 -07005173 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005174 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005175 // Extract cid from fullCodePath
5176 int eidx = fullCodePath.lastIndexOf("/");
5177 String subStr1 = fullCodePath.substring(0, eidx);
5178 int sidx = subStr1.lastIndexOf("/");
5179 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005180 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005181 }
5182
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005183 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005184 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5185 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005186 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005187 }
5188
5189 SdInstallArgs(Uri packageURI, String cid) {
5190 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005191 this.cid = cid;
5192 }
5193
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005194 void createCopyFile() {
5195 cid = getTempContainerId();
5196 }
5197
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005198 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5199 return imcs.checkFreeStorage(true, packageURI);
5200 }
5201
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005202 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005203 if (temp) {
5204 createCopyFile();
5205 }
Kenny Root85387d72010-08-26 10:13:11 -07005206 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005207 packageURI, cid,
5208 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005209 if (newCachePath != null) {
5210 setCachePath(newCachePath);
5211 return PackageManager.INSTALL_SUCCEEDED;
5212 } else {
5213 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5214 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005215 }
5216
5217 @Override
5218 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005219 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005220 }
5221
5222 @Override
5223 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005224 return packagePath;
5225 }
5226
5227 @Override
5228 String getNativeLibraryPath() {
5229 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005230 }
5231
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005232 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005233 if (status != PackageManager.INSTALL_SUCCEEDED) {
5234 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005235 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005236 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005237 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005238 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005239 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5240 Process.SYSTEM_UID);
5241 if (newCachePath != null) {
5242 setCachePath(newCachePath);
5243 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005244 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5245 }
5246 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005247 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005248 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005249 }
5250
5251 boolean doRename(int status, final String pkgName,
5252 String oldCodePath) {
5253 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005254 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005255 if (PackageHelper.isContainerMounted(cid)) {
5256 // Unmount the container
5257 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005258 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005259 return false;
5260 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005261 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005262 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005263 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5264 " which might be stale. Will try to clean up.");
5265 // Clean up the stale container and proceed to recreate.
5266 if (!PackageHelper.destroySdDir(newCacheId)) {
5267 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5268 return false;
5269 }
5270 // Successfully cleaned up stale container. Try to rename again.
5271 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5272 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5273 + " inspite of cleaning it up.");
5274 return false;
5275 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005276 }
5277 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005278 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005279 newCachePath = PackageHelper.mountSdDir(newCacheId,
5280 getEncryptKey(), Process.SYSTEM_UID);
5281 } else {
5282 newCachePath = PackageHelper.getSdDir(newCacheId);
5283 }
5284 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005285 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005286 return false;
5287 }
5288 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005289 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005290 " at new path: " + newCachePath);
5291 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005292 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005293 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005294 }
5295
Kenny Root85387d72010-08-26 10:13:11 -07005296 private void setCachePath(String newCachePath) {
5297 File cachePath = new File(newCachePath);
5298 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5299 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5300 }
5301
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005302 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005303 if (status != PackageManager.INSTALL_SUCCEEDED) {
5304 cleanUp();
5305 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005306 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005307 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005308 PackageHelper.mountSdDir(cid,
5309 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005310 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005311 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005312 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005313 }
5314
5315 private void cleanUp() {
5316 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005317 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005318 }
5319
5320 void cleanUpResourcesLI() {
5321 String sourceFile = getCodePath();
5322 // Remove dex file
5323 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005324 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005325 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005326 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005327 + " at location "
5328 + sourceFile.toString() + ", retcode=" + retCode);
5329 // we don't consider this to be a failure of the core package deletion
5330 }
5331 }
5332 cleanUp();
5333 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005334
5335 boolean matchContainer(String app) {
5336 if (cid.startsWith(app)) {
5337 return true;
5338 }
5339 return false;
5340 }
5341
5342 String getPackageName() {
5343 int idx = cid.lastIndexOf("-");
5344 if (idx == -1) {
5345 return cid;
5346 }
5347 return cid.substring(0, idx);
5348 }
5349
5350 boolean doPostDeleteLI(boolean delete) {
5351 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005352 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005353 if (mounted) {
5354 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005355 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005356 }
5357 if (ret && delete) {
5358 cleanUpResourcesLI();
5359 }
5360 return ret;
5361 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005362 };
5363
5364 // Utility method used to create code paths based on package name and available index.
5365 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5366 String idxStr = "";
5367 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005368 // Fall back to default value of idx=1 if prefix is not
5369 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005370 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005371 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005372 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005373 if (subStr.endsWith(suffix)) {
5374 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005375 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005376 // If oldCodePath already contains prefix find out the
5377 // ending index to either increment or decrement.
5378 int sidx = subStr.lastIndexOf(prefix);
5379 if (sidx != -1) {
5380 subStr = subStr.substring(sidx + prefix.length());
5381 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005382 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5383 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005384 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005385 try {
5386 idx = Integer.parseInt(subStr);
5387 if (idx <= 1) {
5388 idx++;
5389 } else {
5390 idx--;
5391 }
5392 } catch(NumberFormatException e) {
5393 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005394 }
5395 }
5396 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005397 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005398 return prefix + idxStr;
5399 }
5400
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005401 // Utility method used to ignore ADD/REMOVE events
5402 // by directory observer.
5403 private static boolean ignoreCodePath(String fullPathStr) {
5404 String apkName = getApkName(fullPathStr);
5405 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5406 if (idx != -1 && ((idx+1) < apkName.length())) {
5407 // Make sure the package ends with a numeral
5408 String version = apkName.substring(idx+1);
5409 try {
5410 Integer.parseInt(version);
5411 return true;
5412 } catch (NumberFormatException e) {}
5413 }
5414 return false;
5415 }
5416
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005417 // Utility method that returns the relative package path with respect
5418 // to the installation directory. Like say for /data/data/com.test-1.apk
5419 // string com.test-1 is returned.
5420 static String getApkName(String codePath) {
5421 if (codePath == null) {
5422 return null;
5423 }
5424 int sidx = codePath.lastIndexOf("/");
5425 int eidx = codePath.lastIndexOf(".");
5426 if (eidx == -1) {
5427 eidx = codePath.length();
5428 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005429 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005430 return null;
5431 }
5432 return codePath.substring(sidx+1, eidx);
5433 }
5434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435 class PackageInstalledInfo {
5436 String name;
5437 int uid;
5438 PackageParser.Package pkg;
5439 int returnCode;
5440 PackageRemovedInfo removedInfo;
5441 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443 /*
5444 * Install a non-existing package.
5445 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005446 private void installNewPackageLI(PackageParser.Package pkg,
5447 int parseFlags,
5448 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005449 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005450 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005451 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005452
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005453 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 res.name = pkgName;
5455 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005456 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5457 // A package with the same name is already installed, though
5458 // it has been renamed to an older name. The package we
5459 // are trying to install should be installed as an update to
5460 // the existing one, but that has not been requested, so bail.
5461 Slog.w(TAG, "Attempt to re-install " + pkgName
5462 + " without first uninstalling package running as "
5463 + mSettings.mRenamedPackages.get(pkgName));
5464 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5465 return;
5466 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005467 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005469 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005470 + " without first uninstalling.");
5471 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5472 return;
5473 }
5474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005475 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005476 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005477 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005478 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005479 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5480 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5481 }
5482 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005483 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005484 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 res);
5486 // delete the partially installed application. the data directory will have to be
5487 // restored if it was already existing
5488 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5489 // remove package from internal structures. Note that we want deletePackageX to
5490 // delete the package data and cache directories that it created in
5491 // scanPackageLocked, unless those directories existed before we even tried to
5492 // install.
5493 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005494 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005495 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5496 res.removedInfo);
5497 }
5498 }
5499 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005500
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005501 private void replacePackageLI(PackageParser.Package pkg,
5502 int parseFlags,
5503 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005504 String installerPackageName, PackageInstalledInfo res) {
5505
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005506 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005507 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005508 // First find the old package info and check signatures
5509 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005510 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005511 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005512 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005513 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5514 return;
5515 }
5516 }
Kenny Root85387d72010-08-26 10:13:11 -07005517 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005518 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005519 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005520 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005521 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005522 }
5523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005524
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005525 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005526 PackageParser.Package pkg,
5527 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005528 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005529 PackageParser.Package newPackage = null;
5530 String pkgName = deletedPackage.packageName;
5531 boolean deletedPkg = true;
5532 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005533
Jacek Surazski65e13172009-04-28 15:26:38 +02005534 String oldInstallerPackageName = null;
5535 synchronized (mPackages) {
5536 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005539 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005540 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005541 res.removedInfo)) {
5542 // If the existing package was'nt successfully deleted
5543 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5544 deletedPkg = false;
5545 } else {
5546 // Successfully deleted the old package. Now proceed with re-installation
5547 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005548 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005550 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005551 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5552 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005553 }
5554 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005555 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005556 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005557 res);
5558 updatedSettings = true;
5559 }
5560 }
5561
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005562 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005563 // remove package from internal structures. Note that we want deletePackageX to
5564 // delete the package data and cache directories that it created in
5565 // scanPackageLocked, unless those directories existed before we even tried to
5566 // install.
5567 if(updatedSettings) {
5568 deletePackageLI(
5569 pkgName, true,
5570 PackageManager.DONT_DELETE_DATA,
5571 res.removedInfo);
5572 }
5573 // Since we failed to install the new package we need to restore the old
5574 // package that we deleted.
5575 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005576 File restoreFile = new File(deletedPackage.mPath);
5577 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005578 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005579 return;
5580 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005581 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005582 boolean oldOnSd = isExternal(deletedPackage);
5583 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5584 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5585 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5586 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5587 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5588 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5589 return;
5590 }
5591 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005592 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005593 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005594 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005595 mSettings.writeLP();
5596 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005597 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598 }
5599 }
5600 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005602 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005603 PackageParser.Package pkg,
5604 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005605 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005606 PackageParser.Package newPackage = null;
5607 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005608 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005609 PackageParser.PARSE_IS_SYSTEM;
5610 String packageName = deletedPackage.packageName;
5611 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5612 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005613 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005614 return;
5615 }
5616 PackageParser.Package oldPkg;
5617 PackageSetting oldPkgSetting;
5618 synchronized (mPackages) {
5619 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005620 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005621 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5622 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005623 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005624 return;
5625 }
5626 }
5627 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5628 res.removedInfo.removedPackage = packageName;
5629 // Remove existing system package
5630 removePackageLI(oldPkg, true);
5631 synchronized (mPackages) {
5632 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5633 }
5634
5635 // Successfully disabled the old package. Now proceed with re-installation
5636 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5637 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005638 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005639 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005640 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005641 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5642 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5643 }
5644 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005645 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005646 updatedSettings = true;
5647 }
5648
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005649 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005650 // Re installation failed. Restore old information
5651 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005652 if (newPackage != null) {
5653 removePackageLI(newPackage, true);
5654 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005655 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005656 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005658 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005659 // Restore the old system information in Settings
5660 synchronized(mPackages) {
5661 if(updatedSettings) {
5662 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005663 mSettings.setInstallerPackageName(packageName,
5664 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005665 }
5666 mSettings.writeLP();
5667 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005668 } else {
5669 // If this is an update to an existing update, setup
5670 // to remove the existing update.
5671 synchronized (mPackages) {
5672 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5673 if (ps != null && ps.codePathString != null &&
5674 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5675 int installFlags = 0;
5676 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005677 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005678 }
5679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005680 }
5681 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005682
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005683 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005684 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005685 int retCode;
5686 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5687 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5688 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005689 if (mNoDexOpt) {
5690 /*
5691 * If we're in an engineering build, programs are lazily run
5692 * through dexopt. If the .dex file doesn't exist yet, it
5693 * will be created when the program is run next.
5694 */
5695 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5696 } else {
5697 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5698 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5699 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005700 }
5701 }
5702 return PackageManager.INSTALL_SUCCEEDED;
5703 }
5704
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005705 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005706 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005707 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005708 synchronized (mPackages) {
5709 //write settings. the installStatus will be incomplete at this stage.
5710 //note that the new package setting would have already been
5711 //added to mPackages. It hasn't been persisted yet.
5712 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5713 mSettings.writeLP();
5714 }
5715
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005716 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005717 != PackageManager.INSTALL_SUCCEEDED) {
5718 // Discontinue if moving dex files failed.
5719 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005720 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005721 if((res.returnCode = setPermissionsLI(newPackage))
5722 != PackageManager.INSTALL_SUCCEEDED) {
5723 if (mInstaller != null) {
5724 mInstaller.rmdex(newPackage.mScanPath);
5725 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005726 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005727 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005728 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005730 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005731 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005732 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005733 res.name = pkgName;
5734 res.uid = newPackage.applicationInfo.uid;
5735 res.pkg = newPackage;
5736 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005737 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005738 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5739 //to update install status
5740 mSettings.writeLP();
5741 }
5742 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005743
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005744 private void installPackageLI(InstallArgs args,
5745 boolean newInstall, PackageInstalledInfo res) {
5746 int pFlags = args.flags;
5747 String installerPackageName = args.installerPackageName;
5748 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005749 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005750 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005751 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005752 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005753 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005754 // Result object to be returned
5755 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5756
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005757 // Retrieve PackageSettings and parse package
5758 int parseFlags = PackageParser.PARSE_CHATTY |
5759 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5760 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5761 parseFlags |= mDefParseFlags;
5762 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5763 pp.setSeparateProcesses(mSeparateProcesses);
5764 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5765 null, mMetrics, parseFlags);
5766 if (pkg == null) {
5767 res.returnCode = pp.getParseError();
5768 return;
5769 }
5770 String pkgName = res.name = pkg.packageName;
5771 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5772 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5773 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5774 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005775 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005776 }
5777 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5778 res.returnCode = pp.getParseError();
5779 return;
5780 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005781 // Get rid of all references to package scan path via parser.
5782 pp = null;
5783 String oldCodePath = null;
5784 boolean systemApp = false;
5785 synchronized (mPackages) {
5786 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005787 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5788 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005789 if (pkg.mOriginalPackages != null
5790 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005791 && mPackages.containsKey(oldName)) {
5792 // This package is derived from an original package,
5793 // and this device has been updating from that original
5794 // name. We must continue using the original name, so
5795 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005796 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005797 pkgName = pkg.packageName;
5798 replace = true;
5799 } else if (mPackages.containsKey(pkgName)) {
5800 // This package, under its official name, already exists
5801 // on the device; we should replace it.
5802 replace = true;
5803 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005804 }
5805 PackageSetting ps = mSettings.mPackages.get(pkgName);
5806 if (ps != null) {
5807 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5808 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5809 systemApp = (ps.pkg.applicationInfo.flags &
5810 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005811 }
5812 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005814
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005815 if (systemApp && onSd) {
5816 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005817 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005818 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5819 return;
5820 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005821
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005822 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5823 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5824 return;
5825 }
5826 // Set application objects path explicitly after the rename
5827 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005828 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005829 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005830 replacePackageLI(pkg, parseFlags, scanMode,
5831 installerPackageName, res);
5832 } else {
5833 installNewPackageLI(pkg, parseFlags, scanMode,
5834 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005835 }
5836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005837
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005838 private int setPermissionsLI(PackageParser.Package newPackage) {
5839 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005840 int retCode = 0;
5841 // TODO Gross hack but fix later. Ideally move this to be a post installation
5842 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005843 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005844 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 try {
5846 extractPublicFiles(newPackage, destResourceFile);
5847 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005848 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" +
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005849 " forward-locked app.");
5850 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5851 } finally {
5852 //TODO clean up the extracted public files
5853 }
5854 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005855 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005856 newPackage.applicationInfo.uid);
5857 } else {
5858 final int filePermissions =
5859 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005860 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005861 newPackage.applicationInfo.uid);
5862 }
5863 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005864 // The permissions on the resource file was set when it was copied for
5865 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005866 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005868 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005869 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005870 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005872 // TODO Define new internal error
5873 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005874 }
5875 return PackageManager.INSTALL_SUCCEEDED;
5876 }
5877
Kenny Root85387d72010-08-26 10:13:11 -07005878 private static boolean isForwardLocked(PackageParser.Package pkg) {
5879 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005880 }
5881
Kenny Root85387d72010-08-26 10:13:11 -07005882 private static boolean isExternal(PackageParser.Package pkg) {
5883 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5884 }
5885
5886 private static boolean isSystemApp(PackageParser.Package pkg) {
5887 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5888 }
5889
5890 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5891 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005892 }
5893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005894 private void extractPublicFiles(PackageParser.Package newPackage,
5895 File publicZipFile) throws IOException {
5896 final ZipOutputStream publicZipOutStream =
5897 new ZipOutputStream(new FileOutputStream(publicZipFile));
5898 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5899
5900 // Copy manifest, resources.arsc and res directory to public zip
5901
5902 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5903 while (privateZipEntries.hasMoreElements()) {
5904 final ZipEntry zipEntry = privateZipEntries.nextElement();
5905 final String zipEntryName = zipEntry.getName();
5906 if ("AndroidManifest.xml".equals(zipEntryName)
5907 || "resources.arsc".equals(zipEntryName)
5908 || zipEntryName.startsWith("res/")) {
5909 try {
5910 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5911 } catch (IOException e) {
5912 try {
5913 publicZipOutStream.close();
5914 throw e;
5915 } finally {
5916 publicZipFile.delete();
5917 }
5918 }
5919 }
5920 }
5921
5922 publicZipOutStream.close();
5923 FileUtils.setPermissions(
5924 publicZipFile.getAbsolutePath(),
5925 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5926 -1, -1);
5927 }
5928
5929 private static void copyZipEntry(ZipEntry zipEntry,
5930 ZipFile inZipFile,
5931 ZipOutputStream outZipStream) throws IOException {
5932 byte[] buffer = new byte[4096];
5933 int num;
5934
5935 ZipEntry newEntry;
5936 if (zipEntry.getMethod() == ZipEntry.STORED) {
5937 // Preserve the STORED method of the input entry.
5938 newEntry = new ZipEntry(zipEntry);
5939 } else {
5940 // Create a new entry so that the compressed len is recomputed.
5941 newEntry = new ZipEntry(zipEntry.getName());
5942 }
5943 outZipStream.putNextEntry(newEntry);
5944
5945 InputStream data = inZipFile.getInputStream(zipEntry);
5946 while ((num = data.read(buffer)) > 0) {
5947 outZipStream.write(buffer, 0, num);
5948 }
5949 outZipStream.flush();
5950 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005951
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005952 private void deleteTempPackageFiles() {
5953 FilenameFilter filter = new FilenameFilter() {
5954 public boolean accept(File dir, String name) {
5955 return name.startsWith("vmdl") && name.endsWith(".tmp");
5956 }
5957 };
5958 String tmpFilesList[] = mAppInstallDir.list(filter);
5959 if(tmpFilesList == null) {
5960 return;
5961 }
5962 for(int i = 0; i < tmpFilesList.length; i++) {
5963 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5964 tmpFile.delete();
5965 }
5966 }
5967
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005968 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005969 File tmpPackageFile;
5970 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005971 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005972 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005973 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005974 return null;
5975 }
5976 try {
5977 FileUtils.setPermissions(
5978 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5979 -1, -1);
5980 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005981 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005982 return null;
5983 }
5984 return tmpPackageFile;
5985 }
5986
5987 public void deletePackage(final String packageName,
5988 final IPackageDeleteObserver observer,
5989 final int flags) {
5990 mContext.enforceCallingOrSelfPermission(
5991 android.Manifest.permission.DELETE_PACKAGES, null);
5992 // Queue up an async operation since the package deletion may take a little while.
5993 mHandler.post(new Runnable() {
5994 public void run() {
5995 mHandler.removeCallbacks(this);
5996 final boolean succeded = deletePackageX(packageName, true, true, flags);
5997 if (observer != null) {
5998 try {
5999 observer.packageDeleted(succeded);
6000 } catch (RemoteException e) {
6001 Log.i(TAG, "Observer no longer exists.");
6002 } //end catch
6003 } //end if
6004 } //end run
6005 });
6006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006008 /**
6009 * This method is an internal method that could be get invoked either
6010 * to delete an installed package or to clean up a failed installation.
6011 * After deleting an installed package, a broadcast is sent to notify any
6012 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006013 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 * installation wouldn't have sent the initial broadcast either
6015 * The key steps in deleting a package are
6016 * deleting the package information in internal structures like mPackages,
6017 * deleting the packages base directories through installd
6018 * updating mSettings to reflect current status
6019 * persisting settings for later use
6020 * sending a broadcast if necessary
6021 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006022 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6023 boolean deleteCodeAndResources, int flags) {
6024 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006025 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006026
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006027 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6028 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6029 try {
6030 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006031 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006032 return false;
6033 }
6034 } catch (RemoteException e) {
6035 }
6036
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006037 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006038 res = deletePackageLI(packageName, deleteCodeAndResources,
6039 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006040 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006041
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006042 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006043 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006044 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006045
6046 // If the removed package was a system update, the old system packaged
6047 // was re-enabled; we need to broadcast this information
6048 if (systemUpdate) {
6049 Bundle extras = new Bundle(1);
6050 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6051 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6052
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006053 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6054 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006055 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006056 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006057 // Force a gc here.
6058 Runtime.getRuntime().gc();
6059 // Delete the resources here after sending the broadcast to let
6060 // other processes clean up before deleting resources.
6061 if (info.args != null) {
6062 synchronized (mInstallLock) {
6063 info.args.doPostDeleteLI(deleteCodeAndResources);
6064 }
6065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 return res;
6067 }
6068
6069 static class PackageRemovedInfo {
6070 String removedPackage;
6071 int uid = -1;
6072 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006073 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006074 // Clean up resources deleted packages.
6075 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006076
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006077 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006078 Bundle extras = new Bundle(1);
6079 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6080 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6081 if (replacing) {
6082 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6083 }
6084 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006085 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006086 }
6087 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006088 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006089 }
6090 }
6091 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006093 /*
6094 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6095 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006096 * make sure this flag is set for partially installed apps. If not its meaningless to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006097 * delete a partially installed application.
6098 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006099 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006100 int flags) {
6101 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006102 if (outInfo != null) {
6103 outInfo.removedPackage = packageName;
6104 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006105 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006106 // Retrieve object to delete permissions for shared user later on
6107 PackageSetting deletedPs;
6108 synchronized (mPackages) {
6109 deletedPs = mSettings.mPackages.get(packageName);
6110 }
6111 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006112 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006113 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006114 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006115 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006116 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006117 + packageName + ", retcode=" + retCode);
6118 // we don't consider this to be a failure of the core package deletion
6119 }
6120 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006121 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006122 PackageParser.Package pkg = mPackages.get(packageName);
6123 File dataDir = new File(pkg.applicationInfo.dataDir);
6124 dataDir.delete();
6125 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006126 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006127 }
6128 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006129 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006130 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6131 if (outInfo != null) {
6132 outInfo.removedUid = mSettings.removePackageLP(packageName);
6133 }
6134 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006135 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006136 if (deletedPs.sharedUser != null) {
6137 // remove permissions associated with package
6138 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6139 }
6140 }
6141 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006142 // remove from preferred activities.
6143 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6144 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6145 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6146 removed.add(pa);
6147 }
6148 }
6149 for (PreferredActivity pa : removed) {
6150 mSettings.mPreferredActivities.removeFilter(pa);
6151 }
6152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006153 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006154 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 }
6156 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006158 /*
6159 * Tries to delete system package.
6160 */
6161 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006162 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006163 ApplicationInfo applicationInfo = p.applicationInfo;
6164 //applicable for non-partially installed applications only
6165 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006166 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006167 return false;
6168 }
6169 PackageSetting ps = null;
6170 // Confirm if the system package has been updated
6171 // An updated system app can be deleted. This will also have to restore
6172 // the system pkg from system partition
6173 synchronized (mPackages) {
6174 ps = mSettings.getDisabledSystemPkg(p.packageName);
6175 }
6176 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006177 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006178 return false;
6179 } else {
6180 Log.i(TAG, "Deleting system pkg from data partition");
6181 }
6182 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006183 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006184 final boolean deleteCodeAndResources;
6185 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006186 // Delete code and resources for downgrades
6187 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006188 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006189 } else {
6190 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006191 deleteCodeAndResources = false;
6192 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006193 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006194 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6195 if (!ret) {
6196 return false;
6197 }
6198 synchronized (mPackages) {
6199 // Reinstate the old system package
6200 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07006201 // Remove any native libraries. XXX needed?
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07006202 removeNativeBinariesLI(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006203 }
6204 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006205 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006206 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006207 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006208
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006209 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006210 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006211 return false;
6212 }
6213 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006214 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006215 mSettings.writeLP();
6216 }
6217 return true;
6218 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006219
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006220 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6221 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6222 ApplicationInfo applicationInfo = p.applicationInfo;
6223 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006224 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006225 return false;
6226 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006227 if (outInfo != null) {
6228 outInfo.uid = applicationInfo.uid;
6229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006230
6231 // Delete package data from internal structures and also remove data if flag is set
6232 removePackageDataLI(p, outInfo, flags);
6233
6234 // Delete application code and resources
6235 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006236 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006237 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6238 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6239 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6240 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 }
6242 return true;
6243 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006245 /*
6246 * This method handles package deletion in general
6247 */
6248 private boolean deletePackageLI(String packageName,
6249 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6250 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006251 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006252 return false;
6253 }
6254 PackageParser.Package p;
6255 boolean dataOnly = false;
6256 synchronized (mPackages) {
6257 p = mPackages.get(packageName);
6258 if (p == null) {
6259 //this retrieves partially installed apps
6260 dataOnly = true;
6261 PackageSetting ps = mSettings.mPackages.get(packageName);
6262 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006263 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006264 return false;
6265 }
6266 p = ps.pkg;
6267 }
6268 }
6269 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006270 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006271 return false;
6272 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 if (dataOnly) {
6275 // Delete application data first
6276 removePackageDataLI(p, outInfo, flags);
6277 return true;
6278 }
6279 // At this point the package should have ApplicationInfo associated with it
6280 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006281 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006282 return false;
6283 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006284 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006285 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006286 Log.i(TAG, "Removing system package:"+p.packageName);
6287 // When an updated system application is deleted we delete the existing resources as well and
6288 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006289 ret = deleteSystemPackageLI(p, flags, outInfo);
6290 } else {
6291 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006292 // Kill application pre-emptively especially for apps on sd.
6293 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006294 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006295 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006296 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006297 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006298
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006299 public void clearApplicationUserData(final String packageName,
6300 final IPackageDataObserver observer) {
6301 mContext.enforceCallingOrSelfPermission(
6302 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6303 // Queue up an async operation since the package deletion may take a little while.
6304 mHandler.post(new Runnable() {
6305 public void run() {
6306 mHandler.removeCallbacks(this);
6307 final boolean succeeded;
6308 synchronized (mInstallLock) {
6309 succeeded = clearApplicationUserDataLI(packageName);
6310 }
6311 if (succeeded) {
6312 // invoke DeviceStorageMonitor's update method to clear any notifications
6313 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6314 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6315 if (dsm != null) {
6316 dsm.updateMemory();
6317 }
6318 }
6319 if(observer != null) {
6320 try {
6321 observer.onRemoveCompleted(packageName, succeeded);
6322 } catch (RemoteException e) {
6323 Log.i(TAG, "Observer no longer exists.");
6324 }
6325 } //end if observer
6326 } //end run
6327 });
6328 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006330 private boolean clearApplicationUserDataLI(String packageName) {
6331 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006332 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006333 return false;
6334 }
6335 PackageParser.Package p;
6336 boolean dataOnly = false;
6337 synchronized (mPackages) {
6338 p = mPackages.get(packageName);
6339 if(p == null) {
6340 dataOnly = true;
6341 PackageSetting ps = mSettings.mPackages.get(packageName);
6342 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006343 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006344 return false;
6345 }
6346 p = ps.pkg;
6347 }
6348 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006349 boolean useEncryptedFSDir = false;
6350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006351 if(!dataOnly) {
6352 //need to check this only for fully installed applications
6353 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006354 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006355 return false;
6356 }
6357 final ApplicationInfo applicationInfo = p.applicationInfo;
6358 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006359 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006360 return false;
6361 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006362 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006363 }
6364 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006365 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006366 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006367 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006368 + packageName);
6369 return false;
6370 }
6371 }
6372 return true;
6373 }
6374
6375 public void deleteApplicationCacheFiles(final String packageName,
6376 final IPackageDataObserver observer) {
6377 mContext.enforceCallingOrSelfPermission(
6378 android.Manifest.permission.DELETE_CACHE_FILES, null);
6379 // Queue up an async operation since the package deletion may take a little while.
6380 mHandler.post(new Runnable() {
6381 public void run() {
6382 mHandler.removeCallbacks(this);
6383 final boolean succeded;
6384 synchronized (mInstallLock) {
6385 succeded = deleteApplicationCacheFilesLI(packageName);
6386 }
6387 if(observer != null) {
6388 try {
6389 observer.onRemoveCompleted(packageName, succeded);
6390 } catch (RemoteException e) {
6391 Log.i(TAG, "Observer no longer exists.");
6392 }
6393 } //end if observer
6394 } //end run
6395 });
6396 }
6397
6398 private boolean deleteApplicationCacheFilesLI(String packageName) {
6399 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006400 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006401 return false;
6402 }
6403 PackageParser.Package p;
6404 synchronized (mPackages) {
6405 p = mPackages.get(packageName);
6406 }
6407 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006408 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006409 return false;
6410 }
6411 final ApplicationInfo applicationInfo = p.applicationInfo;
6412 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006413 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006414 return false;
6415 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006416 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006417 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006418 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006419 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006420 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006421 + packageName);
6422 return false;
6423 }
6424 }
6425 return true;
6426 }
6427
6428 public void getPackageSizeInfo(final String packageName,
6429 final IPackageStatsObserver observer) {
6430 mContext.enforceCallingOrSelfPermission(
6431 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6432 // Queue up an async operation since the package deletion may take a little while.
6433 mHandler.post(new Runnable() {
6434 public void run() {
6435 mHandler.removeCallbacks(this);
6436 PackageStats lStats = new PackageStats(packageName);
6437 final boolean succeded;
6438 synchronized (mInstallLock) {
6439 succeded = getPackageSizeInfoLI(packageName, lStats);
6440 }
6441 if(observer != null) {
6442 try {
6443 observer.onGetStatsCompleted(lStats, succeded);
6444 } catch (RemoteException e) {
6445 Log.i(TAG, "Observer no longer exists.");
6446 }
6447 } //end if observer
6448 } //end run
6449 });
6450 }
6451
6452 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6453 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006454 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006455 return false;
6456 }
6457 PackageParser.Package p;
6458 boolean dataOnly = false;
6459 synchronized (mPackages) {
6460 p = mPackages.get(packageName);
6461 if(p == null) {
6462 dataOnly = true;
6463 PackageSetting ps = mSettings.mPackages.get(packageName);
6464 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006465 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006466 return false;
6467 }
6468 p = ps.pkg;
6469 }
6470 }
6471 String publicSrcDir = null;
6472 if(!dataOnly) {
6473 final ApplicationInfo applicationInfo = p.applicationInfo;
6474 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006475 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006476 return false;
6477 }
6478 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6479 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006480 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 if (mInstaller != null) {
6482 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006483 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006484 if (res < 0) {
6485 return false;
6486 } else {
6487 return true;
6488 }
6489 }
6490 return true;
6491 }
6492
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006494 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006495 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006496 }
6497
6498 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006499 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006500 }
6501
6502 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006503 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006504 }
6505
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006506 int getUidTargetSdkVersionLockedLP(int uid) {
6507 Object obj = mSettings.getUserIdLP(uid);
6508 if (obj instanceof SharedUserSetting) {
6509 SharedUserSetting sus = (SharedUserSetting)obj;
6510 final int N = sus.packages.size();
6511 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6512 Iterator<PackageSetting> it = sus.packages.iterator();
6513 int i=0;
6514 while (it.hasNext()) {
6515 PackageSetting ps = it.next();
6516 if (ps.pkg != null) {
6517 int v = ps.pkg.applicationInfo.targetSdkVersion;
6518 if (v < vers) vers = v;
6519 }
6520 }
6521 return vers;
6522 } else if (obj instanceof PackageSetting) {
6523 PackageSetting ps = (PackageSetting)obj;
6524 if (ps.pkg != null) {
6525 return ps.pkg.applicationInfo.targetSdkVersion;
6526 }
6527 }
6528 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6529 }
6530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006531 public void addPreferredActivity(IntentFilter filter, int match,
6532 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006533 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006534 if (mContext.checkCallingOrSelfPermission(
6535 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6536 != PackageManager.PERMISSION_GRANTED) {
6537 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6538 < Build.VERSION_CODES.FROYO) {
6539 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6540 + Binder.getCallingUid());
6541 return;
6542 }
6543 mContext.enforceCallingOrSelfPermission(
6544 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6545 }
6546
6547 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006548 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6549 mSettings.mPreferredActivities.addFilter(
6550 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006551 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006552 }
6553 }
6554
Satish Sampath8dbe6122009-06-02 23:35:54 +01006555 public void replacePreferredActivity(IntentFilter filter, int match,
6556 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006557 if (filter.countActions() != 1) {
6558 throw new IllegalArgumentException(
6559 "replacePreferredActivity expects filter to have only 1 action.");
6560 }
6561 if (filter.countCategories() != 1) {
6562 throw new IllegalArgumentException(
6563 "replacePreferredActivity expects filter to have only 1 category.");
6564 }
6565 if (filter.countDataAuthorities() != 0
6566 || filter.countDataPaths() != 0
6567 || filter.countDataSchemes() != 0
6568 || filter.countDataTypes() != 0) {
6569 throw new IllegalArgumentException(
6570 "replacePreferredActivity expects filter to have no data authorities, " +
6571 "paths, schemes or types.");
6572 }
6573 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006574 if (mContext.checkCallingOrSelfPermission(
6575 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6576 != PackageManager.PERMISSION_GRANTED) {
6577 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6578 < Build.VERSION_CODES.FROYO) {
6579 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6580 + Binder.getCallingUid());
6581 return;
6582 }
6583 mContext.enforceCallingOrSelfPermission(
6584 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6585 }
6586
Satish Sampath8dbe6122009-06-02 23:35:54 +01006587 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6588 String action = filter.getAction(0);
6589 String category = filter.getCategory(0);
6590 while (it.hasNext()) {
6591 PreferredActivity pa = it.next();
6592 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6593 it.remove();
6594 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6595 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6596 }
6597 }
6598 addPreferredActivity(filter, match, set, activity);
6599 }
6600 }
6601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006602 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006603 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006604 int uid = Binder.getCallingUid();
6605 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006606 if (pkg == null || pkg.applicationInfo.uid != uid) {
6607 if (mContext.checkCallingOrSelfPermission(
6608 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6609 != PackageManager.PERMISSION_GRANTED) {
6610 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6611 < Build.VERSION_CODES.FROYO) {
6612 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6613 + Binder.getCallingUid());
6614 return;
6615 }
6616 mContext.enforceCallingOrSelfPermission(
6617 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6618 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006619 }
6620
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006621 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006622 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006623 }
6624 }
6625 }
6626
6627 boolean clearPackagePreferredActivitiesLP(String packageName) {
6628 boolean changed = false;
6629 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6630 while (it.hasNext()) {
6631 PreferredActivity pa = it.next();
6632 if (pa.mActivity.getPackageName().equals(packageName)) {
6633 it.remove();
6634 changed = true;
6635 }
6636 }
6637 return changed;
6638 }
6639
6640 public int getPreferredActivities(List<IntentFilter> outFilters,
6641 List<ComponentName> outActivities, String packageName) {
6642
6643 int num = 0;
6644 synchronized (mPackages) {
6645 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6646 while (it.hasNext()) {
6647 PreferredActivity pa = it.next();
6648 if (packageName == null
6649 || pa.mActivity.getPackageName().equals(packageName)) {
6650 if (outFilters != null) {
6651 outFilters.add(new IntentFilter(pa));
6652 }
6653 if (outActivities != null) {
6654 outActivities.add(pa.mActivity);
6655 }
6656 }
6657 }
6658 }
6659
6660 return num;
6661 }
6662
6663 public void setApplicationEnabledSetting(String appPackageName,
6664 int newState, int flags) {
6665 setEnabledSetting(appPackageName, null, newState, flags);
6666 }
6667
6668 public void setComponentEnabledSetting(ComponentName componentName,
6669 int newState, int flags) {
6670 setEnabledSetting(componentName.getPackageName(),
6671 componentName.getClassName(), newState, flags);
6672 }
6673
6674 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006675 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006676 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6677 || newState == COMPONENT_ENABLED_STATE_ENABLED
6678 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6679 throw new IllegalArgumentException("Invalid new component state: "
6680 + newState);
6681 }
6682 PackageSetting pkgSetting;
6683 final int uid = Binder.getCallingUid();
6684 final int permission = mContext.checkCallingPermission(
6685 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6686 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006687 boolean sendNow = false;
6688 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006689 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006690 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006691 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006693 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006695 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006696 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006697 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006698 }
6699 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006700 "Unknown component: " + packageName
6701 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006702 }
6703 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6704 throw new SecurityException(
6705 "Permission Denial: attempt to change component state from pid="
6706 + Binder.getCallingPid()
6707 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6708 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006709 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006710 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006711 if (pkgSetting.enabled == newState) {
6712 // Nothing to do
6713 return;
6714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006716 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006717 } else {
6718 // We're dealing with a component level state change
6719 switch (newState) {
6720 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006721 if (!pkgSetting.enableComponentLP(className)) {
6722 return;
6723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006724 break;
6725 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006726 if (!pkgSetting.disableComponentLP(className)) {
6727 return;
6728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006729 break;
6730 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006731 if (!pkgSetting.restoreComponentLP(className)) {
6732 return;
6733 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006734 break;
6735 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006736 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006737 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006738 }
6739 }
6740 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006741 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006742 components = mPendingBroadcasts.get(packageName);
6743 boolean newPackage = components == null;
6744 if (newPackage) {
6745 components = new ArrayList<String>();
6746 }
6747 if (!components.contains(componentName)) {
6748 components.add(componentName);
6749 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006750 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6751 sendNow = true;
6752 // Purge entry from pending broadcast list if another one exists already
6753 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006754 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006755 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006756 if (newPackage) {
6757 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006758 }
6759 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6760 // Schedule a message
6761 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6762 }
6763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006764 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006766 long callingId = Binder.clearCallingIdentity();
6767 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006768 if (sendNow) {
6769 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006770 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006772 } finally {
6773 Binder.restoreCallingIdentity(callingId);
6774 }
6775 }
6776
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006777 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006778 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6779 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6780 + " components=" + componentNames);
6781 Bundle extras = new Bundle(4);
6782 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6783 String nameList[] = new String[componentNames.size()];
6784 componentNames.toArray(nameList);
6785 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006786 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6787 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006788 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006789 }
6790
Jacek Surazski65e13172009-04-28 15:26:38 +02006791 public String getInstallerPackageName(String packageName) {
6792 synchronized (mPackages) {
6793 PackageSetting pkg = mSettings.mPackages.get(packageName);
6794 if (pkg == null) {
6795 throw new IllegalArgumentException("Unknown package: " + packageName);
6796 }
6797 return pkg.installerPackageName;
6798 }
6799 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006801 public int getApplicationEnabledSetting(String appPackageName) {
6802 synchronized (mPackages) {
6803 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6804 if (pkg == null) {
6805 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6806 }
6807 return pkg.enabled;
6808 }
6809 }
6810
6811 public int getComponentEnabledSetting(ComponentName componentName) {
6812 synchronized (mPackages) {
6813 final String packageNameStr = componentName.getPackageName();
6814 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6815 if (pkg == null) {
6816 throw new IllegalArgumentException("Unknown component: " + componentName);
6817 }
6818 final String classNameStr = componentName.getClassName();
6819 return pkg.currentEnabledStateLP(classNameStr);
6820 }
6821 }
6822
6823 public void enterSafeMode() {
6824 if (!mSystemReady) {
6825 mSafeMode = true;
6826 }
6827 }
6828
6829 public void systemReady() {
6830 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006831
6832 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006833 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006834 mContext.getContentResolver(),
6835 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006836 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006837 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006838 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 }
6841
6842 public boolean isSafeMode() {
6843 return mSafeMode;
6844 }
6845
6846 public boolean hasSystemUidErrors() {
6847 return mHasSystemUidErrors;
6848 }
6849
6850 static String arrayToString(int[] array) {
6851 StringBuffer buf = new StringBuffer(128);
6852 buf.append('[');
6853 if (array != null) {
6854 for (int i=0; i<array.length; i++) {
6855 if (i > 0) buf.append(", ");
6856 buf.append(array[i]);
6857 }
6858 }
6859 buf.append(']');
6860 return buf.toString();
6861 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006863 @Override
6864 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6865 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6866 != PackageManager.PERMISSION_GRANTED) {
6867 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6868 + Binder.getCallingPid()
6869 + ", uid=" + Binder.getCallingUid()
6870 + " without permission "
6871 + android.Manifest.permission.DUMP);
6872 return;
6873 }
6874
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006875 String packageName = null;
6876
6877 int opti = 0;
6878 while (opti < args.length) {
6879 String opt = args[opti];
6880 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6881 break;
6882 }
6883 opti++;
6884 if ("-a".equals(opt)) {
6885 // Right now we only know how to print all.
6886 } else if ("-h".equals(opt)) {
6887 pw.println("Package manager dump options:");
6888 pw.println(" [-h] [cmd] ...");
6889 pw.println(" cmd may be one of:");
6890 pw.println(" [package.name]: info about given package");
6891 return;
6892 } else {
6893 pw.println("Unknown argument: " + opt + "; use -h for help");
6894 }
6895 }
6896
6897 // Is the caller requesting to dump a particular piece of data?
6898 if (opti < args.length) {
6899 String cmd = args[opti];
6900 opti++;
6901 // Is this a package name?
6902 if ("android".equals(cmd) || cmd.contains(".")) {
6903 packageName = cmd;
6904 }
6905 }
6906
6907 boolean printedTitle = false;
6908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006909 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006910 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6911 printedTitle = true;
6912 }
6913 if (mReceivers.dump(pw, printedTitle
6914 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6915 " ", packageName)) {
6916 printedTitle = true;
6917 }
6918 if (mServices.dump(pw, printedTitle
6919 ? "\nService Resolver Table:" : "Service Resolver Table:",
6920 " ", packageName)) {
6921 printedTitle = true;
6922 }
6923 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6924 ? "\nPreferred Activities:" : "Preferred Activities:",
6925 " ", packageName)) {
6926 printedTitle = true;
6927 }
6928 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006929 {
6930 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006931 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6932 continue;
6933 }
6934 if (!printedSomething) {
6935 if (printedTitle) pw.println(" ");
6936 pw.println("Permissions:");
6937 printedSomething = true;
6938 printedTitle = true;
6939 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006940 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6941 pw.print(Integer.toHexString(System.identityHashCode(p)));
6942 pw.println("):");
6943 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6944 pw.print(" uid="); pw.print(p.uid);
6945 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006946 pw.print(" type="); pw.print(p.type);
6947 pw.print(" prot="); pw.println(p.protectionLevel);
6948 if (p.packageSetting != null) {
6949 pw.print(" packageSetting="); pw.println(p.packageSetting);
6950 }
6951 if (p.perm != null) {
6952 pw.print(" perm="); pw.println(p.perm);
6953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006954 }
6955 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006956 printedSomething = false;
6957 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006958 {
6959 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006960 if (packageName != null && !packageName.equals(ps.realName)
6961 && !packageName.equals(ps.name)) {
6962 continue;
6963 }
6964 if (!printedSomething) {
6965 if (printedTitle) pw.println(" ");
6966 pw.println("Packages:");
6967 printedSomething = true;
6968 printedTitle = true;
6969 }
6970 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006971 pw.print(" Package [");
6972 pw.print(ps.realName != null ? ps.realName : ps.name);
6973 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006974 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6975 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006976 if (ps.realName != null) {
6977 pw.print(" compat name="); pw.println(ps.name);
6978 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006979 pw.print(" userId="); pw.print(ps.userId);
6980 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6981 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6982 pw.print(" pkg="); pw.println(ps.pkg);
6983 pw.print(" codePath="); pw.println(ps.codePathString);
6984 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07006985 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07006986 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006987 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006988 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006989 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07006990 if (ps.pkg.mOperationPending) {
6991 pw.println(" mOperationPending=true");
6992 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006993 pw.print(" supportsScreens=[");
6994 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006995 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07006996 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
6997 if (!first) pw.print(", ");
6998 first = false;
6999 pw.print("small");
7000 }
7001 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007002 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007003 if (!first) pw.print(", ");
7004 first = false;
7005 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007006 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007007 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007008 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007009 if (!first) pw.print(", ");
7010 first = false;
7011 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007012 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007013 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007014 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007015 if (!first) pw.print(", ");
7016 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07007017 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07007018 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007019 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007020 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007021 if (!first) pw.print(", ");
7022 first = false;
7023 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007024 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007025 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007026 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7027 if (!first) pw.print(", ");
7028 first = false;
7029 pw.print("anyDensity");
7030 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007031 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007032 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007033 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7034 pw.print(" signatures="); pw.println(ps.signatures);
7035 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007036 pw.print(" haveGids="); pw.println(ps.haveGids);
7037 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007038 pw.print(" installStatus="); pw.print(ps.installStatus);
7039 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007040 if (ps.disabledComponents.size() > 0) {
7041 pw.println(" disabledComponents:");
7042 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007043 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007044 }
7045 }
7046 if (ps.enabledComponents.size() > 0) {
7047 pw.println(" enabledComponents:");
7048 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007049 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007050 }
7051 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007052 if (ps.grantedPermissions.size() > 0) {
7053 pw.println(" grantedPermissions:");
7054 for (String s : ps.grantedPermissions) {
7055 pw.print(" "); pw.println(s);
7056 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007058 }
7059 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007060 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007061 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007062 for (HashMap.Entry<String, String> e
7063 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007064 if (packageName != null && !packageName.equals(e.getKey())
7065 && !packageName.equals(e.getValue())) {
7066 continue;
7067 }
7068 if (!printedSomething) {
7069 if (printedTitle) pw.println(" ");
7070 pw.println("Renamed packages:");
7071 printedSomething = true;
7072 printedTitle = true;
7073 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007074 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7075 pw.println(e.getValue());
7076 }
7077 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007078 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007079 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007080 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007081 if (packageName != null && !packageName.equals(ps.realName)
7082 && !packageName.equals(ps.name)) {
7083 continue;
7084 }
7085 if (!printedSomething) {
7086 if (printedTitle) pw.println(" ");
7087 pw.println("Hidden system packages:");
7088 printedSomething = true;
7089 printedTitle = true;
7090 }
7091 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007092 pw.print(ps.realName != null ? ps.realName : ps.name);
7093 pw.print("] (");
7094 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7095 pw.println("):");
7096 if (ps.realName != null) {
7097 pw.print(" compat name="); pw.println(ps.name);
7098 }
7099 pw.print(" userId="); pw.println(ps.userId);
7100 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7101 pw.print(" codePath="); pw.println(ps.codePathString);
7102 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7103 }
7104 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007105 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007106 {
7107 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007108 if (packageName != null && su != packageSharedUser) {
7109 continue;
7110 }
7111 if (!printedSomething) {
7112 if (printedTitle) pw.println(" ");
7113 pw.println("Shared users:");
7114 printedSomething = true;
7115 printedTitle = true;
7116 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007117 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7118 pw.print(Integer.toHexString(System.identityHashCode(su)));
7119 pw.println("):");
7120 pw.print(" userId="); pw.print(su.userId);
7121 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007122 pw.println(" grantedPermissions:");
7123 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007124 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007126 }
7127 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007128
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007129 if (packageName == null) {
7130 if (printedTitle) pw.println(" ");
7131 printedTitle = true;
7132 pw.println("Settings parse messages:");
7133 pw.println(mSettings.mReadMessages.toString());
7134
7135 pw.println(" ");
7136 pw.println("Package warning messages:");
7137 File fname = getSettingsProblemFile();
7138 FileInputStream in;
7139 try {
7140 in = new FileInputStream(fname);
7141 int avail = in.available();
7142 byte[] data = new byte[avail];
7143 in.read(data);
7144 pw.println(new String(data));
7145 } catch (FileNotFoundException e) {
7146 } catch (IOException e) {
7147 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007149 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007150
7151 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007152 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007153 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007154 if (packageName != null && !packageName.equals(p.info.packageName)) {
7155 continue;
7156 }
7157 if (!printedSomething) {
7158 if (printedTitle) pw.println(" ");
7159 pw.println("Registered ContentProviders:");
7160 printedSomething = true;
7161 printedTitle = true;
7162 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007163 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007164 pw.println(p.toString());
7165 }
7166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007167 }
7168
7169 static final class BasePermission {
7170 final static int TYPE_NORMAL = 0;
7171 final static int TYPE_BUILTIN = 1;
7172 final static int TYPE_DYNAMIC = 2;
7173
7174 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007175 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007176 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007177 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007178 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007179 PackageParser.Permission perm;
7180 PermissionInfo pendingInfo;
7181 int uid;
7182 int[] gids;
7183
7184 BasePermission(String _name, String _sourcePackage, int _type) {
7185 name = _name;
7186 sourcePackage = _sourcePackage;
7187 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007188 // Default to most conservative protection level.
7189 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7190 }
7191
7192 public String toString() {
7193 return "BasePermission{"
7194 + Integer.toHexString(System.identityHashCode(this))
7195 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007196 }
7197 }
7198
7199 static class PackageSignatures {
7200 private Signature[] mSignatures;
7201
7202 PackageSignatures(Signature[] sigs) {
7203 assignSignatures(sigs);
7204 }
7205
7206 PackageSignatures() {
7207 }
7208
7209 void writeXml(XmlSerializer serializer, String tagName,
7210 ArrayList<Signature> pastSignatures) throws IOException {
7211 if (mSignatures == null) {
7212 return;
7213 }
7214 serializer.startTag(null, tagName);
7215 serializer.attribute(null, "count",
7216 Integer.toString(mSignatures.length));
7217 for (int i=0; i<mSignatures.length; i++) {
7218 serializer.startTag(null, "cert");
7219 final Signature sig = mSignatures[i];
7220 final int sigHash = sig.hashCode();
7221 final int numPast = pastSignatures.size();
7222 int j;
7223 for (j=0; j<numPast; j++) {
7224 Signature pastSig = pastSignatures.get(j);
7225 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7226 serializer.attribute(null, "index", Integer.toString(j));
7227 break;
7228 }
7229 }
7230 if (j >= numPast) {
7231 pastSignatures.add(sig);
7232 serializer.attribute(null, "index", Integer.toString(numPast));
7233 serializer.attribute(null, "key", sig.toCharsString());
7234 }
7235 serializer.endTag(null, "cert");
7236 }
7237 serializer.endTag(null, tagName);
7238 }
7239
7240 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7241 throws IOException, XmlPullParserException {
7242 String countStr = parser.getAttributeValue(null, "count");
7243 if (countStr == null) {
7244 reportSettingsProblem(Log.WARN,
7245 "Error in package manager settings: <signatures> has"
7246 + " no count at " + parser.getPositionDescription());
7247 XmlUtils.skipCurrentTag(parser);
7248 }
7249 final int count = Integer.parseInt(countStr);
7250 mSignatures = new Signature[count];
7251 int pos = 0;
7252
7253 int outerDepth = parser.getDepth();
7254 int type;
7255 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7256 && (type != XmlPullParser.END_TAG
7257 || parser.getDepth() > outerDepth)) {
7258 if (type == XmlPullParser.END_TAG
7259 || type == XmlPullParser.TEXT) {
7260 continue;
7261 }
7262
7263 String tagName = parser.getName();
7264 if (tagName.equals("cert")) {
7265 if (pos < count) {
7266 String index = parser.getAttributeValue(null, "index");
7267 if (index != null) {
7268 try {
7269 int idx = Integer.parseInt(index);
7270 String key = parser.getAttributeValue(null, "key");
7271 if (key == null) {
7272 if (idx >= 0 && idx < pastSignatures.size()) {
7273 Signature sig = pastSignatures.get(idx);
7274 if (sig != null) {
7275 mSignatures[pos] = pastSignatures.get(idx);
7276 pos++;
7277 } else {
7278 reportSettingsProblem(Log.WARN,
7279 "Error in package manager settings: <cert> "
7280 + "index " + index + " is not defined at "
7281 + parser.getPositionDescription());
7282 }
7283 } else {
7284 reportSettingsProblem(Log.WARN,
7285 "Error in package manager settings: <cert> "
7286 + "index " + index + " is out of bounds at "
7287 + parser.getPositionDescription());
7288 }
7289 } else {
7290 while (pastSignatures.size() <= idx) {
7291 pastSignatures.add(null);
7292 }
7293 Signature sig = new Signature(key);
7294 pastSignatures.set(idx, sig);
7295 mSignatures[pos] = sig;
7296 pos++;
7297 }
7298 } catch (NumberFormatException e) {
7299 reportSettingsProblem(Log.WARN,
7300 "Error in package manager settings: <cert> "
7301 + "index " + index + " is not a number at "
7302 + parser.getPositionDescription());
7303 }
7304 } else {
7305 reportSettingsProblem(Log.WARN,
7306 "Error in package manager settings: <cert> has"
7307 + " no index at " + parser.getPositionDescription());
7308 }
7309 } else {
7310 reportSettingsProblem(Log.WARN,
7311 "Error in package manager settings: too "
7312 + "many <cert> tags, expected " + count
7313 + " at " + parser.getPositionDescription());
7314 }
7315 } else {
7316 reportSettingsProblem(Log.WARN,
7317 "Unknown element under <cert>: "
7318 + parser.getName());
7319 }
7320 XmlUtils.skipCurrentTag(parser);
7321 }
7322
7323 if (pos < count) {
7324 // Should never happen -- there is an error in the written
7325 // settings -- but if it does we don't want to generate
7326 // a bad array.
7327 Signature[] newSigs = new Signature[pos];
7328 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7329 mSignatures = newSigs;
7330 }
7331 }
7332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007333 private void assignSignatures(Signature[] sigs) {
7334 if (sigs == null) {
7335 mSignatures = null;
7336 return;
7337 }
7338 mSignatures = new Signature[sigs.length];
7339 for (int i=0; i<sigs.length; i++) {
7340 mSignatures[i] = sigs[i];
7341 }
7342 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007344 @Override
7345 public String toString() {
7346 StringBuffer buf = new StringBuffer(128);
7347 buf.append("PackageSignatures{");
7348 buf.append(Integer.toHexString(System.identityHashCode(this)));
7349 buf.append(" [");
7350 if (mSignatures != null) {
7351 for (int i=0; i<mSignatures.length; i++) {
7352 if (i > 0) buf.append(", ");
7353 buf.append(Integer.toHexString(
7354 System.identityHashCode(mSignatures[i])));
7355 }
7356 }
7357 buf.append("]}");
7358 return buf.toString();
7359 }
7360 }
7361
7362 static class PreferredActivity extends IntentFilter {
7363 final int mMatch;
7364 final String[] mSetPackages;
7365 final String[] mSetClasses;
7366 final String[] mSetComponents;
7367 final ComponentName mActivity;
7368 final String mShortActivity;
7369 String mParseError;
7370
7371 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7372 ComponentName activity) {
7373 super(filter);
7374 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7375 mActivity = activity;
7376 mShortActivity = activity.flattenToShortString();
7377 mParseError = null;
7378 if (set != null) {
7379 final int N = set.length;
7380 String[] myPackages = new String[N];
7381 String[] myClasses = new String[N];
7382 String[] myComponents = new String[N];
7383 for (int i=0; i<N; i++) {
7384 ComponentName cn = set[i];
7385 if (cn == null) {
7386 mSetPackages = null;
7387 mSetClasses = null;
7388 mSetComponents = null;
7389 return;
7390 }
7391 myPackages[i] = cn.getPackageName().intern();
7392 myClasses[i] = cn.getClassName().intern();
7393 myComponents[i] = cn.flattenToShortString().intern();
7394 }
7395 mSetPackages = myPackages;
7396 mSetClasses = myClasses;
7397 mSetComponents = myComponents;
7398 } else {
7399 mSetPackages = null;
7400 mSetClasses = null;
7401 mSetComponents = null;
7402 }
7403 }
7404
7405 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7406 IOException {
7407 mShortActivity = parser.getAttributeValue(null, "name");
7408 mActivity = ComponentName.unflattenFromString(mShortActivity);
7409 if (mActivity == null) {
7410 mParseError = "Bad activity name " + mShortActivity;
7411 }
7412 String matchStr = parser.getAttributeValue(null, "match");
7413 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7414 String setCountStr = parser.getAttributeValue(null, "set");
7415 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7416
7417 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7418 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7419 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7420
7421 int setPos = 0;
7422
7423 int outerDepth = parser.getDepth();
7424 int type;
7425 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7426 && (type != XmlPullParser.END_TAG
7427 || parser.getDepth() > outerDepth)) {
7428 if (type == XmlPullParser.END_TAG
7429 || type == XmlPullParser.TEXT) {
7430 continue;
7431 }
7432
7433 String tagName = parser.getName();
7434 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7435 // + parser.getDepth() + " tag=" + tagName);
7436 if (tagName.equals("set")) {
7437 String name = parser.getAttributeValue(null, "name");
7438 if (name == null) {
7439 if (mParseError == null) {
7440 mParseError = "No name in set tag in preferred activity "
7441 + mShortActivity;
7442 }
7443 } else if (setPos >= setCount) {
7444 if (mParseError == null) {
7445 mParseError = "Too many set tags in preferred activity "
7446 + mShortActivity;
7447 }
7448 } else {
7449 ComponentName cn = ComponentName.unflattenFromString(name);
7450 if (cn == null) {
7451 if (mParseError == null) {
7452 mParseError = "Bad set name " + name + " in preferred activity "
7453 + mShortActivity;
7454 }
7455 } else {
7456 myPackages[setPos] = cn.getPackageName();
7457 myClasses[setPos] = cn.getClassName();
7458 myComponents[setPos] = name;
7459 setPos++;
7460 }
7461 }
7462 XmlUtils.skipCurrentTag(parser);
7463 } else if (tagName.equals("filter")) {
7464 //Log.i(TAG, "Starting to parse filter...");
7465 readFromXml(parser);
7466 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7467 // + parser.getDepth() + " tag=" + parser.getName());
7468 } else {
7469 reportSettingsProblem(Log.WARN,
7470 "Unknown element under <preferred-activities>: "
7471 + parser.getName());
7472 XmlUtils.skipCurrentTag(parser);
7473 }
7474 }
7475
7476 if (setPos != setCount) {
7477 if (mParseError == null) {
7478 mParseError = "Not enough set tags (expected " + setCount
7479 + " but found " + setPos + ") in " + mShortActivity;
7480 }
7481 }
7482
7483 mSetPackages = myPackages;
7484 mSetClasses = myClasses;
7485 mSetComponents = myComponents;
7486 }
7487
7488 public void writeToXml(XmlSerializer serializer) throws IOException {
7489 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7490 serializer.attribute(null, "name", mShortActivity);
7491 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7492 serializer.attribute(null, "set", Integer.toString(NS));
7493 for (int s=0; s<NS; s++) {
7494 serializer.startTag(null, "set");
7495 serializer.attribute(null, "name", mSetComponents[s]);
7496 serializer.endTag(null, "set");
7497 }
7498 serializer.startTag(null, "filter");
7499 super.writeToXml(serializer);
7500 serializer.endTag(null, "filter");
7501 }
7502
7503 boolean sameSet(List<ResolveInfo> query, int priority) {
7504 if (mSetPackages == null) return false;
7505 final int NQ = query.size();
7506 final int NS = mSetPackages.length;
7507 int numMatch = 0;
7508 for (int i=0; i<NQ; i++) {
7509 ResolveInfo ri = query.get(i);
7510 if (ri.priority != priority) continue;
7511 ActivityInfo ai = ri.activityInfo;
7512 boolean good = false;
7513 for (int j=0; j<NS; j++) {
7514 if (mSetPackages[j].equals(ai.packageName)
7515 && mSetClasses[j].equals(ai.name)) {
7516 numMatch++;
7517 good = true;
7518 break;
7519 }
7520 }
7521 if (!good) return false;
7522 }
7523 return numMatch == NS;
7524 }
7525 }
7526
7527 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007528 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007530 HashSet<String> grantedPermissions = new HashSet<String>();
7531 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007533 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007534 setFlags(pkgFlags);
7535 }
7536
7537 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007538 this.pkgFlags = pkgFlags & (
7539 ApplicationInfo.FLAG_SYSTEM |
7540 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007541 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007542 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007543 }
7544 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 /**
7547 * Settings base class for pending and resolved classes.
7548 */
7549 static class PackageSettingBase extends GrantedPermissions {
7550 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007551 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007552 File codePath;
7553 String codePathString;
7554 File resourcePath;
7555 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007556 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007557 String obbPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007558 private long timeStamp;
7559 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007560 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007561
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007562 boolean uidError;
7563
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007564 PackageSignatures signatures = new PackageSignatures();
7565
7566 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007567 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007569 /* Explicitly disabled components */
7570 HashSet<String> disabledComponents = new HashSet<String>(0);
7571 /* Explicitly enabled components */
7572 HashSet<String> enabledComponents = new HashSet<String>(0);
7573 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7574 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007575
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007576 PackageSettingBase origPackage;
7577
Jacek Surazski65e13172009-04-28 15:26:38 +02007578 /* package name of the app that installed this package */
7579 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007580
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007581 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007582 int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007583 super(pkgFlags);
7584 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007585 this.realName = realName;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007586 init(codePath, resourcePath, pVersionCode);
7587 }
7588
7589 void init(File codePath, File resourcePath, int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007590 this.codePath = codePath;
7591 this.codePathString = codePath.toString();
7592 this.resourcePath = resourcePath;
7593 this.resourcePathString = resourcePath.toString();
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007594 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007595 }
Kenny Root85387d72010-08-26 10:13:11 -07007596
Jacek Surazski65e13172009-04-28 15:26:38 +02007597 public void setInstallerPackageName(String packageName) {
7598 installerPackageName = packageName;
7599 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007600
Jacek Surazski65e13172009-04-28 15:26:38 +02007601 String getInstallerPackageName() {
7602 return installerPackageName;
7603 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007605 public void setInstallStatus(int newStatus) {
7606 installStatus = newStatus;
7607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007609 public int getInstallStatus() {
7610 return installStatus;
7611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007613 public void setTimeStamp(long newStamp) {
7614 if (newStamp != timeStamp) {
7615 timeStamp = newStamp;
7616 timeStampString = Long.toString(newStamp);
7617 }
7618 }
7619
7620 public void setTimeStamp(long newStamp, String newStampStr) {
7621 timeStamp = newStamp;
7622 timeStampString = newStampStr;
7623 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007625 public long getTimeStamp() {
7626 return timeStamp;
7627 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007629 public String getTimeStampStr() {
7630 return timeStampString;
7631 }
7632
7633 public void copyFrom(PackageSettingBase base) {
7634 grantedPermissions = base.grantedPermissions;
7635 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 timeStamp = base.timeStamp;
7638 timeStampString = base.timeStampString;
7639 signatures = base.signatures;
7640 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007641 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007642 disabledComponents = base.disabledComponents;
7643 enabledComponents = base.enabledComponents;
7644 enabled = base.enabled;
7645 installStatus = base.installStatus;
7646 }
7647
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007648 boolean enableComponentLP(String componentClassName) {
7649 boolean changed = disabledComponents.remove(componentClassName);
7650 changed |= enabledComponents.add(componentClassName);
7651 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007652 }
7653
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007654 boolean disableComponentLP(String componentClassName) {
7655 boolean changed = enabledComponents.remove(componentClassName);
7656 changed |= disabledComponents.add(componentClassName);
7657 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007658 }
7659
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007660 boolean restoreComponentLP(String componentClassName) {
7661 boolean changed = enabledComponents.remove(componentClassName);
7662 changed |= disabledComponents.remove(componentClassName);
7663 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007664 }
7665
7666 int currentEnabledStateLP(String componentName) {
7667 if (enabledComponents.contains(componentName)) {
7668 return COMPONENT_ENABLED_STATE_ENABLED;
7669 } else if (disabledComponents.contains(componentName)) {
7670 return COMPONENT_ENABLED_STATE_DISABLED;
7671 } else {
7672 return COMPONENT_ENABLED_STATE_DEFAULT;
7673 }
7674 }
7675 }
7676
7677 /**
7678 * Settings data for a particular package we know about.
7679 */
7680 static final class PackageSetting extends PackageSettingBase {
7681 int userId;
7682 PackageParser.Package pkg;
7683 SharedUserSetting sharedUser;
7684
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007685 PackageSetting(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007686 int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007687 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007688 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007690 @Override
7691 public String toString() {
7692 return "PackageSetting{"
7693 + Integer.toHexString(System.identityHashCode(this))
7694 + " " + name + "/" + userId + "}";
7695 }
7696 }
7697
7698 /**
7699 * Settings data for a particular shared user ID we know about.
7700 */
7701 static final class SharedUserSetting extends GrantedPermissions {
7702 final String name;
7703 int userId;
7704 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7705 final PackageSignatures signatures = new PackageSignatures();
7706
7707 SharedUserSetting(String _name, int _pkgFlags) {
7708 super(_pkgFlags);
7709 name = _name;
7710 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007712 @Override
7713 public String toString() {
7714 return "SharedUserSetting{"
7715 + Integer.toHexString(System.identityHashCode(this))
7716 + " " + name + "/" + userId + "}";
7717 }
7718 }
7719
7720 /**
7721 * Holds information about dynamic settings.
7722 */
7723 private static final class Settings {
7724 private final File mSettingsFilename;
7725 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007726 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007727 private final HashMap<String, PackageSetting> mPackages =
7728 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 // List of replaced system applications
7730 final HashMap<String, PackageSetting> mDisabledSysPackages =
7731 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007732
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007733 // These are the last platform API version we were using for
7734 // the apps installed on internal and external storage. It is
7735 // used to grant newer permissions one time during a system upgrade.
7736 int mInternalSdkPlatform;
7737 int mExternalSdkPlatform;
7738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007739 // The user's preferred activities associated with particular intent
7740 // filters.
7741 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7742 new IntentResolver<PreferredActivity, PreferredActivity>() {
7743 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007744 protected String packageForFilter(PreferredActivity filter) {
7745 return filter.mActivity.getPackageName();
7746 }
7747 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007748 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007749 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007750 out.print(prefix); out.print(
7751 Integer.toHexString(System.identityHashCode(filter)));
7752 out.print(' ');
7753 out.print(filter.mActivity.flattenToShortString());
7754 out.print(" match=0x");
7755 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007756 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007757 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007758 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007759 out.print(prefix); out.print(" ");
7760 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007761 }
7762 }
7763 }
7764 };
7765 private final HashMap<String, SharedUserSetting> mSharedUsers =
7766 new HashMap<String, SharedUserSetting>();
7767 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7768 private final SparseArray<Object> mOtherUserIds =
7769 new SparseArray<Object>();
7770
7771 // For reading/writing settings file.
7772 private final ArrayList<Signature> mPastSignatures =
7773 new ArrayList<Signature>();
7774
7775 // Mapping from permission names to info about them.
7776 final HashMap<String, BasePermission> mPermissions =
7777 new HashMap<String, BasePermission>();
7778
7779 // Mapping from permission tree names to info about them.
7780 final HashMap<String, BasePermission> mPermissionTrees =
7781 new HashMap<String, BasePermission>();
7782
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007783 // Packages that have been uninstalled and still need their external
7784 // storage data deleted.
7785 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7786
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007787 // Packages that have been renamed since they were first installed.
7788 // Keys are the new names of the packages, values are the original
7789 // names. The packages appear everwhere else under their original
7790 // names.
7791 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 private final StringBuilder mReadMessages = new StringBuilder();
7794
7795 private static final class PendingPackage extends PackageSettingBase {
7796 final int sharedId;
7797
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007798 PendingPackage(String name, String realName, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007799 int sharedId, int pVersionCode, int pkgFlags) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007800 super(name, realName, codePath, resourcePath, pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007801 this.sharedId = sharedId;
7802 }
7803 }
7804 private final ArrayList<PendingPackage> mPendingPackages
7805 = new ArrayList<PendingPackage>();
7806
7807 Settings() {
7808 File dataDir = Environment.getDataDirectory();
7809 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007810 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7811 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007812 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007813 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007814 FileUtils.setPermissions(systemDir.toString(),
7815 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7816 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7817 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007818 FileUtils.setPermissions(systemSecureDir.toString(),
7819 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7820 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7821 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007822 mSettingsFilename = new File(systemDir, "packages.xml");
7823 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007824 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007825 }
7826
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007827 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007828 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007829 int pkgFlags, boolean create, boolean add) {
7830 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007831 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007832 resourcePath, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007833 return p;
7834 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007835
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007836 PackageSetting peekPackageLP(String name) {
7837 return mPackages.get(name);
7838 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007839 PackageSetting p = mPackages.get(name);
7840 if (p != null && p.codePath.getPath().equals(codePath)) {
7841 return p;
7842 }
7843 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007844 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007845 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007847 void setInstallStatus(String pkgName, int status) {
7848 PackageSetting p = mPackages.get(pkgName);
7849 if(p != null) {
7850 if(p.getInstallStatus() != status) {
7851 p.setInstallStatus(status);
7852 }
7853 }
7854 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007855
Jacek Surazski65e13172009-04-28 15:26:38 +02007856 void setInstallerPackageName(String pkgName,
7857 String installerPkgName) {
7858 PackageSetting p = mPackages.get(pkgName);
7859 if(p != null) {
7860 p.setInstallerPackageName(installerPkgName);
7861 }
7862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007863
Jacek Surazski65e13172009-04-28 15:26:38 +02007864 String getInstallerPackageName(String pkgName) {
7865 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007866 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007867 }
7868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007869 int getInstallStatus(String pkgName) {
7870 PackageSetting p = mPackages.get(pkgName);
7871 if(p != null) {
7872 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007874 return -1;
7875 }
7876
7877 SharedUserSetting getSharedUserLP(String name,
7878 int pkgFlags, boolean create) {
7879 SharedUserSetting s = mSharedUsers.get(name);
7880 if (s == null) {
7881 if (!create) {
7882 return null;
7883 }
7884 s = new SharedUserSetting(name, pkgFlags);
7885 if (MULTIPLE_APPLICATION_UIDS) {
7886 s.userId = newUserIdLP(s);
7887 } else {
7888 s.userId = FIRST_APPLICATION_UID;
7889 }
7890 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7891 // < 0 means we couldn't assign a userid; fall out and return
7892 // s, which is currently null
7893 if (s.userId >= 0) {
7894 mSharedUsers.put(name, s);
7895 }
7896 }
7897
7898 return s;
7899 }
7900
7901 int disableSystemPackageLP(String name) {
7902 PackageSetting p = mPackages.get(name);
7903 if(p == null) {
7904 Log.w(TAG, "Package:"+name+" is not an installed package");
7905 return -1;
7906 }
7907 PackageSetting dp = mDisabledSysPackages.get(name);
7908 // always make sure the system package code and resource paths dont change
7909 if(dp == null) {
7910 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7911 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7912 }
7913 mDisabledSysPackages.put(name, p);
7914 }
7915 return removePackageLP(name);
7916 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007917
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007918 PackageSetting enableSystemPackageLP(String name) {
7919 PackageSetting p = mDisabledSysPackages.get(name);
7920 if(p == null) {
7921 Log.w(TAG, "Package:"+name+" is not disabled");
7922 return null;
7923 }
7924 // Reset flag in ApplicationInfo object
7925 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7926 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7927 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007928 PackageSetting ret = addPackageLP(name, p.realName, p.codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007929 p.resourcePath, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007930 mDisabledSysPackages.remove(name);
7931 return ret;
7932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007933
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007934 PackageSetting addPackageLP(String name, String realName, File codePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007935 File resourcePath, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007936 PackageSetting p = mPackages.get(name);
7937 if (p != null) {
7938 if (p.userId == uid) {
7939 return p;
7940 }
7941 reportSettingsProblem(Log.ERROR,
7942 "Adding duplicate package, keeping first: " + name);
7943 return null;
7944 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007945 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007946 p.userId = uid;
7947 if (addUserIdLP(uid, p, name)) {
7948 mPackages.put(name, p);
7949 return p;
7950 }
7951 return null;
7952 }
7953
7954 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7955 SharedUserSetting s = mSharedUsers.get(name);
7956 if (s != null) {
7957 if (s.userId == uid) {
7958 return s;
7959 }
7960 reportSettingsProblem(Log.ERROR,
7961 "Adding duplicate shared user, keeping first: " + name);
7962 return null;
7963 }
7964 s = new SharedUserSetting(name, pkgFlags);
7965 s.userId = uid;
7966 if (addUserIdLP(uid, s, name)) {
7967 mSharedUsers.put(name, s);
7968 return s;
7969 }
7970 return null;
7971 }
7972
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007973 // Transfer ownership of permissions from one package to another.
7974 private void transferPermissions(String origPkg, String newPkg) {
7975 // Transfer ownership of permissions to the new package.
7976 for (int i=0; i<2; i++) {
7977 HashMap<String, BasePermission> permissions =
7978 i == 0 ? mPermissionTrees : mPermissions;
7979 for (BasePermission bp : permissions.values()) {
7980 if (origPkg.equals(bp.sourcePackage)) {
7981 if (DEBUG_UPGRADE) Log.v(TAG,
7982 "Moving permission " + bp.name
7983 + " from pkg " + bp.sourcePackage
7984 + " to " + newPkg);
7985 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007986 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007987 bp.perm = null;
7988 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007989 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007990 }
7991 bp.uid = 0;
7992 bp.gids = null;
7993 }
7994 }
7995 }
7996 }
7997
7998 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007999 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008000 int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008001 PackageSetting p = mPackages.get(name);
8002 if (p != null) {
8003 if (!p.codePath.equals(codePath)) {
8004 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008005 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07008006 // This is an updated system app with versions in both system
8007 // and data partition. Just let the most recent version
8008 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008009 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008010 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07008011 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08008012 // Just a change in the code path is not an issue, but
8013 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008014 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008015 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008016 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008017 }
8018 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008019 reportSettingsProblem(Log.WARN,
8020 "Package " + name + " shared user changed from "
8021 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8022 + " to "
8023 + (sharedUser != null ? sharedUser.name : "<nothing>")
8024 + "; replacing with new");
8025 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008026 } else {
8027 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8028 // If what we are scanning is a system package, then
8029 // make it so, regardless of whether it was previously
8030 // installed only in the data partition.
8031 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008033 }
8034 }
8035 if (p == null) {
8036 // Create a new PackageSettings entry. this can end up here because
8037 // of code path mismatch or user id mismatch of an updated system partition
8038 if (!create) {
8039 return null;
8040 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008041 if (origPackage != null) {
8042 // We are consuming the data from an existing package.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008043 p = new PackageSetting(origPackage.name, name, codePath,
8044 resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008045 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8046 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008047 // Note that we will retain the new package's signature so
8048 // that we can keep its data.
8049 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008050 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008051 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008052 p.sharedUser = origPackage.sharedUser;
8053 p.userId = origPackage.userId;
8054 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008055 mRenamedPackages.put(name, origPackage.name);
8056 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008057 // Update new package state.
8058 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008059 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008060 p = new PackageSetting(name, realName, codePath, resourcePath, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008061 p.setTimeStamp(codePath.lastModified());
8062 p.sharedUser = sharedUser;
8063 if (sharedUser != null) {
8064 p.userId = sharedUser.userId;
8065 } else if (MULTIPLE_APPLICATION_UIDS) {
8066 // Clone the setting here for disabled system packages
8067 PackageSetting dis = mDisabledSysPackages.get(name);
8068 if (dis != null) {
8069 // For disabled packages a new setting is created
8070 // from the existing user id. This still has to be
8071 // added to list of user id's
8072 // Copy signatures from previous setting
8073 if (dis.signatures.mSignatures != null) {
8074 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8075 }
8076 p.userId = dis.userId;
8077 // Clone permissions
8078 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008079 // Clone component info
8080 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8081 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8082 // Add new setting to list of user ids
8083 addUserIdLP(p.userId, p, name);
8084 } else {
8085 // Assign new user id
8086 p.userId = newUserIdLP(p);
8087 }
8088 } else {
8089 p.userId = FIRST_APPLICATION_UID;
8090 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008091 }
8092 if (p.userId < 0) {
8093 reportSettingsProblem(Log.WARN,
8094 "Package " + name + " could not be assigned a valid uid");
8095 return null;
8096 }
8097 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008098 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008099 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008100 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008101 }
8102 }
8103 return p;
8104 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008105
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008106 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008107 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008108 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008109 final String codePath = pkg.applicationInfo.sourceDir;
8110 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008111 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008112 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008113 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008114 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008115 p.codePath = new File(codePath);
8116 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008117 }
8118 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008119 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008120 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008121 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008122 p.resourcePath = new File(resourcePath);
8123 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008124 }
Kenny Root85387d72010-08-26 10:13:11 -07008125 // Update the native library path if needed
8126 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8127 if (nativeLibraryPath != null
8128 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8129 p.nativeLibraryPathString = nativeLibraryPath;
8130 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008131 // Update version code if needed
8132 if (pkg.mVersionCode != p.versionCode) {
8133 p.versionCode = pkg.mVersionCode;
8134 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008135 // Update signatures if needed.
8136 if (p.signatures.mSignatures == null) {
8137 p.signatures.assignSignatures(pkg.mSignatures);
8138 }
8139 // If this app defines a shared user id initialize
8140 // the shared user signatures as well.
8141 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8142 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8143 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008144 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8145 }
8146
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008147 // Utility method that adds a PackageSetting to mPackages and
8148 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008149 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008150 SharedUserSetting sharedUser) {
8151 mPackages.put(name, p);
8152 if (sharedUser != null) {
8153 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8154 reportSettingsProblem(Log.ERROR,
8155 "Package " + p.name + " was user "
8156 + p.sharedUser + " but is now " + sharedUser
8157 + "; I am not changing its files so it will probably fail!");
8158 p.sharedUser.packages.remove(p);
8159 } else if (p.userId != sharedUser.userId) {
8160 reportSettingsProblem(Log.ERROR,
8161 "Package " + p.name + " was user id " + p.userId
8162 + " but is now user " + sharedUser
8163 + " with id " + sharedUser.userId
8164 + "; I am not changing its files so it will probably fail!");
8165 }
8166
8167 sharedUser.packages.add(p);
8168 p.sharedUser = sharedUser;
8169 p.userId = sharedUser.userId;
8170 }
8171 }
8172
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008173 /*
8174 * Update the shared user setting when a package using
8175 * specifying the shared user id is removed. The gids
8176 * associated with each permission of the deleted package
8177 * are removed from the shared user's gid list only if its
8178 * not in use by other permissions of packages in the
8179 * shared user setting.
8180 */
8181 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008182 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008183 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008184 return;
8185 }
8186 // No sharedUserId
8187 if (deletedPs.sharedUser == null) {
8188 return;
8189 }
8190 SharedUserSetting sus = deletedPs.sharedUser;
8191 // Update permissions
8192 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8193 boolean used = false;
8194 if (!sus.grantedPermissions.contains (eachPerm)) {
8195 continue;
8196 }
8197 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008198 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008199 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008200 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008201 used = true;
8202 break;
8203 }
8204 }
8205 if (!used) {
8206 // can safely delete this permission from list
8207 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008208 }
8209 }
8210 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008211 int newGids[] = globalGids;
8212 for (String eachPerm : sus.grantedPermissions) {
8213 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008214 if (bp != null) {
8215 newGids = appendInts(newGids, bp.gids);
8216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008217 }
8218 sus.gids = newGids;
8219 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008221 private int removePackageLP(String name) {
8222 PackageSetting p = mPackages.get(name);
8223 if (p != null) {
8224 mPackages.remove(name);
8225 if (p.sharedUser != null) {
8226 p.sharedUser.packages.remove(p);
8227 if (p.sharedUser.packages.size() == 0) {
8228 mSharedUsers.remove(p.sharedUser.name);
8229 removeUserIdLP(p.sharedUser.userId);
8230 return p.sharedUser.userId;
8231 }
8232 } else {
8233 removeUserIdLP(p.userId);
8234 return p.userId;
8235 }
8236 }
8237 return -1;
8238 }
8239
8240 private boolean addUserIdLP(int uid, Object obj, Object name) {
8241 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8242 return false;
8243 }
8244
8245 if (uid >= FIRST_APPLICATION_UID) {
8246 int N = mUserIds.size();
8247 final int index = uid - FIRST_APPLICATION_UID;
8248 while (index >= N) {
8249 mUserIds.add(null);
8250 N++;
8251 }
8252 if (mUserIds.get(index) != null) {
8253 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008254 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008255 + " name=" + name);
8256 return false;
8257 }
8258 mUserIds.set(index, obj);
8259 } else {
8260 if (mOtherUserIds.get(uid) != null) {
8261 reportSettingsProblem(Log.ERROR,
8262 "Adding duplicate shared id: " + uid
8263 + " name=" + name);
8264 return false;
8265 }
8266 mOtherUserIds.put(uid, obj);
8267 }
8268 return true;
8269 }
8270
8271 public Object getUserIdLP(int uid) {
8272 if (uid >= FIRST_APPLICATION_UID) {
8273 int N = mUserIds.size();
8274 final int index = uid - FIRST_APPLICATION_UID;
8275 return index < N ? mUserIds.get(index) : null;
8276 } else {
8277 return mOtherUserIds.get(uid);
8278 }
8279 }
8280
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008281 private Set<String> findPackagesWithFlag(int flag) {
8282 Set<String> ret = new HashSet<String>();
8283 for (PackageSetting ps : mPackages.values()) {
8284 // Has to match atleast all the flag bits set on flag
8285 if ((ps.pkgFlags & flag) == flag) {
8286 ret.add(ps.name);
8287 }
8288 }
8289 return ret;
8290 }
8291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008292 private void removeUserIdLP(int uid) {
8293 if (uid >= FIRST_APPLICATION_UID) {
8294 int N = mUserIds.size();
8295 final int index = uid - FIRST_APPLICATION_UID;
8296 if (index < N) mUserIds.set(index, null);
8297 } else {
8298 mOtherUserIds.remove(uid);
8299 }
8300 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008301
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008302 void writeLP() {
8303 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8304
8305 // Keep the old settings around until we know the new ones have
8306 // been successfully written.
8307 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008308 // Presence of backup settings file indicates that we failed
8309 // to persist settings earlier. So preserve the older
8310 // backup for future reference since the current settings
8311 // might have been corrupted.
8312 if (!mBackupSettingsFilename.exists()) {
8313 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008314 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008315 return;
8316 }
8317 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008318 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008319 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008321 }
8322
8323 mPastSignatures.clear();
8324
8325 try {
8326 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8327
8328 //XmlSerializer serializer = XmlUtils.serializerInstance();
8329 XmlSerializer serializer = new FastXmlSerializer();
8330 serializer.setOutput(str, "utf-8");
8331 serializer.startDocument(null, true);
8332 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8333
8334 serializer.startTag(null, "packages");
8335
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008336 serializer.startTag(null, "last-platform-version");
8337 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8338 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8339 serializer.endTag(null, "last-platform-version");
8340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008341 serializer.startTag(null, "permission-trees");
8342 for (BasePermission bp : mPermissionTrees.values()) {
8343 writePermission(serializer, bp);
8344 }
8345 serializer.endTag(null, "permission-trees");
8346
8347 serializer.startTag(null, "permissions");
8348 for (BasePermission bp : mPermissions.values()) {
8349 writePermission(serializer, bp);
8350 }
8351 serializer.endTag(null, "permissions");
8352
8353 for (PackageSetting pkg : mPackages.values()) {
8354 writePackage(serializer, pkg);
8355 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008357 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8358 writeDisabledSysPackage(serializer, pkg);
8359 }
8360
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008361 serializer.startTag(null, "preferred-activities");
8362 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8363 serializer.startTag(null, "item");
8364 pa.writeToXml(serializer);
8365 serializer.endTag(null, "item");
8366 }
8367 serializer.endTag(null, "preferred-activities");
8368
8369 for (SharedUserSetting usr : mSharedUsers.values()) {
8370 serializer.startTag(null, "shared-user");
8371 serializer.attribute(null, "name", usr.name);
8372 serializer.attribute(null, "userId",
8373 Integer.toString(usr.userId));
8374 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8375 serializer.startTag(null, "perms");
8376 for (String name : usr.grantedPermissions) {
8377 serializer.startTag(null, "item");
8378 serializer.attribute(null, "name", name);
8379 serializer.endTag(null, "item");
8380 }
8381 serializer.endTag(null, "perms");
8382 serializer.endTag(null, "shared-user");
8383 }
8384
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008385 if (mPackagesToBeCleaned.size() > 0) {
8386 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8387 serializer.startTag(null, "cleaning-package");
8388 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8389 serializer.endTag(null, "cleaning-package");
8390 }
8391 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008392
8393 if (mRenamedPackages.size() > 0) {
8394 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8395 serializer.startTag(null, "renamed-package");
8396 serializer.attribute(null, "new", e.getKey());
8397 serializer.attribute(null, "old", e.getValue());
8398 serializer.endTag(null, "renamed-package");
8399 }
8400 }
8401
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008402 serializer.endTag(null, "packages");
8403
8404 serializer.endDocument();
8405
8406 str.flush();
8407 str.close();
8408
8409 // New settings successfully written, old ones are no longer
8410 // needed.
8411 mBackupSettingsFilename.delete();
8412 FileUtils.setPermissions(mSettingsFilename.toString(),
8413 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8414 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8415 |FileUtils.S_IROTH,
8416 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008417
8418 // Write package list file now, use a JournaledFile.
8419 //
8420 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8421 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8422
8423 str = new FileOutputStream(journal.chooseForWrite());
8424 try {
8425 StringBuilder sb = new StringBuilder();
8426 for (PackageSetting pkg : mPackages.values()) {
8427 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008428 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008429 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8430
8431 // Avoid any application that has a space in its path
8432 // or that is handled by the system.
8433 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8434 continue;
8435
8436 // we store on each line the following information for now:
8437 //
8438 // pkgName - package name
8439 // userId - application-specific user id
8440 // debugFlag - 0 or 1 if the package is debuggable.
8441 // dataPath - path to package's data path
8442 //
8443 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8444 //
8445 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8446 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8447 // system/core/run-as/run-as.c
8448 //
8449 sb.setLength(0);
8450 sb.append(ai.packageName);
8451 sb.append(" ");
8452 sb.append((int)ai.uid);
8453 sb.append(isDebug ? " 1 " : " 0 ");
8454 sb.append(dataPath);
8455 sb.append("\n");
8456 str.write(sb.toString().getBytes());
8457 }
8458 str.flush();
8459 str.close();
8460 journal.commit();
8461 }
8462 catch (Exception e) {
8463 journal.rollback();
8464 }
8465
8466 FileUtils.setPermissions(mPackageListFilename.toString(),
8467 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8468 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8469 |FileUtils.S_IROTH,
8470 -1, -1);
8471
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008472 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008473
8474 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008475 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 -08008476 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008477 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 -08008478 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008479 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008480 if (mSettingsFilename.exists()) {
8481 if (!mSettingsFilename.delete()) {
8482 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8483 }
8484 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008485 //Debug.stopMethodTracing();
8486 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008487
8488 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008489 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008490 serializer.startTag(null, "updated-package");
8491 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008492 if (pkg.realName != null) {
8493 serializer.attribute(null, "realName", pkg.realName);
8494 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008495 serializer.attribute(null, "codePath", pkg.codePathString);
8496 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008497 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008498 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8499 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8500 }
Kenny Root85387d72010-08-26 10:13:11 -07008501 if (pkg.nativeLibraryPathString != null) {
8502 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008504 if (pkg.sharedUser == null) {
8505 serializer.attribute(null, "userId",
8506 Integer.toString(pkg.userId));
8507 } else {
8508 serializer.attribute(null, "sharedUserId",
8509 Integer.toString(pkg.userId));
8510 }
8511 serializer.startTag(null, "perms");
8512 if (pkg.sharedUser == null) {
8513 // If this is a shared user, the permissions will
8514 // be written there. We still need to write an
8515 // empty permissions list so permissionsFixed will
8516 // be set.
8517 for (final String name : pkg.grantedPermissions) {
8518 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008519 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008520 // We only need to write signature or system permissions but this wont
8521 // match the semantics of grantedPermissions. So write all permissions.
8522 serializer.startTag(null, "item");
8523 serializer.attribute(null, "name", name);
8524 serializer.endTag(null, "item");
8525 }
8526 }
8527 }
8528 serializer.endTag(null, "perms");
8529 serializer.endTag(null, "updated-package");
8530 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008531
8532 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008533 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008534 serializer.startTag(null, "package");
8535 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008536 if (pkg.realName != null) {
8537 serializer.attribute(null, "realName", pkg.realName);
8538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008539 serializer.attribute(null, "codePath", pkg.codePathString);
8540 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8541 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8542 }
Kenny Root85387d72010-08-26 10:13:11 -07008543 if (pkg.nativeLibraryPathString != null) {
8544 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8545 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008546 serializer.attribute(null, "flags",
8547 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008548 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008549 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008550 if (pkg.sharedUser == null) {
8551 serializer.attribute(null, "userId",
8552 Integer.toString(pkg.userId));
8553 } else {
8554 serializer.attribute(null, "sharedUserId",
8555 Integer.toString(pkg.userId));
8556 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008557 if (pkg.uidError) {
8558 serializer.attribute(null, "uidError", "true");
8559 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008560 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8561 serializer.attribute(null, "enabled",
8562 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8563 ? "true" : "false");
8564 }
8565 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8566 serializer.attribute(null, "installStatus", "false");
8567 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008568 if (pkg.installerPackageName != null) {
8569 serializer.attribute(null, "installer", pkg.installerPackageName);
8570 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008571 if (pkg.obbPathString != null) {
8572 serializer.attribute(null, "obbPath", pkg.obbPathString);
8573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008574 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8575 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8576 serializer.startTag(null, "perms");
8577 if (pkg.sharedUser == null) {
8578 // If this is a shared user, the permissions will
8579 // be written there. We still need to write an
8580 // empty permissions list so permissionsFixed will
8581 // be set.
8582 for (final String name : pkg.grantedPermissions) {
8583 serializer.startTag(null, "item");
8584 serializer.attribute(null, "name", name);
8585 serializer.endTag(null, "item");
8586 }
8587 }
8588 serializer.endTag(null, "perms");
8589 }
8590 if (pkg.disabledComponents.size() > 0) {
8591 serializer.startTag(null, "disabled-components");
8592 for (final String name : pkg.disabledComponents) {
8593 serializer.startTag(null, "item");
8594 serializer.attribute(null, "name", name);
8595 serializer.endTag(null, "item");
8596 }
8597 serializer.endTag(null, "disabled-components");
8598 }
8599 if (pkg.enabledComponents.size() > 0) {
8600 serializer.startTag(null, "enabled-components");
8601 for (final String name : pkg.enabledComponents) {
8602 serializer.startTag(null, "item");
8603 serializer.attribute(null, "name", name);
8604 serializer.endTag(null, "item");
8605 }
8606 serializer.endTag(null, "enabled-components");
8607 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008609 serializer.endTag(null, "package");
8610 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008612 void writePermission(XmlSerializer serializer, BasePermission bp)
8613 throws XmlPullParserException, java.io.IOException {
8614 if (bp.type != BasePermission.TYPE_BUILTIN
8615 && bp.sourcePackage != null) {
8616 serializer.startTag(null, "item");
8617 serializer.attribute(null, "name", bp.name);
8618 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008619 if (bp.protectionLevel !=
8620 PermissionInfo.PROTECTION_NORMAL) {
8621 serializer.attribute(null, "protection",
8622 Integer.toString(bp.protectionLevel));
8623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008624 if (DEBUG_SETTINGS) Log.v(TAG,
8625 "Writing perm: name=" + bp.name + " type=" + bp.type);
8626 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8627 PermissionInfo pi = bp.perm != null ? bp.perm.info
8628 : bp.pendingInfo;
8629 if (pi != null) {
8630 serializer.attribute(null, "type", "dynamic");
8631 if (pi.icon != 0) {
8632 serializer.attribute(null, "icon",
8633 Integer.toString(pi.icon));
8634 }
8635 if (pi.nonLocalizedLabel != null) {
8636 serializer.attribute(null, "label",
8637 pi.nonLocalizedLabel.toString());
8638 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008639 }
8640 }
8641 serializer.endTag(null, "item");
8642 }
8643 }
8644
8645 String getReadMessagesLP() {
8646 return mReadMessages.toString();
8647 }
8648
Oscar Montemayora8529f62009-11-18 10:14:20 -08008649 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008650 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8651 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008652 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008653 while(its.hasNext()) {
8654 String key = its.next();
8655 PackageSetting ps = mPackages.get(key);
8656 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008657 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008658 }
8659 }
8660 return ret;
8661 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008662
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008663 boolean readLP() {
8664 FileInputStream str = null;
8665 if (mBackupSettingsFilename.exists()) {
8666 try {
8667 str = new FileInputStream(mBackupSettingsFilename);
8668 mReadMessages.append("Reading from backup settings file\n");
8669 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008670 if (mSettingsFilename.exists()) {
8671 // If both the backup and settings file exist, we
8672 // ignore the settings since it might have been
8673 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008674 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008675 mSettingsFilename.delete();
8676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008677 } catch (java.io.IOException e) {
8678 // We'll try for the normal settings file.
8679 }
8680 }
8681
8682 mPastSignatures.clear();
8683
8684 try {
8685 if (str == null) {
8686 if (!mSettingsFilename.exists()) {
8687 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008688 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008689 return false;
8690 }
8691 str = new FileInputStream(mSettingsFilename);
8692 }
8693 XmlPullParser parser = Xml.newPullParser();
8694 parser.setInput(str, null);
8695
8696 int type;
8697 while ((type=parser.next()) != XmlPullParser.START_TAG
8698 && type != XmlPullParser.END_DOCUMENT) {
8699 ;
8700 }
8701
8702 if (type != XmlPullParser.START_TAG) {
8703 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008704 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008705 return false;
8706 }
8707
8708 int outerDepth = parser.getDepth();
8709 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8710 && (type != XmlPullParser.END_TAG
8711 || parser.getDepth() > outerDepth)) {
8712 if (type == XmlPullParser.END_TAG
8713 || type == XmlPullParser.TEXT) {
8714 continue;
8715 }
8716
8717 String tagName = parser.getName();
8718 if (tagName.equals("package")) {
8719 readPackageLP(parser);
8720 } else if (tagName.equals("permissions")) {
8721 readPermissionsLP(mPermissions, parser);
8722 } else if (tagName.equals("permission-trees")) {
8723 readPermissionsLP(mPermissionTrees, parser);
8724 } else if (tagName.equals("shared-user")) {
8725 readSharedUserLP(parser);
8726 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008727 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008728 } else if (tagName.equals("preferred-activities")) {
8729 readPreferredActivitiesLP(parser);
8730 } else if(tagName.equals("updated-package")) {
8731 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008732 } else if (tagName.equals("cleaning-package")) {
8733 String name = parser.getAttributeValue(null, "name");
8734 if (name != null) {
8735 mPackagesToBeCleaned.add(name);
8736 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008737 } else if (tagName.equals("renamed-package")) {
8738 String nname = parser.getAttributeValue(null, "new");
8739 String oname = parser.getAttributeValue(null, "old");
8740 if (nname != null && oname != null) {
8741 mRenamedPackages.put(nname, oname);
8742 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008743 } else if (tagName.equals("last-platform-version")) {
8744 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8745 try {
8746 String internal = parser.getAttributeValue(null, "internal");
8747 if (internal != null) {
8748 mInternalSdkPlatform = Integer.parseInt(internal);
8749 }
8750 String external = parser.getAttributeValue(null, "external");
8751 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008752 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008753 }
8754 } catch (NumberFormatException e) {
8755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008756 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008757 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008758 + parser.getName());
8759 XmlUtils.skipCurrentTag(parser);
8760 }
8761 }
8762
8763 str.close();
8764
8765 } catch(XmlPullParserException e) {
8766 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008767 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768
8769 } catch(java.io.IOException 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 }
8774
8775 int N = mPendingPackages.size();
8776 for (int i=0; i<N; i++) {
8777 final PendingPackage pp = mPendingPackages.get(i);
8778 Object idObj = getUserIdLP(pp.sharedId);
8779 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008780 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008781 (SharedUserSetting)idObj, pp.codePath, pp.resourcePath,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008782 pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008783 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008784 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008785 + pp.name);
8786 continue;
8787 }
8788 p.copyFrom(pp);
8789 } else if (idObj != null) {
8790 String msg = "Bad package setting: package " + pp.name
8791 + " has shared uid " + pp.sharedId
8792 + " that is not a shared uid\n";
8793 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008794 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008795 } else {
8796 String msg = "Bad package setting: package " + pp.name
8797 + " has shared uid " + pp.sharedId
8798 + " that is not defined\n";
8799 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008800 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008801 }
8802 }
8803 mPendingPackages.clear();
8804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008805 mReadMessages.append("Read completed successfully: "
8806 + mPackages.size() + " packages, "
8807 + mSharedUsers.size() + " shared uids\n");
8808
8809 return true;
8810 }
8811
8812 private int readInt(XmlPullParser parser, String ns, String name,
8813 int defValue) {
8814 String v = parser.getAttributeValue(ns, name);
8815 try {
8816 if (v == null) {
8817 return defValue;
8818 }
8819 return Integer.parseInt(v);
8820 } catch (NumberFormatException e) {
8821 reportSettingsProblem(Log.WARN,
8822 "Error in package manager settings: attribute " +
8823 name + " has bad integer value " + v + " at "
8824 + parser.getPositionDescription());
8825 }
8826 return defValue;
8827 }
8828
8829 private void readPermissionsLP(HashMap<String, BasePermission> out,
8830 XmlPullParser parser)
8831 throws IOException, XmlPullParserException {
8832 int outerDepth = parser.getDepth();
8833 int type;
8834 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8835 && (type != XmlPullParser.END_TAG
8836 || parser.getDepth() > outerDepth)) {
8837 if (type == XmlPullParser.END_TAG
8838 || type == XmlPullParser.TEXT) {
8839 continue;
8840 }
8841
8842 String tagName = parser.getName();
8843 if (tagName.equals("item")) {
8844 String name = parser.getAttributeValue(null, "name");
8845 String sourcePackage = parser.getAttributeValue(null, "package");
8846 String ptype = parser.getAttributeValue(null, "type");
8847 if (name != null && sourcePackage != null) {
8848 boolean dynamic = "dynamic".equals(ptype);
8849 BasePermission bp = new BasePermission(name, sourcePackage,
8850 dynamic
8851 ? BasePermission.TYPE_DYNAMIC
8852 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008853 bp.protectionLevel = readInt(parser, null, "protection",
8854 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008855 if (dynamic) {
8856 PermissionInfo pi = new PermissionInfo();
8857 pi.packageName = sourcePackage.intern();
8858 pi.name = name.intern();
8859 pi.icon = readInt(parser, null, "icon", 0);
8860 pi.nonLocalizedLabel = parser.getAttributeValue(
8861 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008862 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008863 bp.pendingInfo = pi;
8864 }
8865 out.put(bp.name, bp);
8866 } else {
8867 reportSettingsProblem(Log.WARN,
8868 "Error in package manager settings: permissions has"
8869 + " no name at " + parser.getPositionDescription());
8870 }
8871 } else {
8872 reportSettingsProblem(Log.WARN,
8873 "Unknown element reading permissions: "
8874 + parser.getName() + " at "
8875 + parser.getPositionDescription());
8876 }
8877 XmlUtils.skipCurrentTag(parser);
8878 }
8879 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008881 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008882 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008884 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008885 String codePathStr = parser.getAttributeValue(null, "codePath");
8886 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008887 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008888 resourcePathStr = codePathStr;
8889 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008890 String version = parser.getAttributeValue(null, "version");
8891 int versionCode = 0;
8892 if (version != null) {
8893 try {
8894 versionCode = Integer.parseInt(version);
8895 } catch (NumberFormatException e) {
8896 }
8897 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008899 int pkgFlags = 0;
8900 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008901 PackageSetting ps = new PackageSetting(name, realName,
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008902 new File(codePathStr),
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008903 new File(resourcePathStr), versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008904 String timeStampStr = parser.getAttributeValue(null, "ts");
8905 if (timeStampStr != null) {
8906 try {
8907 long timeStamp = Long.parseLong(timeStampStr);
8908 ps.setTimeStamp(timeStamp, timeStampStr);
8909 } catch (NumberFormatException e) {
8910 }
8911 }
8912 String idStr = parser.getAttributeValue(null, "userId");
8913 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8914 if(ps.userId <= 0) {
8915 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8916 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8917 }
8918 int outerDepth = parser.getDepth();
8919 int type;
8920 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8921 && (type != XmlPullParser.END_TAG
8922 || parser.getDepth() > outerDepth)) {
8923 if (type == XmlPullParser.END_TAG
8924 || type == XmlPullParser.TEXT) {
8925 continue;
8926 }
8927
8928 String tagName = parser.getName();
8929 if (tagName.equals("perms")) {
8930 readGrantedPermissionsLP(parser,
8931 ps.grantedPermissions);
8932 } else {
8933 reportSettingsProblem(Log.WARN,
8934 "Unknown element under <updated-package>: "
8935 + parser.getName());
8936 XmlUtils.skipCurrentTag(parser);
8937 }
8938 }
8939 mDisabledSysPackages.put(name, ps);
8940 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008941
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008942 private void readPackageLP(XmlPullParser parser)
8943 throws XmlPullParserException, IOException {
8944 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008945 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008946 String idStr = null;
8947 String sharedIdStr = null;
8948 String codePathStr = null;
8949 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07008950 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07008951 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008952 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008953 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008954 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008955 int pkgFlags = 0;
8956 String timeStampStr;
8957 long timeStamp = 0;
8958 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008959 String version = null;
8960 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008961 try {
8962 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008963 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008965 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008966 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8967 codePathStr = parser.getAttributeValue(null, "codePath");
8968 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07008969 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07008970 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008971 version = parser.getAttributeValue(null, "version");
8972 if (version != null) {
8973 try {
8974 versionCode = Integer.parseInt(version);
8975 } catch (NumberFormatException e) {
8976 }
8977 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008978 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008979
8980 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008981 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008982 try {
8983 pkgFlags = Integer.parseInt(systemStr);
8984 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008985 }
8986 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008987 // For backward compatibility
8988 systemStr = parser.getAttributeValue(null, "system");
8989 if (systemStr != null) {
8990 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8991 } else {
8992 // Old settings that don't specify system... just treat
8993 // them as system, good enough.
8994 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008996 }
8997 timeStampStr = parser.getAttributeValue(null, "ts");
8998 if (timeStampStr != null) {
8999 try {
9000 timeStamp = Long.parseLong(timeStampStr);
9001 } catch (NumberFormatException e) {
9002 }
9003 }
9004 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
9005 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
9006 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9007 if (resourcePathStr == null) {
9008 resourcePathStr = codePathStr;
9009 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009010 if (realName != null) {
9011 realName = realName.intern();
9012 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009013 if (name == null) {
9014 reportSettingsProblem(Log.WARN,
9015 "Error in package manager settings: <package> has no name at "
9016 + parser.getPositionDescription());
9017 } else if (codePathStr == null) {
9018 reportSettingsProblem(Log.WARN,
9019 "Error in package manager settings: <package> has no codePath at "
9020 + parser.getPositionDescription());
9021 } else if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009022 packageSetting = addPackageLP(name.intern(), realName,
9023 new File(codePathStr), new File(resourcePathStr),
9024 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9026 + ": userId=" + userId + " pkg=" + packageSetting);
9027 if (packageSetting == null) {
9028 reportSettingsProblem(Log.ERROR,
9029 "Failure adding uid " + userId
9030 + " while parsing settings at "
9031 + parser.getPositionDescription());
9032 } else {
9033 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9034 }
9035 } else if (sharedIdStr != null) {
9036 userId = sharedIdStr != null
9037 ? Integer.parseInt(sharedIdStr) : 0;
9038 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009039 packageSetting = new PendingPackage(name.intern(), realName,
9040 new File(codePathStr), new File(resourcePathStr),
9041 userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009042 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9043 mPendingPackages.add((PendingPackage) packageSetting);
9044 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9045 + ": sharedUserId=" + userId + " pkg="
9046 + packageSetting);
9047 } else {
9048 reportSettingsProblem(Log.WARN,
9049 "Error in package manager settings: package "
9050 + name + " has bad sharedId " + sharedIdStr
9051 + " at " + parser.getPositionDescription());
9052 }
9053 } else {
9054 reportSettingsProblem(Log.WARN,
9055 "Error in package manager settings: package "
9056 + name + " has bad userId " + idStr + " at "
9057 + parser.getPositionDescription());
9058 }
9059 } catch (NumberFormatException e) {
9060 reportSettingsProblem(Log.WARN,
9061 "Error in package manager settings: package "
9062 + name + " has bad userId " + idStr + " at "
9063 + parser.getPositionDescription());
9064 }
9065 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009066 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009067 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009068 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009069 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009070 final String enabledStr = parser.getAttributeValue(null, "enabled");
9071 if (enabledStr != null) {
9072 if (enabledStr.equalsIgnoreCase("true")) {
9073 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9074 } else if (enabledStr.equalsIgnoreCase("false")) {
9075 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9076 } else if (enabledStr.equalsIgnoreCase("default")) {
9077 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9078 } else {
9079 reportSettingsProblem(Log.WARN,
9080 "Error in package manager settings: package "
9081 + name + " has bad enabled value: " + idStr
9082 + " at " + parser.getPositionDescription());
9083 }
9084 } else {
9085 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9086 }
9087 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9088 if (installStatusStr != null) {
9089 if (installStatusStr.equalsIgnoreCase("false")) {
9090 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9091 } else {
9092 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9093 }
9094 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009096 int outerDepth = parser.getDepth();
9097 int type;
9098 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9099 && (type != XmlPullParser.END_TAG
9100 || parser.getDepth() > outerDepth)) {
9101 if (type == XmlPullParser.END_TAG
9102 || type == XmlPullParser.TEXT) {
9103 continue;
9104 }
9105
9106 String tagName = parser.getName();
9107 if (tagName.equals("disabled-components")) {
9108 readDisabledComponentsLP(packageSetting, parser);
9109 } else if (tagName.equals("enabled-components")) {
9110 readEnabledComponentsLP(packageSetting, parser);
9111 } else if (tagName.equals("sigs")) {
9112 packageSetting.signatures.readXml(parser, mPastSignatures);
9113 } else if (tagName.equals("perms")) {
9114 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009115 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009116 packageSetting.permissionsFixed = true;
9117 } else {
9118 reportSettingsProblem(Log.WARN,
9119 "Unknown element under <package>: "
9120 + parser.getName());
9121 XmlUtils.skipCurrentTag(parser);
9122 }
9123 }
9124 } else {
9125 XmlUtils.skipCurrentTag(parser);
9126 }
9127 }
9128
9129 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9130 XmlPullParser parser)
9131 throws IOException, XmlPullParserException {
9132 int outerDepth = parser.getDepth();
9133 int type;
9134 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9135 && (type != XmlPullParser.END_TAG
9136 || parser.getDepth() > outerDepth)) {
9137 if (type == XmlPullParser.END_TAG
9138 || type == XmlPullParser.TEXT) {
9139 continue;
9140 }
9141
9142 String tagName = parser.getName();
9143 if (tagName.equals("item")) {
9144 String name = parser.getAttributeValue(null, "name");
9145 if (name != null) {
9146 packageSetting.disabledComponents.add(name.intern());
9147 } else {
9148 reportSettingsProblem(Log.WARN,
9149 "Error in package manager settings: <disabled-components> has"
9150 + " no name at " + parser.getPositionDescription());
9151 }
9152 } else {
9153 reportSettingsProblem(Log.WARN,
9154 "Unknown element under <disabled-components>: "
9155 + parser.getName());
9156 }
9157 XmlUtils.skipCurrentTag(parser);
9158 }
9159 }
9160
9161 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9162 XmlPullParser parser)
9163 throws IOException, XmlPullParserException {
9164 int outerDepth = parser.getDepth();
9165 int type;
9166 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9167 && (type != XmlPullParser.END_TAG
9168 || parser.getDepth() > outerDepth)) {
9169 if (type == XmlPullParser.END_TAG
9170 || type == XmlPullParser.TEXT) {
9171 continue;
9172 }
9173
9174 String tagName = parser.getName();
9175 if (tagName.equals("item")) {
9176 String name = parser.getAttributeValue(null, "name");
9177 if (name != null) {
9178 packageSetting.enabledComponents.add(name.intern());
9179 } else {
9180 reportSettingsProblem(Log.WARN,
9181 "Error in package manager settings: <enabled-components> has"
9182 + " no name at " + parser.getPositionDescription());
9183 }
9184 } else {
9185 reportSettingsProblem(Log.WARN,
9186 "Unknown element under <enabled-components>: "
9187 + parser.getName());
9188 }
9189 XmlUtils.skipCurrentTag(parser);
9190 }
9191 }
9192
9193 private void readSharedUserLP(XmlPullParser parser)
9194 throws XmlPullParserException, IOException {
9195 String name = null;
9196 String idStr = null;
9197 int pkgFlags = 0;
9198 SharedUserSetting su = null;
9199 try {
9200 name = parser.getAttributeValue(null, "name");
9201 idStr = parser.getAttributeValue(null, "userId");
9202 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9203 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9204 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9205 }
9206 if (name == null) {
9207 reportSettingsProblem(Log.WARN,
9208 "Error in package manager settings: <shared-user> has no name at "
9209 + parser.getPositionDescription());
9210 } else if (userId == 0) {
9211 reportSettingsProblem(Log.WARN,
9212 "Error in package manager settings: shared-user "
9213 + name + " has bad userId " + idStr + " at "
9214 + parser.getPositionDescription());
9215 } else {
9216 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9217 reportSettingsProblem(Log.ERROR,
9218 "Occurred while parsing settings at "
9219 + parser.getPositionDescription());
9220 }
9221 }
9222 } catch (NumberFormatException e) {
9223 reportSettingsProblem(Log.WARN,
9224 "Error in package manager settings: package "
9225 + name + " has bad userId " + idStr + " at "
9226 + parser.getPositionDescription());
9227 };
9228
9229 if (su != null) {
9230 int outerDepth = parser.getDepth();
9231 int type;
9232 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9233 && (type != XmlPullParser.END_TAG
9234 || parser.getDepth() > outerDepth)) {
9235 if (type == XmlPullParser.END_TAG
9236 || type == XmlPullParser.TEXT) {
9237 continue;
9238 }
9239
9240 String tagName = parser.getName();
9241 if (tagName.equals("sigs")) {
9242 su.signatures.readXml(parser, mPastSignatures);
9243 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009244 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009245 } else {
9246 reportSettingsProblem(Log.WARN,
9247 "Unknown element under <shared-user>: "
9248 + parser.getName());
9249 XmlUtils.skipCurrentTag(parser);
9250 }
9251 }
9252
9253 } else {
9254 XmlUtils.skipCurrentTag(parser);
9255 }
9256 }
9257
9258 private void readGrantedPermissionsLP(XmlPullParser parser,
9259 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9260 int outerDepth = parser.getDepth();
9261 int type;
9262 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9263 && (type != XmlPullParser.END_TAG
9264 || parser.getDepth() > outerDepth)) {
9265 if (type == XmlPullParser.END_TAG
9266 || type == XmlPullParser.TEXT) {
9267 continue;
9268 }
9269
9270 String tagName = parser.getName();
9271 if (tagName.equals("item")) {
9272 String name = parser.getAttributeValue(null, "name");
9273 if (name != null) {
9274 outPerms.add(name.intern());
9275 } else {
9276 reportSettingsProblem(Log.WARN,
9277 "Error in package manager settings: <perms> has"
9278 + " no name at " + parser.getPositionDescription());
9279 }
9280 } else {
9281 reportSettingsProblem(Log.WARN,
9282 "Unknown element under <perms>: "
9283 + parser.getName());
9284 }
9285 XmlUtils.skipCurrentTag(parser);
9286 }
9287 }
9288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009289 private void readPreferredActivitiesLP(XmlPullParser parser)
9290 throws XmlPullParserException, IOException {
9291 int outerDepth = parser.getDepth();
9292 int type;
9293 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9294 && (type != XmlPullParser.END_TAG
9295 || parser.getDepth() > outerDepth)) {
9296 if (type == XmlPullParser.END_TAG
9297 || type == XmlPullParser.TEXT) {
9298 continue;
9299 }
9300
9301 String tagName = parser.getName();
9302 if (tagName.equals("item")) {
9303 PreferredActivity pa = new PreferredActivity(parser);
9304 if (pa.mParseError == null) {
9305 mPreferredActivities.addFilter(pa);
9306 } else {
9307 reportSettingsProblem(Log.WARN,
9308 "Error in package manager settings: <preferred-activity> "
9309 + pa.mParseError + " at "
9310 + parser.getPositionDescription());
9311 }
9312 } else {
9313 reportSettingsProblem(Log.WARN,
9314 "Unknown element under <preferred-activities>: "
9315 + parser.getName());
9316 XmlUtils.skipCurrentTag(parser);
9317 }
9318 }
9319 }
9320
9321 // Returns -1 if we could not find an available UserId to assign
9322 private int newUserIdLP(Object obj) {
9323 // Let's be stupidly inefficient for now...
9324 final int N = mUserIds.size();
9325 for (int i=0; i<N; i++) {
9326 if (mUserIds.get(i) == null) {
9327 mUserIds.set(i, obj);
9328 return FIRST_APPLICATION_UID + i;
9329 }
9330 }
9331
9332 // None left?
9333 if (N >= MAX_APPLICATION_UIDS) {
9334 return -1;
9335 }
9336
9337 mUserIds.add(obj);
9338 return FIRST_APPLICATION_UID + N;
9339 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009341 public PackageSetting getDisabledSystemPkg(String name) {
9342 synchronized(mPackages) {
9343 PackageSetting ps = mDisabledSysPackages.get(name);
9344 return ps;
9345 }
9346 }
9347
9348 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009349 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9350 return true;
9351 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009352 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9353 if (Config.LOGV) {
9354 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9355 + " componentName = " + componentInfo.name);
9356 Log.v(TAG, "enabledComponents: "
9357 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9358 Log.v(TAG, "disabledComponents: "
9359 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9360 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009361 if (packageSettings == null) {
9362 if (false) {
9363 Log.w(TAG, "WAITING FOR DEBUGGER");
9364 Debug.waitForDebugger();
9365 Log.i(TAG, "We will crash!");
9366 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009367 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009368 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009369 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9370 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9371 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9372 return false;
9373 }
9374 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9375 return true;
9376 }
9377 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9378 return false;
9379 }
9380 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009381 }
9382 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009383
9384 // ------- apps on sdcard specific code -------
9385 static final boolean DEBUG_SD_INSTALL = false;
Oscar Montemayord02546b2010-01-14 16:38:40 -08009386 final private String mSdEncryptKey = "AppsOnSD";
Oscar Montemayor462f0372010-01-14 16:38:40 -08009387 final private String mSdEncryptAlg = "AES";
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009388 private boolean mMediaMounted = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009389 private static final int MAX_CONTAINERS = 250;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009390
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009391 private String getEncryptKey() {
9392 try {
9393 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(mSdEncryptKey);
9394 if (sdEncKey == null) {
9395 sdEncKey = SystemKeyStore.getInstance().
9396 generateNewKeyHexString(128, mSdEncryptAlg, mSdEncryptKey);
9397 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009398 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009399 return null;
9400 }
9401 }
9402 return sdEncKey;
9403 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009404 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009405 return null;
9406 }
9407 }
9408
Kenny Rootc78a8072010-07-27 15:18:38 -07009409 /* package */ static String getTempContainerId() {
9410 int tmpIdx = 1;
9411 String list[] = PackageHelper.getSecureContainerList();
9412 if (list != null) {
9413 for (final String name : list) {
9414 // Ignore null and non-temporary container entries
9415 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9416 continue;
9417 }
9418
9419 String subStr = name.substring(mTempContainerPrefix.length());
9420 try {
9421 int cid = Integer.parseInt(subStr);
9422 if (cid >= tmpIdx) {
9423 tmpIdx = cid + 1;
9424 }
9425 } catch (NumberFormatException e) {
9426 }
9427 }
9428 }
9429 return mTempContainerPrefix + tmpIdx;
9430 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009431
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009432 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009433 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009434 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009435 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9436 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9437 throw new SecurityException("Media status can only be updated by the system");
9438 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009439 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009440 Log.i(TAG, "Updating external media status from " +
9441 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9442 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009443 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9444 mediaStatus+", mMediaMounted=" + mMediaMounted);
9445 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009446 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9447 reportStatus ? 1 : 0, -1);
9448 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009449 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009450 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009451 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009452 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009453 // Queue up an async operation since the package installation may take a little while.
9454 mHandler.post(new Runnable() {
9455 public void run() {
9456 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009457 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009458 }
9459 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009460 }
9461
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009462 /*
9463 * Collect information of applications on external media, map them
9464 * against existing containers and update information based on current
9465 * mount status. Please note that we always have to report status
9466 * if reportStatus has been set to true especially when unloading packages.
9467 */
9468 private void updateExternalMediaStatusInner(boolean mediaStatus,
9469 boolean reportStatus) {
9470 // Collection of uids
9471 int uidArr[] = null;
9472 // Collection of stale containers
9473 HashSet<String> removeCids = new HashSet<String>();
9474 // Collection of packages on external media with valid containers.
9475 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9476 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009477 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009478 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009479 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009480 } else {
9481 // Process list of secure containers and categorize them
9482 // as active or stale based on their package internal state.
9483 int uidList[] = new int[list.length];
9484 int num = 0;
9485 synchronized (mPackages) {
9486 for (String cid : list) {
9487 SdInstallArgs args = new SdInstallArgs(cid);
9488 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009489 String pkgName = args.getPackageName();
9490 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009491 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9492 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009493 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009494 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009495 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9496 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009497 // The package status is changed only if the code path
9498 // matches between settings and the container id.
9499 if (ps != null && ps.codePathString != null &&
9500 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009501 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9502 " corresponds to pkg : " + pkgName +
9503 " at code path: " + ps.codePathString);
9504 // We do have a valid package installed on sdcard
9505 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009506 int uid = ps.userId;
9507 if (uid != -1) {
9508 uidList[num++] = uid;
9509 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009510 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009511 // Stale container on sdcard. Just delete
9512 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9513 removeCids.add(cid);
9514 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009515 }
9516 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009517
9518 if (num > 0) {
9519 // Sort uid list
9520 Arrays.sort(uidList, 0, num);
9521 // Throw away duplicates
9522 uidArr = new int[num];
9523 uidArr[0] = uidList[0];
9524 int di = 0;
9525 for (int i = 1; i < num; i++) {
9526 if (uidList[i-1] != uidList[i]) {
9527 uidArr[di++] = uidList[i];
9528 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009529 }
9530 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009531 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009532 // Process packages with valid entries.
9533 if (mediaStatus) {
9534 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009535 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009536 startCleaningPackages();
9537 } else {
9538 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009539 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009540 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009541 }
9542
9543 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009544 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009545 int size = pkgList.size();
9546 if (size > 0) {
9547 // Send broadcasts here
9548 Bundle extras = new Bundle();
9549 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9550 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009551 if (uidArr != null) {
9552 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9553 }
9554 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9555 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009556 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009557 }
9558 }
9559
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009560 /*
9561 * Look at potentially valid container ids from processCids
9562 * If package information doesn't match the one on record
9563 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009564 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009565 */
9566 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009567 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009568 ArrayList<String> pkgList = new ArrayList<String>();
9569 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009570 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009571 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009572 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009573 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9574 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009575 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009576 try {
9577 // Make sure there are no container errors first.
9578 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9579 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009580 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009581 " when installing from sdcard");
9582 continue;
9583 }
9584 // Check code path here.
9585 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009586 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009587 " does not match one in settings " + codePath);
9588 continue;
9589 }
9590 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009591 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009592 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009593 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009594 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9595 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009596 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009597 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009598 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009599 retCode = PackageManager.INSTALL_SUCCEEDED;
9600 pkgList.add(pkg.packageName);
9601 // Post process args
9602 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9603 }
9604 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009605 Slog.i(TAG, "Failed to install pkg from " +
9606 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009607 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009608 }
9609
9610 } finally {
9611 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9612 // Don't destroy container here. Wait till gc clears things up.
9613 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009614 }
9615 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009616 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009617 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009618 // If the platform SDK has changed since the last time we booted,
9619 // we need to re-grant app permission to catch any new ones that
9620 // appear. This is really a hack, and means that apps can in some
9621 // cases get permissions that the user didn't initially explicitly
9622 // allow... it would be nice to have some better way to handle
9623 // this situation.
9624 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9625 != mSdkVersion;
9626 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9627 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9628 + "; regranting permissions for external storage");
9629 mSettings.mExternalSdkPlatform = mSdkVersion;
9630
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009631 // Make sure group IDs have been assigned, and any permission
9632 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009633 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009634 // Persist settings
9635 mSettings.writeLP();
9636 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009637 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009638 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009639 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009640 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009641 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009642 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009643 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009644 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009645 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009646 if (removeCids != null) {
9647 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009648 if (cid.startsWith(mTempContainerPrefix)) {
9649 Log.i(TAG, "Destroying stale temporary container " + cid);
9650 PackageHelper.destroySdDir(cid);
9651 } else {
9652 Log.w(TAG, "Container " + cid + " is stale");
9653 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009654 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009655 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009656 }
9657
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009658 /*
9659 * Utility method to unload a list of specified containers
9660 */
9661 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9662 // Just unmount all valid containers.
9663 for (SdInstallArgs arg : cidArgs) {
9664 synchronized (mInstallLock) {
9665 arg.doPostDeleteLI(false);
9666 }
9667 }
9668 }
9669
9670 /*
9671 * Unload packages mounted on external media. This involves deleting
9672 * package data from internal structures, sending broadcasts about
9673 * diabled packages, gc'ing to free up references, unmounting all
9674 * secure containers corresponding to packages on external media, and
9675 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9676 * Please note that we always have to post this message if status has
9677 * been requested no matter what.
9678 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009679 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009680 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009681 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009682 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009683 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009684 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009685 for (SdInstallArgs args : keys) {
9686 String cid = args.cid;
9687 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009688 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009689 // Delete package internally
9690 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9691 synchronized (mInstallLock) {
9692 boolean res = deletePackageLI(pkgName, false,
9693 PackageManager.DONT_DELETE_DATA, outInfo);
9694 if (res) {
9695 pkgList.add(pkgName);
9696 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009697 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009698 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009699 }
9700 }
9701 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009702 // We have to absolutely send UPDATED_MEDIA_STATUS only
9703 // after confirming that all the receivers processed the ordered
9704 // broadcast when packages get disabled, force a gc to clean things up.
9705 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009706 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009707 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9708 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9709 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009710 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9711 reportStatus ? 1 : 0, 1, keys);
9712 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009713 }
9714 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009715 } else {
9716 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9717 reportStatus ? 1 : 0, -1, keys);
9718 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009719 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009720 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009721
9722 public void movePackage(final String packageName,
9723 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009724 mContext.enforceCallingOrSelfPermission(
9725 android.Manifest.permission.MOVE_PACKAGE, null);
9726 int returnCode = PackageManager.MOVE_SUCCEEDED;
9727 int currFlags = 0;
9728 int newFlags = 0;
9729 synchronized (mPackages) {
9730 PackageParser.Package pkg = mPackages.get(packageName);
9731 if (pkg == null) {
9732 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009733 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009734 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009735 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009736 Slog.w(TAG, "Cannot move system application");
9737 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009738 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009739 Slog.w(TAG, "Cannot move forward locked app.");
9740 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009741 } else if (pkg.mOperationPending) {
9742 Slog.w(TAG, "Attempt to move package which has pending operations");
9743 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009744 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009745 // Find install location first
9746 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9747 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9748 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009749 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009750 } else {
9751 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9752 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009753 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9754 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009755 if (newFlags == currFlags) {
9756 Slog.w(TAG, "No move required. Trying to move to same location");
9757 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9758 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009759 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009760 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9761 pkg.mOperationPending = true;
9762 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009763 }
9764 }
9765 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009766 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009767 } else {
9768 Message msg = mHandler.obtainMessage(INIT_COPY);
9769 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009770 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9771 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9772 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009773 msg.obj = mp;
9774 mHandler.sendMessage(msg);
9775 }
9776 }
9777 }
9778
9779 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9780 // Queue up an async operation since the package deletion may take a little while.
9781 mHandler.post(new Runnable() {
9782 public void run() {
9783 mHandler.removeCallbacks(this);
9784 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009785 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9786 int uidArr[] = null;
9787 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009788 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009789 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009790 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009791 Slog.w(TAG, " Package " + mp.packageName +
9792 " doesn't exist. Aborting move");
9793 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9794 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9795 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9796 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9797 " Aborting move and returning error");
9798 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9799 } else {
9800 uidArr = new int[] { pkg.applicationInfo.uid };
9801 pkgList = new ArrayList<String>();
9802 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009803 }
9804 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009805 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9806 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009807 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009808 // Update package code and resource paths
9809 synchronized (mInstallLock) {
9810 synchronized (mPackages) {
9811 PackageParser.Package pkg = mPackages.get(mp.packageName);
9812 // Recheck for package again.
9813 if (pkg == null ) {
9814 Slog.w(TAG, " Package " + mp.packageName +
9815 " doesn't exist. Aborting move");
9816 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9817 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9818 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9819 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9820 " Aborting move and returning error");
9821 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9822 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009823 final String oldCodePath = pkg.mPath;
9824 final String newCodePath = mp.targetArgs.getCodePath();
9825 final String newResPath = mp.targetArgs.getResourcePath();
9826 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009827 pkg.mPath = newCodePath;
9828 // Move dex files around
9829 if (moveDexFilesLI(pkg)
9830 != PackageManager.INSTALL_SUCCEEDED) {
9831 // Moving of dex files failed. Set
9832 // error code and abort move.
9833 pkg.mPath = pkg.mScanPath;
9834 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9835 } else {
9836 pkg.mScanPath = newCodePath;
9837 pkg.applicationInfo.sourceDir = newCodePath;
9838 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009839 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009840 PackageSetting ps = (PackageSetting) pkg.mExtras;
9841 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9842 ps.codePathString = ps.codePath.getPath();
9843 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9844 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009845 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009846 // Set the application info flag correctly.
9847 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9848 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9849 } else {
9850 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9851 }
9852 ps.setFlags(pkg.applicationInfo.flags);
9853 mAppDirs.remove(oldCodePath);
9854 mAppDirs.put(newCodePath, pkg);
9855 // Persist settings
9856 mSettings.writeLP();
9857 }
9858 }
9859 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009860 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009861 // Send resources available broadcast
9862 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009863 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009864 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009865 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009866 // Clean up failed installation
9867 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009868 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009869 }
9870 } else {
9871 // Force a gc to clear things up.
9872 Runtime.getRuntime().gc();
9873 // Delete older code
9874 synchronized (mInstallLock) {
9875 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009876 }
9877 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009878
9879 // Allow more operations on this file if we didn't fail because
9880 // an operation was already pending for this package.
9881 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9882 synchronized (mPackages) {
9883 PackageParser.Package pkg = mPackages.get(mp.packageName);
9884 if (pkg != null) {
9885 pkg.mOperationPending = false;
9886 }
9887 }
9888 }
9889
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009890 IPackageMoveObserver observer = mp.observer;
9891 if (observer != null) {
9892 try {
9893 observer.packageMoved(mp.packageName, returnCode);
9894 } catch (RemoteException e) {
9895 Log.i(TAG, "Observer no longer exists.");
9896 }
9897 }
9898 }
9899 });
9900 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009901
9902 public boolean setInstallLocation(int loc) {
9903 mContext.enforceCallingOrSelfPermission(
9904 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9905 if (getInstallLocation() == loc) {
9906 return true;
9907 }
9908 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9909 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9910 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9911 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9912 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9913 return true;
9914 }
9915 return false;
9916 }
9917
9918 public int getInstallLocation() {
9919 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9920 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009922}