blob: 685bee4857a3910910f5e0907def60c35773bb09 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080019import com.android.internal.app.IMediaContainerService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import com.android.internal.app.ResolverActivity;
Kenny Root85387d72010-08-26 10:13:11 -070021import com.android.internal.content.NativeLibraryHelper;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -080022import com.android.internal.content.PackageHelper;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080023import com.android.internal.util.FastXmlSerializer;
Dianne Hackborn1afd1c92010-03-18 22:47:17 -070024import com.android.internal.util.JournaledFile;
Dianne Hackborn2269d1572010-02-24 19:54:22 -080025import com.android.internal.util.XmlUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026
27import org.xmlpull.v1.XmlPullParser;
28import org.xmlpull.v1.XmlPullParserException;
29import org.xmlpull.v1.XmlSerializer;
30
31import android.app.ActivityManagerNative;
32import android.app.IActivityManager;
Dianne Hackborn87bba1e2010-02-26 17:25:54 -080033import android.app.admin.IDevicePolicyManager;
Christopher Tate45281862010-03-05 15:46:30 -080034import android.app.backup.IBackupManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.Context;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070036import android.content.ComponentName;
Dianne Hackbornecb0e632010-04-07 20:22:55 -070037import android.content.IIntentReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.Intent;
39import android.content.IntentFilter;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070040import android.content.IntentSender;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080041import android.content.ServiceConnection;
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -070042import android.content.IntentSender.SendIntentException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.ActivityInfo;
44import android.content.pm.ApplicationInfo;
45import android.content.pm.ComponentInfo;
Dianne Hackborn49237342009-08-27 20:08:01 -070046import android.content.pm.FeatureInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.pm.IPackageDataObserver;
48import android.content.pm.IPackageDeleteObserver;
49import android.content.pm.IPackageInstallObserver;
50import android.content.pm.IPackageManager;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -080051import android.content.pm.IPackageMoveObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.pm.IPackageStatsObserver;
53import android.content.pm.InstrumentationInfo;
54import android.content.pm.PackageInfo;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -080055import android.content.pm.PackageInfoLite;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.content.pm.PackageManager;
57import android.content.pm.PackageStats;
58import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
59import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
60import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.content.pm.PackageParser;
62import android.content.pm.PermissionInfo;
63import android.content.pm.PermissionGroupInfo;
64import android.content.pm.ProviderInfo;
65import android.content.pm.ResolveInfo;
66import android.content.pm.ServiceInfo;
67import android.content.pm.Signature;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.Uri;
69import android.os.Binder;
Dianne Hackborn851a5412009-05-08 12:06:44 -070070import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Bundle;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -080072import android.os.Debug;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.os.HandlerThread;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -080074import android.os.IBinder;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -070075import android.os.Looper;
76import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Parcel;
78import android.os.RemoteException;
79import android.os.Environment;
80import android.os.FileObserver;
81import android.os.FileUtils;
82import android.os.Handler;
83import android.os.ParcelFileDescriptor;
84import android.os.Process;
85import android.os.ServiceManager;
86import android.os.SystemClock;
87import android.os.SystemProperties;
Suchi Amalapurapu40e47252010-04-07 16:15:50 -070088import android.provider.Settings;
Oscar Montemayord02546b2010-01-14 16:38:40 -080089import android.security.SystemKeyStore;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.*;
91import android.view.Display;
92import android.view.WindowManager;
93
94import java.io.File;
95import java.io.FileDescriptor;
96import java.io.FileInputStream;
97import java.io.FileNotFoundException;
98import java.io.FileOutputStream;
99import java.io.FileReader;
100import java.io.FilenameFilter;
101import java.io.IOException;
102import java.io.InputStream;
103import java.io.PrintWriter;
Oscar Montemayord02546b2010-01-14 16:38:40 -0800104import java.security.NoSuchAlgorithmException;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800105import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.ArrayList;
107import java.util.Arrays;
Dianne Hackborn49237342009-08-27 20:08:01 -0700108import java.util.Collection;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.Collections;
110import java.util.Comparator;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800111import java.util.Date;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112import java.util.Enumeration;
113import java.util.HashMap;
114import java.util.HashSet;
115import java.util.Iterator;
Kenny Root85387d72010-08-26 10:13:11 -0700116import java.util.LinkedList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117import java.util.List;
118import java.util.Map;
119import java.util.Set;
120import java.util.zip.ZipEntry;
David 'Digit' Turnerfeba7432009-11-06 17:54:12 -0800121import java.util.zip.ZipException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122import java.util.zip.ZipFile;
123import java.util.zip.ZipOutputStream;
124
Dianne Hackbornd4310ac2010-03-16 22:55:08 -0700125/**
126 * Keep track of all those .apks everywhere.
127 *
128 * This is very central to the platform's security; please run the unit
129 * tests whenever making modifications here:
130 *
131mmm frameworks/base/tests/AndroidTests
132adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
133adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
134 *
135 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136class PackageManagerService extends IPackageManager.Stub {
137 private static final String TAG = "PackageManager";
138 private static final boolean DEBUG_SETTINGS = false;
139 private static final boolean DEBUG_PREFERRED = false;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800140 private static final boolean DEBUG_UPGRADE = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800141 private static final boolean DEBUG_INSTALL = false;
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -0700142 private static final boolean DEBUG_NATIVE = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143
144 private static final boolean MULTIPLE_APPLICATION_UIDS = true;
145 private static final int RADIO_UID = Process.PHONE_UID;
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400146 private static final int LOG_UID = Process.LOG_UID;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800147 private static final int FIRST_APPLICATION_UID =
148 Process.FIRST_APPLICATION_UID;
149 private static final int MAX_APPLICATION_UIDS = 1000;
150
151 private static final boolean SHOW_INFO = false;
152
153 private static final boolean GET_CERTIFICATES = true;
154
Oscar Montemayora8529f62009-11-18 10:14:20 -0800155 private static final String SYSTEM_PROPERTY_EFS_ENABLED = "persist.security.efs.enabled";
156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private static final int REMOVE_EVENTS =
158 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
159 private static final int ADD_EVENTS =
160 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
161
162 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800163 // Suffix used during package installation when copying/moving
164 // package apks to install directory.
165 private static final String INSTALL_PACKAGE_SUFFIX = "-";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -0800167 /**
168 * Indicates the state of installation. Used by PackageManager to
169 * figure out incomplete installations. Say a package is being installed
170 * (the state is set to PKG_INSTALL_INCOMPLETE) and remains so till
171 * the package installation is successful or unsuccesful lin which case
172 * the PackageManager will no longer maintain state information associated
173 * with the package. If some exception(like device freeze or battery being
174 * pulled out) occurs during installation of a package, the PackageManager
175 * needs this information to clean up the previously failed installation.
176 */
177 private static final int PKG_INSTALL_INCOMPLETE = 0;
178 private static final int PKG_INSTALL_COMPLETE = 1;
179
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 static final int SCAN_MONITOR = 1<<0;
181 static final int SCAN_NO_DEX = 1<<1;
182 static final int SCAN_FORCE_DEX = 1<<2;
183 static final int SCAN_UPDATE_SIGNATURE = 1<<3;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800184 static final int SCAN_NEW_INSTALL = 1<<4;
185 static final int SCAN_NO_PATHS = 1<<5;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Dianne Hackborn399cccb2010-04-13 22:57:49 -0700187 static final int REMOVE_CHATTY = 1<<16;
188
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800189 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
190 "com.android.defcontainer",
191 "com.android.defcontainer.DefaultContainerService");
Kenny Rootc78a8072010-07-27 15:18:38 -0700192
Kenny Root85387d72010-08-26 10:13:11 -0700193 private static final String LIB_DIR_NAME = "lib";
194
Kenny Rootc78a8072010-07-27 15:18:38 -0700195 static final String mTempContainerPrefix = "smdl2tmp";
196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197 final HandlerThread mHandlerThread = new HandlerThread("PackageManager",
198 Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700199 final PackageHandler mHandler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Dianne Hackborn851a5412009-05-08 12:06:44 -0700201 final int mSdkVersion = Build.VERSION.SDK_INT;
202 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME)
203 ? null : Build.VERSION.CODENAME;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800204
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 final Context mContext;
206 final boolean mFactoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700207 final boolean mNoDexOpt;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208 final DisplayMetrics mMetrics;
209 final int mDefParseFlags;
210 final String[] mSeparateProcesses;
211
212 // This is where all application persistent data goes.
213 final File mAppDataDir;
214
Oscar Montemayora8529f62009-11-18 10:14:20 -0800215 // If Encrypted File System feature is enabled, all application persistent data
216 // should go here instead.
217 final File mSecureAppDataDir;
218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 // This is the object monitoring the framework dir.
220 final FileObserver mFrameworkInstallObserver;
221
222 // This is the object monitoring the system app dir.
223 final FileObserver mSystemInstallObserver;
224
225 // This is the object monitoring mAppInstallDir.
226 final FileObserver mAppInstallObserver;
227
228 // This is the object monitoring mDrmAppPrivateInstallDir.
229 final FileObserver mDrmAppInstallObserver;
230
231 // Used for priviledge escalation. MUST NOT BE CALLED WITH mPackages
232 // LOCK HELD. Can be called with mInstallLock held.
233 final Installer mInstaller;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800234
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 final File mFrameworkDir;
236 final File mSystemAppDir;
237 final File mAppInstallDir;
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700238 final File mDalvikCacheDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
241 // apps.
242 final File mDrmAppPrivateInstallDir;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 // Lock for state used when installing and doing other long running
247 // operations. Methods that must be called with this lock held have
248 // the prefix "LI".
249 final Object mInstallLock = new Object();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 // These are the directories in the 3rd party applications installed dir
252 // that we have currently loaded packages from. Keys are the application's
253 // installed zip file (absolute codePath), and values are Package.
254 final HashMap<String, PackageParser.Package> mAppDirs =
255 new HashMap<String, PackageParser.Package>();
256
257 // Information for the parser to write more useful error messages.
258 File mScanningPath;
259 int mLastScanError;
260
261 final int[] mOutPermissions = new int[3];
262
263 // ----------------------------------------------------------------
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 // Keys are String (package name), values are Package. This also serves
266 // as the lock for the global state. Methods that must be called with
267 // this lock held have the prefix "LP".
268 final HashMap<String, PackageParser.Package> mPackages =
269 new HashMap<String, PackageParser.Package>();
270
271 final Settings mSettings;
272 boolean mRestoredSettings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800273
274 // Group-ids that are given to all packages as read from etc/permissions/*.xml.
275 int[] mGlobalGids;
276
277 // These are the built-in uid -> permission mappings that were read from the
278 // etc/permissions.xml file.
279 final SparseArray<HashSet<String>> mSystemPermissions =
280 new SparseArray<HashSet<String>>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800282 // These are the built-in shared libraries that were read from the
283 // etc/permissions.xml file.
284 final HashMap<String, String> mSharedLibraries = new HashMap<String, String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800285
Dianne Hackborn49237342009-08-27 20:08:01 -0700286 // Temporary for building the final shared libraries for an .apk.
287 String[] mTmpSharedLibraries = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800288
Dianne Hackborn49237342009-08-27 20:08:01 -0700289 // These are the features this devices supports that were read from the
290 // etc/permissions.xml file.
291 final HashMap<String, FeatureInfo> mAvailableFeatures =
292 new HashMap<String, FeatureInfo>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 // All available activities, for your resolving pleasure.
295 final ActivityIntentResolver mActivities =
296 new ActivityIntentResolver();
297
298 // All available receivers, for your resolving pleasure.
299 final ActivityIntentResolver mReceivers =
300 new ActivityIntentResolver();
301
302 // All available services, for your resolving pleasure.
303 final ServiceIntentResolver mServices = new ServiceIntentResolver();
304
305 // Keys are String (provider class name), values are Provider.
306 final HashMap<ComponentName, PackageParser.Provider> mProvidersByComponent =
307 new HashMap<ComponentName, PackageParser.Provider>();
308
309 // Mapping from provider base names (first directory in content URI codePath)
310 // to the provider information.
311 final HashMap<String, PackageParser.Provider> mProviders =
312 new HashMap<String, PackageParser.Provider>();
313
314 // Mapping from instrumentation class names to info about them.
315 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
316 new HashMap<ComponentName, PackageParser.Instrumentation>();
317
318 // Mapping from permission names to info about them.
319 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
320 new HashMap<String, PackageParser.PermissionGroup>();
321
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800322 // Packages whose data we have transfered into another package, thus
323 // should no longer exist.
324 final HashSet<String> mTransferedPackages = new HashSet<String>();
325
Dianne Hackborn854060af2009-07-09 18:14:31 -0700326 // Broadcast actions that are only available to the system.
327 final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800329 boolean mSystemReady;
330 boolean mSafeMode;
331 boolean mHasSystemUidErrors;
332
333 ApplicationInfo mAndroidApplication;
334 final ActivityInfo mResolveActivity = new ActivityInfo();
335 final ResolveInfo mResolveInfo = new ResolveInfo();
336 ComponentName mResolveComponentName;
337 PackageParser.Package mPlatformPackage;
338
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700339 // Set of pending broadcasts for aggregating enable/disable of components.
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800340 final HashMap<String, ArrayList<String>> mPendingBroadcasts
341 = new HashMap<String, ArrayList<String>>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800342 // Service Connection to remote media container service to copy
343 // package uri's from external media onto secure containers
344 // or internal storage.
345 private IMediaContainerService mContainerService = null;
346
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700347 static final int SEND_PENDING_BROADCAST = 1;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800348 static final int MCS_BOUND = 3;
349 static final int END_COPY = 4;
350 static final int INIT_COPY = 5;
351 static final int MCS_UNBIND = 6;
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800352 static final int START_CLEANING_PACKAGE = 7;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800353 static final int FIND_INSTALL_LOC = 8;
Christopher Tate1bb69062010-02-19 17:02:12 -0800354 static final int POST_INSTALL = 9;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800355 static final int MCS_RECONNECT = 10;
356 static final int MCS_GIVE_UP = 11;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700357 static final int UPDATED_MEDIA_STATUS = 12;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700358 static final int WRITE_SETTINGS = 13;
359
360 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800361
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700362 // Delay time in millisecs
363 static final int BROADCAST_DELAY = 10 * 1000;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800364 final private DefaultContainerConnection mDefContainerConn =
365 new DefaultContainerConnection();
366 class DefaultContainerConnection implements ServiceConnection {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800367 public void onServiceConnected(ComponentName name, IBinder service) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800368 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800369 IMediaContainerService imcs =
370 IMediaContainerService.Stub.asInterface(service);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800371 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800372 }
373
374 public void onServiceDisconnected(ComponentName name) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800375 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800376 }
377 };
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700378
Christopher Tate1bb69062010-02-19 17:02:12 -0800379 // Recordkeeping of restore-after-install operations that are currently in flight
380 // between the Package Manager and the Backup Manager
381 class PostInstallData {
382 public InstallArgs args;
383 public PackageInstalledInfo res;
384
385 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
386 args = _a;
387 res = _r;
388 }
389 };
390 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
391 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows
392
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700393 class PackageHandler extends Handler {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800394 private boolean mBound = false;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800395 final ArrayList<HandlerParams> mPendingInstalls =
396 new ArrayList<HandlerParams>();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800397
398 private boolean connectToService() {
399 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
400 " DefaultContainerService");
401 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700402 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800403 if (mContext.bindService(service, mDefContainerConn,
404 Context.BIND_AUTO_CREATE)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700405 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800406 mBound = true;
407 return true;
408 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700409 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800410 return false;
411 }
412
413 private void disconnectService() {
414 mContainerService = null;
415 mBound = false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700416 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800417 mContext.unbindService(mDefContainerConn);
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800419 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800420
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700421 PackageHandler(Looper looper) {
422 super(looper);
423 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700424
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700425 public void handleMessage(Message msg) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700426 try {
427 doHandleMessage(msg);
428 } finally {
429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
430 }
431 }
432
433 void doHandleMessage(Message msg) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700434 switch (msg.what) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800435 case INIT_COPY: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800436 if (DEBUG_SD_INSTALL) Log.i(TAG, "init_copy");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -0800437 HandlerParams params = (HandlerParams) msg.obj;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800438 int idx = mPendingInstalls.size();
439 if (DEBUG_SD_INSTALL) Log.i(TAG, "idx=" + idx);
440 // If a bind was already initiated we dont really
441 // need to do anything. The pending install
442 // will be processed later on.
443 if (!mBound) {
444 // If this is the only one pending we might
445 // have to bind to the service again.
446 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800447 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800448 params.serviceError();
449 return;
450 } else {
451 // Once we bind to the service, the first
452 // pending request will be processed.
453 mPendingInstalls.add(idx, params);
454 }
455 } else {
456 mPendingInstalls.add(idx, params);
457 // Already bound to the service. Just make
458 // sure we trigger off processing the first request.
459 if (idx == 0) {
460 mHandler.sendEmptyMessage(MCS_BOUND);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800461 }
462 }
463 break;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800464 }
465 case MCS_BOUND: {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800466 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_bound");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800467 if (msg.obj != null) {
468 mContainerService = (IMediaContainerService) msg.obj;
469 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800470 if (mContainerService == null) {
471 // Something seriously wrong. Bail out
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800472 Slog.e(TAG, "Cannot bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800473 for (HandlerParams params : mPendingInstalls) {
474 mPendingInstalls.remove(0);
475 // Indicate service bind error
476 params.serviceError();
477 }
478 mPendingInstalls.clear();
479 } else if (mPendingInstalls.size() > 0) {
480 HandlerParams params = mPendingInstalls.get(0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -0800481 if (params != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800482 params.startCopy();
483 }
484 } else {
485 // Should never happen ideally.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800486 Slog.w(TAG, "Empty queue");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800487 }
488 break;
489 }
490 case MCS_RECONNECT : {
491 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_reconnect");
492 if (mPendingInstalls.size() > 0) {
493 if (mBound) {
494 disconnectService();
495 }
496 if (!connectToService()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800497 Slog.e(TAG, "Failed to bind to media container service");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800498 for (HandlerParams params : mPendingInstalls) {
499 mPendingInstalls.remove(0);
500 // Indicate service bind error
501 params.serviceError();
502 }
503 mPendingInstalls.clear();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800504 }
505 }
506 break;
507 }
508 case MCS_UNBIND : {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800509 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_unbind");
510 // Delete pending install
511 if (mPendingInstalls.size() > 0) {
512 mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800513 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -0800514 if (mPendingInstalls.size() == 0) {
515 if (mBound) {
516 disconnectService();
517 }
518 } else {
519 // There are more pending requests in queue.
520 // Just post MCS_BOUND message to trigger processing
521 // of next pending install.
522 mHandler.sendEmptyMessage(MCS_BOUND);
523 }
524 break;
525 }
526 case MCS_GIVE_UP: {
527 if (DEBUG_SD_INSTALL) Log.i(TAG, "mcs_giveup too many retries");
528 HandlerParams params = mPendingInstalls.remove(0);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800529 break;
530 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700531 case SEND_PENDING_BROADCAST : {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800532 String packages[];
533 ArrayList components[];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700534 int size = 0;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700535 int uids[];
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700536 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700537 synchronized (mPackages) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800538 if (mPendingBroadcasts == null) {
539 return;
540 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700541 size = mPendingBroadcasts.size();
542 if (size <= 0) {
543 // Nothing to be done. Just return
544 return;
545 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800546 packages = new String[size];
547 components = new ArrayList[size];
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700548 uids = new int[size];
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800549 Iterator<HashMap.Entry<String, ArrayList<String>>>
550 it = mPendingBroadcasts.entrySet().iterator();
551 int i = 0;
552 while (it.hasNext() && i < size) {
553 HashMap.Entry<String, ArrayList<String>> ent = it.next();
554 packages[i] = ent.getKey();
555 components[i] = ent.getValue();
556 PackageSetting ps = mSettings.mPackages.get(ent.getKey());
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700557 uids[i] = (ps != null) ? ps.userId : -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800558 i++;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700559 }
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800560 size = i;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700561 mPendingBroadcasts.clear();
562 }
563 // Send broadcasts
564 for (int i = 0; i < size; i++) {
Dianne Hackborn86a72da2009-11-11 20:12:41 -0800565 sendPackageChangedBroadcast(packages[i], true,
566 (ArrayList<String>)components[i], uids[i]);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700567 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700568 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700569 break;
570 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800571 case START_CLEANING_PACKAGE: {
572 String packageName = (String)msg.obj;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800574 synchronized (mPackages) {
575 if (!mSettings.mPackagesToBeCleaned.contains(packageName)) {
576 mSettings.mPackagesToBeCleaned.add(packageName);
577 }
578 }
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
Dianne Hackborne83cefce2010-02-04 17:38:14 -0800580 startCleaningPackages();
581 } break;
Christopher Tate1bb69062010-02-19 17:02:12 -0800582 case POST_INSTALL: {
583 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
584 PostInstallData data = mRunningInstalls.get(msg.arg1);
585 mRunningInstalls.delete(msg.arg1);
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700586 boolean deleteOld = false;
Christopher Tate1bb69062010-02-19 17:02:12 -0800587
588 if (data != null) {
589 InstallArgs args = data.args;
590 PackageInstalledInfo res = data.res;
591
592 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700593 res.removedInfo.sendBroadcast(false, true);
Christopher Tate1bb69062010-02-19 17:02:12 -0800594 Bundle extras = new Bundle(1);
595 extras.putInt(Intent.EXTRA_UID, res.uid);
596 final boolean update = res.removedInfo.removedPackage != null;
597 if (update) {
598 extras.putBoolean(Intent.EXTRA_REPLACING, true);
599 }
600 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
601 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700602 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800603 if (update) {
604 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
605 res.pkg.applicationInfo.packageName,
Dianne Hackbornecb0e632010-04-07 20:22:55 -0700606 extras, null);
Christopher Tate1bb69062010-02-19 17:02:12 -0800607 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -0700608 if (res.removedInfo.args != null) {
609 // Remove the replaced package's older resources safely now
610 deleteOld = true;
611 }
612 }
613 // Force a gc to clear up things
614 Runtime.getRuntime().gc();
615 // We delete after a gc for applications on sdcard.
616 if (deleteOld) {
617 synchronized (mInstallLock) {
618 res.removedInfo.args.doPostDeleteLI(true);
619 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -0800620 }
Christopher Tate1bb69062010-02-19 17:02:12 -0800621 if (args.observer != null) {
622 try {
623 args.observer.packageInstalled(res.name, res.returnCode);
624 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800625 Slog.i(TAG, "Observer no longer exists.");
Christopher Tate1bb69062010-02-19 17:02:12 -0800626 }
627 }
628 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800629 Slog.e(TAG, "Bogus post-install token " + msg.arg1);
Christopher Tate1bb69062010-02-19 17:02:12 -0800630 }
631 } break;
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700632 case UPDATED_MEDIA_STATUS: {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -0700633 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
634 boolean reportStatus = msg.arg1 == 1;
635 boolean doGc = msg.arg2 == 1;
636 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
637 if (doGc) {
638 // Force a gc to clear up stale containers.
639 Runtime.getRuntime().gc();
640 }
641 if (msg.obj != null) {
642 Set<SdInstallArgs> args = (Set<SdInstallArgs>) msg.obj;
643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
644 // Unload containers
645 unloadAllContainers(args);
646 }
647 if (reportStatus) {
648 try {
649 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
650 PackageHelper.getMountService().finishMediaUpdate();
651 } catch (RemoteException e) {
652 Log.e(TAG, "MountService not running?");
653 }
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -0700654 }
655 } break;
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700656 case WRITE_SETTINGS: {
657 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
658 synchronized (mPackages) {
659 removeMessages(WRITE_SETTINGS);
660 mSettings.writeLP();
661 }
662 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
663 } break;
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700664 }
665 }
666 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800667
Dianne Hackbornd7c09682010-03-30 10:42:20 -0700668 void scheduleWriteSettingsLocked() {
669 if (!mHandler.hasMessages(WRITE_SETTINGS)) {
670 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
671 }
672 }
673
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800674 static boolean installOnSd(int flags) {
675 if (((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) ||
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700676 ((flags & PackageManager.INSTALL_INTERNAL) != 0)) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800677 return false;
678 }
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -0700679 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
680 return true;
681 }
682 return false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -0800683 }
684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800685 public static final IPackageManager main(Context context, boolean factoryTest) {
686 PackageManagerService m = new PackageManagerService(context, factoryTest);
687 ServiceManager.addService("package", m);
688 return m;
689 }
690
691 static String[] splitString(String str, char sep) {
692 int count = 1;
693 int i = 0;
694 while ((i=str.indexOf(sep, i)) >= 0) {
695 count++;
696 i++;
697 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 String[] res = new String[count];
700 i=0;
701 count = 0;
702 int lastI=0;
703 while ((i=str.indexOf(sep, i)) >= 0) {
704 res[count] = str.substring(lastI, i);
705 count++;
706 i++;
707 lastI = i;
708 }
709 res[count] = str.substring(lastI, str.length());
710 return res;
711 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 public PackageManagerService(Context context, boolean factoryTest) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800717 if (mSdkVersion <= 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800718 Slog.w(TAG, "**** ro.build.version.sdk not set!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800721 mContext = context;
722 mFactoryTest = factoryTest;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700723 mNoDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 mMetrics = new DisplayMetrics();
725 mSettings = new Settings();
726 mSettings.addSharedUserLP("android.uid.system",
727 Process.SYSTEM_UID, ApplicationInfo.FLAG_SYSTEM);
728 mSettings.addSharedUserLP("android.uid.phone",
729 MULTIPLE_APPLICATION_UIDS
730 ? RADIO_UID : FIRST_APPLICATION_UID,
731 ApplicationInfo.FLAG_SYSTEM);
Mike Lockwoodd42685d2009-09-03 09:25:22 -0400732 mSettings.addSharedUserLP("android.uid.log",
733 MULTIPLE_APPLICATION_UIDS
734 ? LOG_UID : FIRST_APPLICATION_UID,
735 ApplicationInfo.FLAG_SYSTEM);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736
737 String separateProcesses = SystemProperties.get("debug.separate_processes");
738 if (separateProcesses != null && separateProcesses.length() > 0) {
739 if ("*".equals(separateProcesses)) {
740 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
741 mSeparateProcesses = null;
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800742 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800743 } else {
744 mDefParseFlags = 0;
745 mSeparateProcesses = separateProcesses.split(",");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800746 Slog.w(TAG, "Running with debug.separate_processes: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800747 + separateProcesses);
748 }
749 } else {
750 mDefParseFlags = 0;
751 mSeparateProcesses = null;
752 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 Installer installer = new Installer();
755 // Little hacky thing to check if installd is here, to determine
756 // whether we are running on the simulator and thus need to take
757 // care of building the /data file structure ourself.
758 // (apparently the sim now has a working installer)
759 if (installer.ping() && Process.supportsProcesses()) {
760 mInstaller = installer;
761 } else {
762 mInstaller = null;
763 }
764
765 WindowManager wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
766 Display d = wm.getDefaultDisplay();
767 d.getMetrics(mMetrics);
768
769 synchronized (mInstallLock) {
770 synchronized (mPackages) {
771 mHandlerThread.start();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -0700772 mHandler = new PackageHandler(mHandlerThread.getLooper());
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800773
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 File dataDir = Environment.getDataDirectory();
775 mAppDataDir = new File(dataDir, "data");
Oscar Montemayora8529f62009-11-18 10:14:20 -0800776 mSecureAppDataDir = new File(dataDir, "secure/data");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
778
779 if (mInstaller == null) {
780 // Make sure these dirs exist, when we are running in
781 // the simulator.
782 // Make a wide-open directory for random misc stuff.
783 File miscDir = new File(dataDir, "misc");
784 miscDir.mkdirs();
785 mAppDataDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -0800786 mSecureAppDataDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 mDrmAppPrivateInstallDir.mkdirs();
788 }
789
790 readPermissions();
791
792 mRestoredSettings = mSettings.readLP();
793 long startTime = SystemClock.uptimeMillis();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800794
795 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 startTime);
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800797
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800798 // Set flag to monitor and not change apk file paths when
799 // scanning install directories.
800 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700801 if (mNoDexOpt) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800802 Slog.w(TAG, "Running ENG build: no pre-dexopt!");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800803 scanMode |= SCAN_NO_DEX;
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -0700804 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 final HashSet<String> libFiles = new HashSet<String>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 mFrameworkDir = new File(Environment.getRootDirectory(), "framework");
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700809 mDalvikCacheDir = new File(dataDir, "dalvik-cache");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 if (mInstaller != null) {
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700812 boolean didDexOpt = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800813
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800814 /**
815 * Out of paranoia, ensure that everything in the boot class
816 * path has been dexed.
817 */
818 String bootClassPath = System.getProperty("java.boot.class.path");
819 if (bootClassPath != null) {
820 String[] paths = splitString(bootClassPath, ':');
821 for (int i=0; i<paths.length; i++) {
822 try {
823 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) {
824 libFiles.add(paths[i]);
825 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700826 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800827 }
828 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800829 Slog.w(TAG, "Boot class path not found: " + paths[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800831 Slog.w(TAG, "Exception reading boot class path: " + paths[i], e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 }
833 }
834 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800835 Slog.w(TAG, "No BOOTCLASSPATH found!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 /**
839 * Also ensure all external libraries have had dexopt run on them.
840 */
841 if (mSharedLibraries.size() > 0) {
842 Iterator<String> libs = mSharedLibraries.values().iterator();
843 while (libs.hasNext()) {
844 String lib = libs.next();
845 try {
846 if (dalvik.system.DexFile.isDexOptNeeded(lib)) {
847 libFiles.add(lib);
848 mInstaller.dexopt(lib, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700849 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
851 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800852 Slog.w(TAG, "Library not found: " + lib);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800854 Slog.w(TAG, "Exception reading library: " + lib, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
856 }
857 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 // Gross hack for now: we know this file doesn't contain any
860 // code, so don't dexopt it to avoid the resulting log spew.
861 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk");
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 /**
864 * And there are a number of commands implemented in Java, which
865 * we currently need to do the dexopt on so that they can be
866 * run from a non-root shell.
867 */
868 String[] frameworkFiles = mFrameworkDir.list();
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700869 if (frameworkFiles != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 for (int i=0; i<frameworkFiles.length; i++) {
871 File libPath = new File(mFrameworkDir, frameworkFiles[i]);
872 String path = libPath.getPath();
873 // Skip the file if we alrady did it.
874 if (libFiles.contains(path)) {
875 continue;
876 }
877 // Skip the file if it is not a type we want to dexopt.
878 if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
879 continue;
880 }
881 try {
882 if (dalvik.system.DexFile.isDexOptNeeded(path)) {
883 mInstaller.dexopt(path, Process.SYSTEM_UID, true);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700884 didDexOpt = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800885 }
886 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800887 Slog.w(TAG, "Jar not found: " + path);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800888 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800889 Slog.w(TAG, "Exception reading jar: " + path, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 }
891 }
892 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800893
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700894 if (didDexOpt) {
895 // If we had to do a dexopt of one of the previous
896 // things, then something on the system has changed.
897 // Consider this significant, and wipe away all other
898 // existing dexopt files to ensure we don't leave any
899 // dangling around.
900 String[] files = mDalvikCacheDir.list();
901 if (files != null) {
902 for (int i=0; i<files.length; i++) {
903 String fn = files[i];
904 if (fn.startsWith("data@app@")
905 || fn.startsWith("data@app-private@")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800906 Slog.i(TAG, "Pruning dalvik file: " + fn);
Dianne Hackborna33e3f72009-09-29 17:28:24 -0700907 (new File(mDalvikCacheDir, fn)).delete();
908 }
909 }
910 }
911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800913
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800914 // Find base frameworks (resource packages without code).
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 mFrameworkInstallObserver = new AppDirObserver(
916 mFrameworkDir.getPath(), OBSERVER_EVENTS, true);
917 mFrameworkInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700918 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM
919 | PackageParser.PARSE_IS_SYSTEM_DIR,
Suchi Amalapurapudaec17222010-01-14 21:25:16 -0800920 scanMode | SCAN_NO_DEX);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800921
922 // Collect all system packages.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800923 mSystemAppDir = new File(Environment.getRootDirectory(), "app");
924 mSystemInstallObserver = new AppDirObserver(
925 mSystemAppDir.getPath(), OBSERVER_EVENTS, true);
926 mSystemInstallObserver.startWatching();
Dianne Hackborn806da1d2010-03-18 16:50:07 -0700927 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM
928 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800929
930 if (mInstaller != null) {
931 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
932 mInstaller.moveFiles();
933 }
934
935 // Prune any system packages that no longer exist.
936 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
937 while (psit.hasNext()) {
938 PackageSetting ps = psit.next();
939 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0
Dianne Hackborn6dee18c2010-02-09 23:59:16 -0800940 && !mPackages.containsKey(ps.name)
941 && !mSettings.mDisabledSysPackages.containsKey(ps.name)) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -0800942 psit.remove();
943 String msg = "System package " + ps.name
944 + " no longer exists; wiping its data";
945 reportSettingsProblem(Log.WARN, msg);
946 if (mInstaller != null) {
947 // XXX how to set useEncryptedFSDir for packages that
948 // are not encrypted?
949 mInstaller.remove(ps.name, true);
950 }
951 }
952 }
953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 mAppInstallDir = new File(dataDir, "app");
955 if (mInstaller == null) {
956 // Make sure these dirs exist, when we are running in
957 // the simulator.
958 mAppInstallDir.mkdirs(); // scanDirLI() assumes this dir exists
959 }
960 //look for any incomplete package installations
Oscar Montemayora8529f62009-11-18 10:14:20 -0800961 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackages();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962 //clean up list
963 for(int i = 0; i < deletePkgsList.size(); i++) {
964 //clean up here
965 cleanupInstallFailedPackage(deletePkgsList.get(i));
966 }
967 //delete tmp files
968 deleteTempPackageFiles();
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800969
970 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 SystemClock.uptimeMillis());
972 mAppInstallObserver = new AppDirObserver(
973 mAppInstallDir.getPath(), OBSERVER_EVENTS, false);
974 mAppInstallObserver.startWatching();
975 scanDirLI(mAppInstallDir, 0, scanMode);
976
977 mDrmAppInstallObserver = new AppDirObserver(
978 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false);
979 mDrmAppInstallObserver.startWatching();
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -0800980 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981
Doug Zongkerab5c49c2009-12-04 10:31:43 -0800982 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 SystemClock.uptimeMillis());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -0800984 Slog.i(TAG, "Time to scan packages: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 + ((SystemClock.uptimeMillis()-startTime)/1000f)
986 + " seconds");
987
Dianne Hackbornf22221f2010-04-05 18:35:42 -0700988 // If the platform SDK has changed since the last time we booted,
989 // we need to re-grant app permission to catch any new ones that
990 // appear. This is really a hack, and means that apps can in some
991 // cases get permissions that the user didn't initially explicitly
992 // allow... it would be nice to have some better way to handle
993 // this situation.
994 final boolean regrantPermissions = mSettings.mInternalSdkPlatform
995 != mSdkVersion;
996 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
997 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
998 + "; regranting permissions for internal storage");
999 mSettings.mInternalSdkPlatform = mSdkVersion;
1000
Dianne Hackborn92cfa102010-04-28 11:00:44 -07001001 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002
1003 mSettings.writeLP();
1004
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001005 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 SystemClock.uptimeMillis());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001007
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 // Now after opening every single application zip, make sure they
1009 // are all flushed. Not really needed, but keeps things nice and
1010 // tidy.
1011 Runtime.getRuntime().gc();
1012 } // synchronized (mPackages)
1013 } // synchronized (mInstallLock)
1014 }
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001015
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 @Override
1017 public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1018 throws RemoteException {
1019 try {
1020 return super.onTransact(code, data, reply, flags);
1021 } catch (RuntimeException e) {
1022 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001023 Slog.e(TAG, "Package Manager Crash", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
1025 throw e;
1026 }
1027 }
1028
Dianne Hackborne6620b22010-01-22 14:46:21 -08001029 void cleanupInstallFailedPackage(PackageSetting ps) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001030 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 if (mInstaller != null) {
Kenny Rootbdbc9252010-01-28 12:03:49 -08001032 boolean useSecureFS = useEncryptedFilesystemForPackage(ps.pkg);
1033 int retCode = mInstaller.remove(ps.name, useSecureFS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001035 Slog.w(TAG, "Couldn't remove app data directory for package: "
Dianne Hackborne6620b22010-01-22 14:46:21 -08001036 + ps.name + ", retcode=" + retCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037 }
1038 } else {
1039 //for emulator
Dianne Hackborne6620b22010-01-22 14:46:21 -08001040 PackageParser.Package pkg = mPackages.get(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 File dataDir = new File(pkg.applicationInfo.dataDir);
1042 dataDir.delete();
1043 }
Dianne Hackborne6620b22010-01-22 14:46:21 -08001044 if (ps.codePath != null) {
1045 if (!ps.codePath.delete()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001046 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001047 }
1048 }
1049 if (ps.resourcePath != null) {
1050 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001051 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
Dianne Hackborne6620b22010-01-22 14:46:21 -08001052 }
1053 }
1054 mSettings.removePackageLP(ps.name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
1056
1057 void readPermissions() {
1058 // Read permissions from .../etc/permission directory.
1059 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions");
1060 if (!libraryDir.exists() || !libraryDir.isDirectory()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001061 Slog.w(TAG, "No directory " + libraryDir + ", skipping");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 return;
1063 }
1064 if (!libraryDir.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001065 Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 return;
1067 }
1068
1069 // Iterate over the files in the directory and scan .xml files
1070 for (File f : libraryDir.listFiles()) {
1071 // We'll read platform.xml last
1072 if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1073 continue;
1074 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001075
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 if (!f.getPath().endsWith(".xml")) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001077 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 continue;
1079 }
1080 if (!f.canRead()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001081 Slog.w(TAG, "Permissions library file " + f + " cannot be read");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 continue;
1083 }
1084
1085 readPermissionsFromXml(f);
1086 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001087
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1089 final File permFile = new File(Environment.getRootDirectory(),
1090 "etc/permissions/platform.xml");
1091 readPermissionsFromXml(permFile);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001092
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001093 StringBuilder sb = new StringBuilder(128);
1094 sb.append("Libs:");
1095 Iterator<String> it = mSharedLibraries.keySet().iterator();
1096 while (it.hasNext()) {
1097 sb.append(' ');
1098 String name = it.next();
1099 sb.append(name);
1100 sb.append(':');
1101 sb.append(mSharedLibraries.get(name));
1102 }
1103 Log.i(TAG, sb.toString());
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001104
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001105 sb.setLength(0);
1106 sb.append("Features:");
1107 it = mAvailableFeatures.keySet().iterator();
1108 while (it.hasNext()) {
1109 sb.append(' ');
1110 sb.append(it.next());
1111 }
1112 Log.i(TAG, sb.toString());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001114
1115 private void readPermissionsFromXml(File permFile) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 FileReader permReader = null;
1117 try {
1118 permReader = new FileReader(permFile);
1119 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001120 Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 return;
1122 }
1123
1124 try {
1125 XmlPullParser parser = Xml.newPullParser();
1126 parser.setInput(permReader);
1127
1128 XmlUtils.beginDocument(parser, "permissions");
1129
1130 while (true) {
1131 XmlUtils.nextElement(parser);
1132 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1133 break;
1134 }
1135
1136 String name = parser.getName();
1137 if ("group".equals(name)) {
1138 String gidStr = parser.getAttributeValue(null, "gid");
1139 if (gidStr != null) {
1140 int gid = Integer.parseInt(gidStr);
1141 mGlobalGids = appendInt(mGlobalGids, gid);
1142 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001143 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 + parser.getPositionDescription());
1145 }
1146
1147 XmlUtils.skipCurrentTag(parser);
1148 continue;
1149 } else if ("permission".equals(name)) {
1150 String perm = parser.getAttributeValue(null, "name");
1151 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001152 Slog.w(TAG, "<permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 + parser.getPositionDescription());
1154 XmlUtils.skipCurrentTag(parser);
1155 continue;
1156 }
1157 perm = perm.intern();
1158 readPermission(parser, perm);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 } else if ("assign-permission".equals(name)) {
1161 String perm = parser.getAttributeValue(null, "name");
1162 if (perm == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001163 Slog.w(TAG, "<assign-permission> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 + parser.getPositionDescription());
1165 XmlUtils.skipCurrentTag(parser);
1166 continue;
1167 }
1168 String uidStr = parser.getAttributeValue(null, "uid");
1169 if (uidStr == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001170 Slog.w(TAG, "<assign-permission> without uid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 + parser.getPositionDescription());
1172 XmlUtils.skipCurrentTag(parser);
1173 continue;
1174 }
1175 int uid = Process.getUidForName(uidStr);
1176 if (uid < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001177 Slog.w(TAG, "<assign-permission> with unknown uid \""
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 + uidStr + "\" at "
1179 + parser.getPositionDescription());
1180 XmlUtils.skipCurrentTag(parser);
1181 continue;
1182 }
1183 perm = perm.intern();
1184 HashSet<String> perms = mSystemPermissions.get(uid);
1185 if (perms == null) {
1186 perms = new HashSet<String>();
1187 mSystemPermissions.put(uid, perms);
1188 }
1189 perms.add(perm);
1190 XmlUtils.skipCurrentTag(parser);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 } else if ("library".equals(name)) {
1193 String lname = parser.getAttributeValue(null, "name");
1194 String lfile = parser.getAttributeValue(null, "file");
1195 if (lname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001196 Slog.w(TAG, "<library> without name at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 + parser.getPositionDescription());
1198 } else if (lfile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001199 Slog.w(TAG, "<library> without file at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 + parser.getPositionDescription());
1201 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001202 //Log.i(TAG, "Got library " + lname + " in " + lfile);
Dianne Hackborn49237342009-08-27 20:08:01 -07001203 mSharedLibraries.put(lname, lfile);
1204 }
1205 XmlUtils.skipCurrentTag(parser);
1206 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001207
Dianne Hackborn49237342009-08-27 20:08:01 -07001208 } else if ("feature".equals(name)) {
1209 String fname = parser.getAttributeValue(null, "name");
1210 if (fname == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001211 Slog.w(TAG, "<feature> without name at "
Dianne Hackborn49237342009-08-27 20:08:01 -07001212 + parser.getPositionDescription());
1213 } else {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07001214 //Log.i(TAG, "Got feature " + fname);
Dianne Hackborn49237342009-08-27 20:08:01 -07001215 FeatureInfo fi = new FeatureInfo();
1216 fi.name = fname;
1217 mAvailableFeatures.put(fname, fi);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 }
1219 XmlUtils.skipCurrentTag(parser);
1220 continue;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 } else {
1223 XmlUtils.skipCurrentTag(parser);
1224 continue;
1225 }
1226
1227 }
1228 } catch (XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001229 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001231 Slog.w(TAG, "Got execption parsing permissions.", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 }
1233 }
1234
1235 void readPermission(XmlPullParser parser, String name)
1236 throws IOException, XmlPullParserException {
1237
1238 name = name.intern();
1239
1240 BasePermission bp = mSettings.mPermissions.get(name);
1241 if (bp == null) {
1242 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1243 mSettings.mPermissions.put(name, bp);
1244 }
1245 int outerDepth = parser.getDepth();
1246 int type;
1247 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1248 && (type != XmlPullParser.END_TAG
1249 || parser.getDepth() > outerDepth)) {
1250 if (type == XmlPullParser.END_TAG
1251 || type == XmlPullParser.TEXT) {
1252 continue;
1253 }
1254
1255 String tagName = parser.getName();
1256 if ("group".equals(tagName)) {
1257 String gidStr = parser.getAttributeValue(null, "gid");
1258 if (gidStr != null) {
1259 int gid = Process.getGidForName(gidStr);
1260 bp.gids = appendInt(bp.gids, gid);
1261 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001262 Slog.w(TAG, "<group> without gid at "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 + parser.getPositionDescription());
1264 }
1265 }
1266 XmlUtils.skipCurrentTag(parser);
1267 }
1268 }
1269
1270 static int[] appendInt(int[] cur, int val) {
1271 if (cur == null) {
1272 return new int[] { val };
1273 }
1274 final int N = cur.length;
1275 for (int i=0; i<N; i++) {
1276 if (cur[i] == val) {
1277 return cur;
1278 }
1279 }
1280 int[] ret = new int[N+1];
1281 System.arraycopy(cur, 0, ret, 0, N);
1282 ret[N] = val;
1283 return ret;
1284 }
1285
1286 static int[] appendInts(int[] cur, int[] add) {
1287 if (add == null) return cur;
1288 if (cur == null) return add;
1289 final int N = add.length;
1290 for (int i=0; i<N; i++) {
1291 cur = appendInt(cur, add[i]);
1292 }
1293 return cur;
1294 }
1295
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001296 static int[] removeInt(int[] cur, int val) {
1297 if (cur == null) {
1298 return null;
1299 }
1300 final int N = cur.length;
1301 for (int i=0; i<N; i++) {
1302 if (cur[i] == val) {
1303 int[] ret = new int[N-1];
1304 if (i > 0) {
1305 System.arraycopy(cur, 0, ret, 0, i);
1306 }
1307 if (i < (N-1)) {
Jeff Brown8c8bb8b2010-04-20 17:21:47 -07001308 System.arraycopy(cur, i + 1, ret, i, N - i - 1);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001309 }
1310 return ret;
1311 }
1312 }
1313 return cur;
1314 }
1315
1316 static int[] removeInts(int[] cur, int[] rem) {
1317 if (rem == null) return cur;
1318 if (cur == null) return cur;
1319 final int N = rem.length;
1320 for (int i=0; i<N; i++) {
1321 cur = removeInt(cur, rem[i]);
1322 }
1323 return cur;
1324 }
1325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 PackageInfo generatePackageInfo(PackageParser.Package p, int flags) {
Suchi Amalapurapub897cff2009-10-14 12:11:48 -07001327 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1328 // The package has been uninstalled but has retained data and resources.
1329 return PackageParser.generatePackageInfo(p, null, flags);
1330 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 final PackageSetting ps = (PackageSetting)p.mExtras;
1332 if (ps == null) {
1333 return null;
1334 }
1335 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1336 return PackageParser.generatePackageInfo(p, gp.gids, flags);
1337 }
1338
1339 public PackageInfo getPackageInfo(String packageName, int flags) {
1340 synchronized (mPackages) {
1341 PackageParser.Package p = mPackages.get(packageName);
1342 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001343 TAG, "getPackageInfo " + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 + ": " + p);
1345 if (p != null) {
1346 return generatePackageInfo(p, flags);
1347 }
1348 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1349 return generatePackageInfoFromSettingsLP(packageName, flags);
1350 }
1351 }
1352 return null;
1353 }
1354
Dianne Hackborn47096932010-02-11 15:57:09 -08001355 public String[] currentToCanonicalPackageNames(String[] names) {
1356 String[] out = new String[names.length];
1357 synchronized (mPackages) {
1358 for (int i=names.length-1; i>=0; i--) {
1359 PackageSetting ps = mSettings.mPackages.get(names[i]);
1360 out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1361 }
1362 }
1363 return out;
1364 }
1365
1366 public String[] canonicalToCurrentPackageNames(String[] names) {
1367 String[] out = new String[names.length];
1368 synchronized (mPackages) {
1369 for (int i=names.length-1; i>=0; i--) {
1370 String cur = mSettings.mRenamedPackages.get(names[i]);
1371 out[i] = cur != null ? cur : names[i];
1372 }
1373 }
1374 return out;
1375 }
1376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 public int getPackageUid(String packageName) {
1378 synchronized (mPackages) {
1379 PackageParser.Package p = mPackages.get(packageName);
1380 if(p != null) {
1381 return p.applicationInfo.uid;
1382 }
1383 PackageSetting ps = mSettings.mPackages.get(packageName);
1384 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1385 return -1;
1386 }
1387 p = ps.pkg;
1388 return p != null ? p.applicationInfo.uid : -1;
1389 }
1390 }
1391
1392 public int[] getPackageGids(String packageName) {
1393 synchronized (mPackages) {
1394 PackageParser.Package p = mPackages.get(packageName);
1395 if (Config.LOGV) Log.v(
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001396 TAG, "getPackageGids" + packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 + ": " + p);
1398 if (p != null) {
1399 final PackageSetting ps = (PackageSetting)p.mExtras;
1400 final SharedUserSetting suid = ps.sharedUser;
1401 return suid != null ? suid.gids : ps.gids;
1402 }
1403 }
1404 // stupid thing to indicate an error.
1405 return new int[0];
1406 }
1407
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001408 static final PermissionInfo generatePermissionInfo(
1409 BasePermission bp, int flags) {
1410 if (bp.perm != null) {
1411 return PackageParser.generatePermissionInfo(bp.perm, flags);
1412 }
1413 PermissionInfo pi = new PermissionInfo();
1414 pi.name = bp.name;
1415 pi.packageName = bp.sourcePackage;
1416 pi.nonLocalizedLabel = bp.name;
1417 pi.protectionLevel = bp.protectionLevel;
1418 return pi;
1419 }
1420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 public PermissionInfo getPermissionInfo(String name, int flags) {
1422 synchronized (mPackages) {
1423 final BasePermission p = mSettings.mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001424 if (p != null) {
1425 return generatePermissionInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427 return null;
1428 }
1429 }
1430
1431 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1432 synchronized (mPackages) {
1433 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1434 for (BasePermission p : mSettings.mPermissions.values()) {
1435 if (group == null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001436 if (p.perm == null || p.perm.info.group == null) {
1437 out.add(generatePermissionInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07001440 if (p.perm != null && group.equals(p.perm.info.group)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1442 }
1443 }
1444 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 if (out.size() > 0) {
1447 return out;
1448 }
1449 return mPermissionGroups.containsKey(group) ? out : null;
1450 }
1451 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1454 synchronized (mPackages) {
1455 return PackageParser.generatePermissionGroupInfo(
1456 mPermissionGroups.get(name), flags);
1457 }
1458 }
1459
1460 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
1461 synchronized (mPackages) {
1462 final int N = mPermissionGroups.size();
1463 ArrayList<PermissionGroupInfo> out
1464 = new ArrayList<PermissionGroupInfo>(N);
1465 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
1466 out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
1467 }
1468 return out;
1469 }
1470 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 private ApplicationInfo generateApplicationInfoFromSettingsLP(String packageName, int flags) {
1473 PackageSetting ps = mSettings.mPackages.get(packageName);
1474 if(ps != null) {
1475 if(ps.pkg == null) {
1476 PackageInfo pInfo = generatePackageInfoFromSettingsLP(packageName, flags);
1477 if(pInfo != null) {
1478 return pInfo.applicationInfo;
1479 }
1480 return null;
1481 }
1482 return PackageParser.generateApplicationInfo(ps.pkg, flags);
1483 }
1484 return null;
1485 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 private PackageInfo generatePackageInfoFromSettingsLP(String packageName, int flags) {
1488 PackageSetting ps = mSettings.mPackages.get(packageName);
1489 if(ps != null) {
1490 if(ps.pkg == null) {
1491 ps.pkg = new PackageParser.Package(packageName);
1492 ps.pkg.applicationInfo.packageName = packageName;
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08001493 ps.pkg.applicationInfo.flags = ps.pkgFlags;
1494 ps.pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
1495 ps.pkg.applicationInfo.sourceDir = ps.codePathString;
1496 ps.pkg.applicationInfo.dataDir = getDataPathForPackage(ps.pkg).getPath();
Kenny Root85387d72010-08-26 10:13:11 -07001497 ps.pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07001498 ps.pkg.mSetEnabled = ps.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 }
1500 return generatePackageInfo(ps.pkg, flags);
1501 }
1502 return null;
1503 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001504
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001505 public ApplicationInfo getApplicationInfo(String packageName, int flags) {
1506 synchronized (mPackages) {
1507 PackageParser.Package p = mPackages.get(packageName);
1508 if (Config.LOGV) Log.v(
1509 TAG, "getApplicationInfo " + packageName
1510 + ": " + p);
1511 if (p != null) {
1512 // Note: isEnabledLP() does not apply here - always return info
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07001513 return PackageParser.generateApplicationInfo(p, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001514 }
1515 if ("android".equals(packageName)||"system".equals(packageName)) {
1516 return mAndroidApplication;
1517 }
1518 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1519 return generateApplicationInfoFromSettingsLP(packageName, flags);
1520 }
1521 }
1522 return null;
1523 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001524
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
1527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.CLEAR_APP_CACHE, null);
1529 // Queue up an async operation since clearing cache may take a little while.
1530 mHandler.post(new Runnable() {
1531 public void run() {
1532 mHandler.removeCallbacks(this);
1533 int retCode = -1;
1534 if (mInstaller != null) {
1535 retCode = mInstaller.freeCache(freeStorageSize);
1536 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001537 Slog.w(TAG, "Couldn't clear application caches");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 } //end if mInstaller
1540 if (observer != null) {
1541 try {
1542 observer.onRemoveCompleted(null, (retCode >= 0));
1543 } catch (RemoteException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001544 Slog.w(TAG, "RemoveException when invoking call back");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546 }
1547 }
1548 });
1549 }
1550
Suchi Amalapurapubc806f62009-06-17 15:18:19 -07001551 public void freeStorage(final long freeStorageSize, final IntentSender pi) {
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001552 mContext.enforceCallingOrSelfPermission(
1553 android.Manifest.permission.CLEAR_APP_CACHE, null);
1554 // Queue up an async operation since clearing cache may take a little while.
1555 mHandler.post(new Runnable() {
1556 public void run() {
1557 mHandler.removeCallbacks(this);
1558 int retCode = -1;
1559 if (mInstaller != null) {
1560 retCode = mInstaller.freeCache(freeStorageSize);
1561 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001562 Slog.w(TAG, "Couldn't clear application caches");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001563 }
1564 }
1565 if(pi != null) {
1566 try {
1567 // Callback via pending intent
1568 int code = (retCode >= 0) ? 1 : 0;
1569 pi.sendIntent(null, code, null,
1570 null, null);
1571 } catch (SendIntentException e1) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001572 Slog.i(TAG, "Failed to send pending intent");
Suchi Amalapurapu1ccac752009-06-12 10:09:58 -07001573 }
1574 }
1575 }
1576 });
1577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 public ActivityInfo getActivityInfo(ComponentName component, int flags) {
1580 synchronized (mPackages) {
1581 PackageParser.Activity a = mActivities.mActivities.get(component);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07001582
1583 if (Config.LOGV) Log.v(TAG, "getActivityInfo " + component + ": " + a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
Mitsuru Oshima64f59342009-06-21 00:03:11 -07001585 return PackageParser.generateActivityInfo(a, flags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 }
1587 if (mResolveComponentName.equals(component)) {
1588 return mResolveActivity;
1589 }
1590 }
1591 return null;
1592 }
1593
1594 public ActivityInfo getReceiverInfo(ComponentName component, int flags) {
1595 synchronized (mPackages) {
1596 PackageParser.Activity a = mReceivers.mActivities.get(component);
1597 if (Config.LOGV) Log.v(
1598 TAG, "getReceiverInfo " + component + ": " + a);
1599 if (a != null && mSettings.isEnabledLP(a.info, flags)) {
1600 return PackageParser.generateActivityInfo(a, flags);
1601 }
1602 }
1603 return null;
1604 }
1605
1606 public ServiceInfo getServiceInfo(ComponentName component, int flags) {
1607 synchronized (mPackages) {
1608 PackageParser.Service s = mServices.mServices.get(component);
1609 if (Config.LOGV) Log.v(
1610 TAG, "getServiceInfo " + component + ": " + s);
1611 if (s != null && mSettings.isEnabledLP(s.info, flags)) {
1612 return PackageParser.generateServiceInfo(s, flags);
1613 }
1614 }
1615 return null;
1616 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001617
Dianne Hackborn361199b2010-08-30 17:42:07 -07001618 public ProviderInfo getProviderInfo(ComponentName component, int flags) {
1619 synchronized (mPackages) {
1620 PackageParser.Provider p = mProvidersByComponent.get(component);
1621 if (Config.LOGV) Log.v(
1622 TAG, "getProviderInfo " + component + ": " + p);
1623 if (p != null && mSettings.isEnabledLP(p.info, flags)) {
1624 return PackageParser.generateProviderInfo(p, flags);
1625 }
1626 }
1627 return null;
1628 }
1629
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001630 public String[] getSystemSharedLibraryNames() {
1631 Set<String> libSet;
1632 synchronized (mPackages) {
1633 libSet = mSharedLibraries.keySet();
Dianne Hackborn49237342009-08-27 20:08:01 -07001634 int size = libSet.size();
1635 if (size > 0) {
1636 String[] libs = new String[size];
1637 libSet.toArray(libs);
1638 return libs;
1639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
Dianne Hackborn49237342009-08-27 20:08:01 -07001641 return null;
1642 }
1643
1644 public FeatureInfo[] getSystemAvailableFeatures() {
1645 Collection<FeatureInfo> featSet;
1646 synchronized (mPackages) {
1647 featSet = mAvailableFeatures.values();
1648 int size = featSet.size();
1649 if (size > 0) {
1650 FeatureInfo[] features = new FeatureInfo[size+1];
1651 featSet.toArray(features);
1652 FeatureInfo fi = new FeatureInfo();
1653 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
1654 FeatureInfo.GL_ES_VERSION_UNDEFINED);
1655 features[size] = fi;
1656 return features;
1657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
1659 return null;
1660 }
1661
Dianne Hackborn039c68e2009-09-26 16:39:23 -07001662 public boolean hasSystemFeature(String name) {
1663 synchronized (mPackages) {
1664 return mAvailableFeatures.containsKey(name);
1665 }
1666 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001667
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001668 public int checkPermission(String permName, String pkgName) {
1669 synchronized (mPackages) {
1670 PackageParser.Package p = mPackages.get(pkgName);
1671 if (p != null && p.mExtras != null) {
1672 PackageSetting ps = (PackageSetting)p.mExtras;
1673 if (ps.sharedUser != null) {
1674 if (ps.sharedUser.grantedPermissions.contains(permName)) {
1675 return PackageManager.PERMISSION_GRANTED;
1676 }
1677 } else if (ps.grantedPermissions.contains(permName)) {
1678 return PackageManager.PERMISSION_GRANTED;
1679 }
1680 }
1681 }
1682 return PackageManager.PERMISSION_DENIED;
1683 }
1684
1685 public int checkUidPermission(String permName, int uid) {
1686 synchronized (mPackages) {
1687 Object obj = mSettings.getUserIdLP(uid);
1688 if (obj != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08001689 GrantedPermissions gp = (GrantedPermissions)obj;
1690 if (gp.grantedPermissions.contains(permName)) {
1691 return PackageManager.PERMISSION_GRANTED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 }
1693 } else {
1694 HashSet<String> perms = mSystemPermissions.get(uid);
1695 if (perms != null && perms.contains(permName)) {
1696 return PackageManager.PERMISSION_GRANTED;
1697 }
1698 }
1699 }
1700 return PackageManager.PERMISSION_DENIED;
1701 }
1702
1703 private BasePermission findPermissionTreeLP(String permName) {
1704 for(BasePermission bp : mSettings.mPermissionTrees.values()) {
1705 if (permName.startsWith(bp.name) &&
1706 permName.length() > bp.name.length() &&
1707 permName.charAt(bp.name.length()) == '.') {
1708 return bp;
1709 }
1710 }
1711 return null;
1712 }
1713
1714 private BasePermission checkPermissionTreeLP(String permName) {
1715 if (permName != null) {
1716 BasePermission bp = findPermissionTreeLP(permName);
1717 if (bp != null) {
1718 if (bp.uid == Binder.getCallingUid()) {
1719 return bp;
1720 }
1721 throw new SecurityException("Calling uid "
1722 + Binder.getCallingUid()
1723 + " is not allowed to add to permission tree "
1724 + bp.name + " owned by uid " + bp.uid);
1725 }
1726 }
1727 throw new SecurityException("No permission tree found for " + permName);
1728 }
1729
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001730 static boolean compareStrings(CharSequence s1, CharSequence s2) {
1731 if (s1 == null) {
1732 return s2 == null;
1733 }
1734 if (s2 == null) {
1735 return false;
1736 }
1737 if (s1.getClass() != s2.getClass()) {
1738 return false;
1739 }
1740 return s1.equals(s2);
1741 }
1742
1743 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
1744 if (pi1.icon != pi2.icon) return false;
Adam Powell81cd2e92010-04-21 16:35:18 -07001745 if (pi1.logo != pi2.logo) return false;
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001746 if (pi1.protectionLevel != pi2.protectionLevel) return false;
1747 if (!compareStrings(pi1.name, pi2.name)) return false;
1748 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
1749 // We'll take care of setting this one.
1750 if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
1751 // These are not currently stored in settings.
1752 //if (!compareStrings(pi1.group, pi2.group)) return false;
1753 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
1754 //if (pi1.labelRes != pi2.labelRes) return false;
1755 //if (pi1.descriptionRes != pi2.descriptionRes) return false;
1756 return true;
1757 }
1758
1759 boolean addPermissionLocked(PermissionInfo info, boolean async) {
1760 if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
1761 throw new SecurityException("Label must be specified in permission");
1762 }
1763 BasePermission tree = checkPermissionTreeLP(info.name);
1764 BasePermission bp = mSettings.mPermissions.get(info.name);
1765 boolean added = bp == null;
1766 boolean changed = true;
1767 if (added) {
1768 bp = new BasePermission(info.name, tree.sourcePackage,
1769 BasePermission.TYPE_DYNAMIC);
1770 } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
1771 throw new SecurityException(
1772 "Not allowed to modify non-dynamic permission "
1773 + info.name);
1774 } else {
1775 if (bp.protectionLevel == info.protectionLevel
1776 && bp.perm.owner.equals(tree.perm.owner)
1777 && bp.uid == tree.uid
1778 && comparePermissionInfos(bp.perm.info, info)) {
1779 changed = false;
1780 }
1781 }
1782 bp.protectionLevel = info.protectionLevel;
1783 bp.perm = new PackageParser.Permission(tree.perm.owner,
1784 new PermissionInfo(info));
1785 bp.perm.info.packageName = tree.perm.info.packageName;
1786 bp.uid = tree.uid;
1787 if (added) {
1788 mSettings.mPermissions.put(info.name, bp);
1789 }
1790 if (changed) {
1791 if (!async) {
1792 mSettings.writeLP();
1793 } else {
1794 scheduleWriteSettingsLocked();
1795 }
1796 }
1797 return added;
1798 }
1799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 public boolean addPermission(PermissionInfo info) {
1801 synchronized (mPackages) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07001802 return addPermissionLocked(info, false);
1803 }
1804 }
1805
1806 public boolean addPermissionAsync(PermissionInfo info) {
1807 synchronized (mPackages) {
1808 return addPermissionLocked(info, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
1811
1812 public void removePermission(String name) {
1813 synchronized (mPackages) {
1814 checkPermissionTreeLP(name);
1815 BasePermission bp = mSettings.mPermissions.get(name);
1816 if (bp != null) {
1817 if (bp.type != BasePermission.TYPE_DYNAMIC) {
1818 throw new SecurityException(
1819 "Not allowed to modify non-dynamic permission "
1820 + name);
1821 }
1822 mSettings.mPermissions.remove(name);
1823 mSettings.writeLP();
1824 }
1825 }
1826 }
1827
Dianne Hackborn854060af2009-07-09 18:14:31 -07001828 public boolean isProtectedBroadcast(String actionName) {
1829 synchronized (mPackages) {
1830 return mProtectedBroadcasts.contains(actionName);
1831 }
1832 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 public int checkSignatures(String pkg1, String pkg2) {
1835 synchronized (mPackages) {
1836 PackageParser.Package p1 = mPackages.get(pkg1);
1837 PackageParser.Package p2 = mPackages.get(pkg2);
1838 if (p1 == null || p1.mExtras == null
1839 || p2 == null || p2.mExtras == null) {
1840 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1841 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001842 return checkSignaturesLP(p1.mSignatures, p2.mSignatures);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 }
1844 }
1845
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001846 public int checkUidSignatures(int uid1, int uid2) {
1847 synchronized (mPackages) {
1848 Signature[] s1;
1849 Signature[] s2;
1850 Object obj = mSettings.getUserIdLP(uid1);
1851 if (obj != null) {
1852 if (obj instanceof SharedUserSetting) {
1853 s1 = ((SharedUserSetting)obj).signatures.mSignatures;
1854 } else if (obj instanceof PackageSetting) {
1855 s1 = ((PackageSetting)obj).signatures.mSignatures;
1856 } else {
1857 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1858 }
1859 } else {
1860 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1861 }
1862 obj = mSettings.getUserIdLP(uid2);
1863 if (obj != null) {
1864 if (obj instanceof SharedUserSetting) {
1865 s2 = ((SharedUserSetting)obj).signatures.mSignatures;
1866 } else if (obj instanceof PackageSetting) {
1867 s2 = ((PackageSetting)obj).signatures.mSignatures;
1868 } else {
1869 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1870 }
1871 } else {
1872 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
1873 }
1874 return checkSignaturesLP(s1, s2);
1875 }
1876 }
1877
1878 int checkSignaturesLP(Signature[] s1, Signature[] s2) {
1879 if (s1 == null) {
1880 return s2 == null
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 ? PackageManager.SIGNATURE_NEITHER_SIGNED
1882 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
1883 }
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07001884 if (s2 == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
1886 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001887 HashSet<Signature> set1 = new HashSet<Signature>();
1888 for (Signature sig : s1) {
1889 set1.add(sig);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07001891 HashSet<Signature> set2 = new HashSet<Signature>();
1892 for (Signature sig : s2) {
1893 set2.add(sig);
1894 }
1895 // Make sure s2 contains all signatures in s1.
1896 if (set1.equals(set2)) {
1897 return PackageManager.SIGNATURE_MATCH;
1898 }
1899 return PackageManager.SIGNATURE_NO_MATCH;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
1901
1902 public String[] getPackagesForUid(int uid) {
1903 synchronized (mPackages) {
1904 Object obj = mSettings.getUserIdLP(uid);
1905 if (obj instanceof SharedUserSetting) {
1906 SharedUserSetting sus = (SharedUserSetting)obj;
1907 final int N = sus.packages.size();
1908 String[] res = new String[N];
1909 Iterator<PackageSetting> it = sus.packages.iterator();
1910 int i=0;
1911 while (it.hasNext()) {
1912 res[i++] = it.next().name;
1913 }
1914 return res;
1915 } else if (obj instanceof PackageSetting) {
1916 PackageSetting ps = (PackageSetting)obj;
1917 return new String[] { ps.name };
1918 }
1919 }
1920 return null;
1921 }
1922
1923 public String getNameForUid(int uid) {
1924 synchronized (mPackages) {
1925 Object obj = mSettings.getUserIdLP(uid);
1926 if (obj instanceof SharedUserSetting) {
1927 SharedUserSetting sus = (SharedUserSetting)obj;
1928 return sus.name + ":" + sus.userId;
1929 } else if (obj instanceof PackageSetting) {
1930 PackageSetting ps = (PackageSetting)obj;
1931 return ps.name;
1932 }
1933 }
1934 return null;
1935 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 public int getUidForSharedUser(String sharedUserName) {
1938 if(sharedUserName == null) {
1939 return -1;
1940 }
1941 synchronized (mPackages) {
1942 SharedUserSetting suid = mSettings.getSharedUserLP(sharedUserName, 0, false);
1943 if(suid == null) {
1944 return -1;
1945 }
1946 return suid.userId;
1947 }
1948 }
1949
1950 public ResolveInfo resolveIntent(Intent intent, String resolvedType,
1951 int flags) {
1952 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags);
Mihai Predaeae850c2009-05-13 10:13:48 +02001953 return chooseBestActivity(intent, resolvedType, flags, query);
1954 }
1955
Mihai Predaeae850c2009-05-13 10:13:48 +02001956 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
1957 int flags, List<ResolveInfo> query) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 if (query != null) {
1959 final int N = query.size();
1960 if (N == 1) {
1961 return query.get(0);
1962 } else if (N > 1) {
1963 // If there is more than one activity with the same priority,
1964 // then let the user decide between them.
1965 ResolveInfo r0 = query.get(0);
1966 ResolveInfo r1 = query.get(1);
1967 if (false) {
1968 System.out.println(r0.activityInfo.name +
1969 "=" + r0.priority + " vs " +
1970 r1.activityInfo.name +
1971 "=" + r1.priority);
1972 }
1973 // If the first activity has a higher priority, or a different
1974 // default, then it is always desireable to pick it.
1975 if (r0.priority != r1.priority
1976 || r0.preferredOrder != r1.preferredOrder
1977 || r0.isDefault != r1.isDefault) {
1978 return query.get(0);
1979 }
1980 // If we have saved a preference for a preferred activity for
1981 // this Intent, use that.
1982 ResolveInfo ri = findPreferredActivity(intent, resolvedType,
1983 flags, query, r0.priority);
1984 if (ri != null) {
1985 return ri;
1986 }
1987 return mResolveInfo;
1988 }
1989 }
1990 return null;
1991 }
1992
1993 ResolveInfo findPreferredActivity(Intent intent, String resolvedType,
1994 int flags, List<ResolveInfo> query, int priority) {
1995 synchronized (mPackages) {
1996 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
1997 List<PreferredActivity> prefs =
Mihai Preda074edef2009-05-18 17:13:31 +02001998 mSettings.mPreferredActivities.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
2000 if (prefs != null && prefs.size() > 0) {
2001 // First figure out how good the original match set is.
2002 // We will only allow preferred activities that came
2003 // from the same match quality.
2004 int match = 0;
2005 final int N = query.size();
2006 if (DEBUG_PREFERRED) Log.v(TAG, "Figuring out best match...");
2007 for (int j=0; j<N; j++) {
2008 ResolveInfo ri = query.get(j);
2009 if (DEBUG_PREFERRED) Log.v(TAG, "Match for " + ri.activityInfo
2010 + ": 0x" + Integer.toHexString(match));
2011 if (ri.match > match) match = ri.match;
2012 }
2013 if (DEBUG_PREFERRED) Log.v(TAG, "Best match: 0x"
2014 + Integer.toHexString(match));
2015 match &= IntentFilter.MATCH_CATEGORY_MASK;
2016 final int M = prefs.size();
2017 for (int i=0; i<M; i++) {
2018 PreferredActivity pa = prefs.get(i);
2019 if (pa.mMatch != match) {
2020 continue;
2021 }
2022 ActivityInfo ai = getActivityInfo(pa.mActivity, flags);
2023 if (DEBUG_PREFERRED) {
2024 Log.v(TAG, "Got preferred activity:");
Marco Nelissend85621c2010-09-03 09:25:33 -07002025 if (ai != null) {
2026 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
2027 } else {
2028 Log.v(TAG, " null");
2029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002030 }
2031 if (ai != null) {
2032 for (int j=0; j<N; j++) {
2033 ResolveInfo ri = query.get(j);
2034 if (!ri.activityInfo.applicationInfo.packageName
2035 .equals(ai.applicationInfo.packageName)) {
2036 continue;
2037 }
2038 if (!ri.activityInfo.name.equals(ai.name)) {
2039 continue;
2040 }
2041
2042 // Okay we found a previously set preferred app.
2043 // If the result set is different from when this
2044 // was created, we need to clear it and re-ask the
2045 // user their preference.
2046 if (!pa.sameSet(query, priority)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002047 Slog.i(TAG, "Result set changed, dropping preferred activity for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002048 + intent + " type " + resolvedType);
2049 mSettings.mPreferredActivities.removeFilter(pa);
2050 return null;
2051 }
2052
2053 // Yay!
2054 return ri;
2055 }
2056 }
2057 }
2058 }
2059 }
2060 return null;
2061 }
2062
2063 public List<ResolveInfo> queryIntentActivities(Intent intent,
2064 String resolvedType, int flags) {
2065 ComponentName comp = intent.getComponent();
2066 if (comp != null) {
2067 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2068 ActivityInfo ai = getActivityInfo(comp, flags);
2069 if (ai != null) {
2070 ResolveInfo ri = new ResolveInfo();
2071 ri.activityInfo = ai;
2072 list.add(ri);
2073 }
2074 return list;
2075 }
2076
2077 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002078 String pkgName = intent.getPackage();
2079 if (pkgName == null) {
2080 return (List<ResolveInfo>)mActivities.queryIntent(intent,
2081 resolvedType, flags);
2082 }
2083 PackageParser.Package pkg = mPackages.get(pkgName);
2084 if (pkg != null) {
2085 return (List<ResolveInfo>) mActivities.queryIntentForPackage(intent,
2086 resolvedType, flags, pkg.activities);
2087 }
2088 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 }
2090 }
2091
2092 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
2093 Intent[] specifics, String[] specificTypes, Intent intent,
2094 String resolvedType, int flags) {
2095 final String resultsAction = intent.getAction();
2096
2097 List<ResolveInfo> results = queryIntentActivities(
2098 intent, resolvedType, flags|PackageManager.GET_RESOLVED_FILTER);
2099 if (Config.LOGV) Log.v(TAG, "Query " + intent + ": " + results);
2100
2101 int specificsPos = 0;
2102 int N;
2103
2104 // todo: note that the algorithm used here is O(N^2). This
2105 // isn't a problem in our current environment, but if we start running
2106 // into situations where we have more than 5 or 10 matches then this
2107 // should probably be changed to something smarter...
2108
2109 // First we go through and resolve each of the specific items
2110 // that were supplied, taking care of removing any corresponding
2111 // duplicate items in the generic resolve list.
2112 if (specifics != null) {
2113 for (int i=0; i<specifics.length; i++) {
2114 final Intent sintent = specifics[i];
2115 if (sintent == null) {
2116 continue;
2117 }
2118
2119 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + sintent);
2120 String action = sintent.getAction();
2121 if (resultsAction != null && resultsAction.equals(action)) {
2122 // If this action was explicitly requested, then don't
2123 // remove things that have it.
2124 action = null;
2125 }
2126 ComponentName comp = sintent.getComponent();
2127 ResolveInfo ri = null;
2128 ActivityInfo ai = null;
2129 if (comp == null) {
2130 ri = resolveIntent(
2131 sintent,
2132 specificTypes != null ? specificTypes[i] : null,
2133 flags);
2134 if (ri == null) {
2135 continue;
2136 }
2137 if (ri == mResolveInfo) {
2138 // ACK! Must do something better with this.
2139 }
2140 ai = ri.activityInfo;
2141 comp = new ComponentName(ai.applicationInfo.packageName,
2142 ai.name);
2143 } else {
2144 ai = getActivityInfo(comp, flags);
2145 if (ai == null) {
2146 continue;
2147 }
2148 }
2149
2150 // Look for any generic query activities that are duplicates
2151 // of this specific one, and remove them from the results.
2152 if (Config.LOGV) Log.v(TAG, "Specific #" + i + ": " + ai);
2153 N = results.size();
2154 int j;
2155 for (j=specificsPos; j<N; j++) {
2156 ResolveInfo sri = results.get(j);
2157 if ((sri.activityInfo.name.equals(comp.getClassName())
2158 && sri.activityInfo.applicationInfo.packageName.equals(
2159 comp.getPackageName()))
2160 || (action != null && sri.filter.matchAction(action))) {
2161 results.remove(j);
2162 if (Config.LOGV) Log.v(
2163 TAG, "Removing duplicate item from " + j
2164 + " due to specific " + specificsPos);
2165 if (ri == null) {
2166 ri = sri;
2167 }
2168 j--;
2169 N--;
2170 }
2171 }
2172
2173 // Add this specific item to its proper place.
2174 if (ri == null) {
2175 ri = new ResolveInfo();
2176 ri.activityInfo = ai;
2177 }
2178 results.add(specificsPos, ri);
2179 ri.specificIndex = i;
2180 specificsPos++;
2181 }
2182 }
2183
2184 // Now we go through the remaining generic results and remove any
2185 // duplicate actions that are found here.
2186 N = results.size();
2187 for (int i=specificsPos; i<N-1; i++) {
2188 final ResolveInfo rii = results.get(i);
2189 if (rii.filter == null) {
2190 continue;
2191 }
2192
2193 // Iterate over all of the actions of this result's intent
2194 // filter... typically this should be just one.
2195 final Iterator<String> it = rii.filter.actionsIterator();
2196 if (it == null) {
2197 continue;
2198 }
2199 while (it.hasNext()) {
2200 final String action = it.next();
2201 if (resultsAction != null && resultsAction.equals(action)) {
2202 // If this action was explicitly requested, then don't
2203 // remove things that have it.
2204 continue;
2205 }
2206 for (int j=i+1; j<N; j++) {
2207 final ResolveInfo rij = results.get(j);
2208 if (rij.filter != null && rij.filter.hasAction(action)) {
2209 results.remove(j);
2210 if (Config.LOGV) Log.v(
2211 TAG, "Removing duplicate item from " + j
2212 + " due to action " + action + " at " + i);
2213 j--;
2214 N--;
2215 }
2216 }
2217 }
2218
2219 // If the caller didn't request filter information, drop it now
2220 // so we don't have to marshall/unmarshall it.
2221 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2222 rii.filter = null;
2223 }
2224 }
2225
2226 // Filter out the caller activity if so requested.
2227 if (caller != null) {
2228 N = results.size();
2229 for (int i=0; i<N; i++) {
2230 ActivityInfo ainfo = results.get(i).activityInfo;
2231 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
2232 && caller.getClassName().equals(ainfo.name)) {
2233 results.remove(i);
2234 break;
2235 }
2236 }
2237 }
2238
2239 // If the caller didn't request filter information,
2240 // drop them now so we don't have to
2241 // marshall/unmarshall it.
2242 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
2243 N = results.size();
2244 for (int i=0; i<N; i++) {
2245 results.get(i).filter = null;
2246 }
2247 }
2248
2249 if (Config.LOGV) Log.v(TAG, "Result: " + results);
2250 return results;
2251 }
2252
2253 public List<ResolveInfo> queryIntentReceivers(Intent intent,
2254 String resolvedType, int flags) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002255 ComponentName comp = intent.getComponent();
2256 if (comp != null) {
2257 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2258 ActivityInfo ai = getReceiverInfo(comp, flags);
2259 if (ai != null) {
2260 ResolveInfo ri = new ResolveInfo();
2261 ri.activityInfo = ai;
2262 list.add(ri);
2263 }
2264 return list;
2265 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002268 String pkgName = intent.getPackage();
2269 if (pkgName == null) {
2270 return (List<ResolveInfo>)mReceivers.queryIntent(intent,
2271 resolvedType, flags);
2272 }
2273 PackageParser.Package pkg = mPackages.get(pkgName);
2274 if (pkg != null) {
2275 return (List<ResolveInfo>) mReceivers.queryIntentForPackage(intent,
2276 resolvedType, flags, pkg.receivers);
2277 }
2278 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 }
2280 }
2281
2282 public ResolveInfo resolveService(Intent intent, String resolvedType,
2283 int flags) {
2284 List<ResolveInfo> query = queryIntentServices(intent, resolvedType,
2285 flags);
2286 if (query != null) {
2287 if (query.size() >= 1) {
2288 // If there is more than one service with the same priority,
2289 // just arbitrarily pick the first one.
2290 return query.get(0);
2291 }
2292 }
2293 return null;
2294 }
2295
2296 public List<ResolveInfo> queryIntentServices(Intent intent,
2297 String resolvedType, int flags) {
2298 ComponentName comp = intent.getComponent();
2299 if (comp != null) {
2300 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
2301 ServiceInfo si = getServiceInfo(comp, flags);
2302 if (si != null) {
2303 ResolveInfo ri = new ResolveInfo();
2304 ri.serviceInfo = si;
2305 list.add(ri);
2306 }
2307 return list;
2308 }
2309
2310 synchronized (mPackages) {
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07002311 String pkgName = intent.getPackage();
2312 if (pkgName == null) {
2313 return (List<ResolveInfo>)mServices.queryIntent(intent,
2314 resolvedType, flags);
2315 }
2316 PackageParser.Package pkg = mPackages.get(pkgName);
2317 if (pkg != null) {
2318 return (List<ResolveInfo>)mServices.queryIntentForPackage(intent,
2319 resolvedType, flags, pkg.services);
2320 }
2321 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 }
2323 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002324
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 public List<PackageInfo> getInstalledPackages(int flags) {
2326 ArrayList<PackageInfo> finalList = new ArrayList<PackageInfo>();
2327
2328 synchronized (mPackages) {
2329 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2330 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2331 while (i.hasNext()) {
2332 final PackageSetting ps = i.next();
2333 PackageInfo psPkg = generatePackageInfoFromSettingsLP(ps.name, flags);
2334 if(psPkg != null) {
2335 finalList.add(psPkg);
2336 }
2337 }
2338 }
2339 else {
2340 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2341 while (i.hasNext()) {
2342 final PackageParser.Package p = i.next();
2343 if (p.applicationInfo != null) {
2344 PackageInfo pi = generatePackageInfo(p, flags);
2345 if(pi != null) {
2346 finalList.add(pi);
2347 }
2348 }
2349 }
2350 }
2351 }
2352 return finalList;
2353 }
2354
2355 public List<ApplicationInfo> getInstalledApplications(int flags) {
2356 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2357 synchronized(mPackages) {
2358 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2359 Iterator<PackageSetting> i = mSettings.mPackages.values().iterator();
2360 while (i.hasNext()) {
2361 final PackageSetting ps = i.next();
2362 ApplicationInfo ai = generateApplicationInfoFromSettingsLP(ps.name, flags);
2363 if(ai != null) {
2364 finalList.add(ai);
2365 }
2366 }
2367 }
2368 else {
2369 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2370 while (i.hasNext()) {
2371 final PackageParser.Package p = i.next();
2372 if (p.applicationInfo != null) {
2373 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags);
2374 if(ai != null) {
2375 finalList.add(ai);
2376 }
2377 }
2378 }
2379 }
2380 }
2381 return finalList;
2382 }
2383
2384 public List<ApplicationInfo> getPersistentApplications(int flags) {
2385 ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
2386
2387 synchronized (mPackages) {
2388 Iterator<PackageParser.Package> i = mPackages.values().iterator();
2389 while (i.hasNext()) {
2390 PackageParser.Package p = i.next();
2391 if (p.applicationInfo != null
2392 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
Kenny Root85387d72010-08-26 10:13:11 -07002393 && (!mSafeMode || isSystemApp(p))) {
Jey2eebf5c2009-11-18 18:37:31 -08002394 finalList.add(PackageParser.generateApplicationInfo(p, flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 }
2396 }
2397 }
2398
2399 return finalList;
2400 }
2401
2402 public ProviderInfo resolveContentProvider(String name, int flags) {
2403 synchronized (mPackages) {
2404 final PackageParser.Provider provider = mProviders.get(name);
2405 return provider != null
2406 && mSettings.isEnabledLP(provider.info, flags)
2407 && (!mSafeMode || (provider.info.applicationInfo.flags
2408 &ApplicationInfo.FLAG_SYSTEM) != 0)
2409 ? PackageParser.generateProviderInfo(provider, flags)
2410 : null;
2411 }
2412 }
2413
Fred Quintana718d8a22009-04-29 17:53:20 -07002414 /**
2415 * @deprecated
2416 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 public void querySyncProviders(List outNames, List outInfo) {
2418 synchronized (mPackages) {
2419 Iterator<Map.Entry<String, PackageParser.Provider>> i
2420 = mProviders.entrySet().iterator();
2421
2422 while (i.hasNext()) {
2423 Map.Entry<String, PackageParser.Provider> entry = i.next();
2424 PackageParser.Provider p = entry.getValue();
2425
2426 if (p.syncable
2427 && (!mSafeMode || (p.info.applicationInfo.flags
2428 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2429 outNames.add(entry.getKey());
2430 outInfo.add(PackageParser.generateProviderInfo(p, 0));
2431 }
2432 }
2433 }
2434 }
2435
2436 public List<ProviderInfo> queryContentProviders(String processName,
2437 int uid, int flags) {
2438 ArrayList<ProviderInfo> finalList = null;
2439
2440 synchronized (mPackages) {
2441 Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator();
2442 while (i.hasNext()) {
2443 PackageParser.Provider p = i.next();
2444 if (p.info.authority != null
2445 && (processName == null ||
2446 (p.info.processName.equals(processName)
2447 && p.info.applicationInfo.uid == uid))
2448 && mSettings.isEnabledLP(p.info, flags)
2449 && (!mSafeMode || (p.info.applicationInfo.flags
2450 &ApplicationInfo.FLAG_SYSTEM) != 0)) {
2451 if (finalList == null) {
2452 finalList = new ArrayList<ProviderInfo>(3);
2453 }
2454 finalList.add(PackageParser.generateProviderInfo(p,
2455 flags));
2456 }
2457 }
2458 }
2459
2460 if (finalList != null) {
2461 Collections.sort(finalList, mProviderInitOrderSorter);
2462 }
2463
2464 return finalList;
2465 }
2466
2467 public InstrumentationInfo getInstrumentationInfo(ComponentName name,
2468 int flags) {
2469 synchronized (mPackages) {
2470 final PackageParser.Instrumentation i = mInstrumentation.get(name);
2471 return PackageParser.generateInstrumentationInfo(i, flags);
2472 }
2473 }
2474
2475 public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
2476 int flags) {
2477 ArrayList<InstrumentationInfo> finalList =
2478 new ArrayList<InstrumentationInfo>();
2479
2480 synchronized (mPackages) {
2481 Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
2482 while (i.hasNext()) {
2483 PackageParser.Instrumentation p = i.next();
2484 if (targetPackage == null
2485 || targetPackage.equals(p.info.targetPackage)) {
2486 finalList.add(PackageParser.generateInstrumentationInfo(p,
2487 flags));
2488 }
2489 }
2490 }
2491
2492 return finalList;
2493 }
2494
2495 private void scanDirLI(File dir, int flags, int scanMode) {
2496 Log.d(TAG, "Scanning app dir " + dir);
2497
2498 String[] files = dir.list();
2499
2500 int i;
2501 for (i=0; i<files.length; i++) {
2502 File file = new File(dir, files[i]);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08002503 if (!isPackageFilename(files[i])) {
2504 // Ignore entries which are not apk's
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002505 continue;
2506 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002507 PackageParser.Package pkg = scanPackageLI(file,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 flags|PackageParser.PARSE_MUST_BE_APK, scanMode);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002509 // Don't mess around with apps in system partition.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08002510 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
2511 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002512 // Delete the apk
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002513 Slog.w(TAG, "Cleaning up failed install of " + file);
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002514 file.delete();
2515 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517 }
2518
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002519 private static File getSettingsProblemFile() {
2520 File dataDir = Environment.getDataDirectory();
2521 File systemDir = new File(dataDir, "system");
2522 File fname = new File(systemDir, "uiderrors.txt");
2523 return fname;
2524 }
2525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 private static void reportSettingsProblem(int priority, String msg) {
2527 try {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002528 File fname = getSettingsProblemFile();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002529 FileOutputStream out = new FileOutputStream(fname, true);
2530 PrintWriter pw = new PrintWriter(out);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002531 SimpleDateFormat formatter = new SimpleDateFormat();
2532 String dateString = formatter.format(new Date(System.currentTimeMillis()));
2533 pw.println(dateString + ": " + msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 pw.close();
2535 FileUtils.setPermissions(
2536 fname.toString(),
2537 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
2538 -1, -1);
2539 } catch (java.io.IOException e) {
2540 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002541 Slog.println(priority, TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 }
2543
2544 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
2545 PackageParser.Package pkg, File srcFile, int parseFlags) {
2546 if (GET_CERTIFICATES) {
Jeff Browne7600722010-04-07 18:28:23 -07002547 if (ps != null
2548 && ps.codePath.equals(srcFile)
2549 && ps.getTimeStamp() == srcFile.lastModified()) {
2550 if (ps.signatures.mSignatures != null
2551 && ps.signatures.mSignatures.length != 0) {
2552 // Optimization: reuse the existing cached certificates
2553 // if the package appears to be unchanged.
2554 pkg.mSignatures = ps.signatures.mSignatures;
2555 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 }
Jeff Browne7600722010-04-07 18:28:23 -07002557
2558 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them.");
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002559 } else {
Jeff Browne7600722010-04-07 18:28:23 -07002560 Log.i(TAG, srcFile.toString() + " changed; collecting certs");
2561 }
2562
2563 if (!pp.collectCertificates(pkg, parseFlags)) {
2564 mLastScanError = pp.getParseError();
2565 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002566 }
2567 }
2568 return true;
2569 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 /*
2572 * Scan a package and return the newly parsed package.
2573 * Returns null in case of errors and the error code is stored in mLastScanError
2574 */
2575 private PackageParser.Package scanPackageLI(File scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002576 int parseFlags, int scanMode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002578 String scanPath = scanFile.getPath();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002579 parseFlags |= mDefParseFlags;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002580 PackageParser pp = new PackageParser(scanPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 pp.setSeparateProcesses(mSeparateProcesses);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582 final PackageParser.Package pkg = pp.parsePackage(scanFile,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002583 scanPath, mMetrics, parseFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 if (pkg == null) {
2585 mLastScanError = pp.getParseError();
2586 return null;
2587 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002588 PackageSetting ps = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 PackageSetting updatedPkg;
2590 synchronized (mPackages) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002591 // Look to see if we already know about this package.
2592 String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002593 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002594 // This package has been renamed to its original name. Let's
2595 // use that.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002596 ps = mSettings.peekPackageLP(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002597 }
2598 // If there was no original package, see one for the real package name.
2599 if (ps == null) {
2600 ps = mSettings.peekPackageLP(pkg.packageName);
2601 }
2602 // Check to see if this package could be hiding/updating a system
2603 // package. Must look for it either under the original or real
2604 // package name depending on our state.
2605 updatedPkg = mSettings.mDisabledSysPackages.get(
2606 ps != null ? ps.name : pkg.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002608 // First check if this is a system package that may involve an update
2609 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
Kenny Root9ee92742010-09-01 13:40:57 -07002610 if (ps != null && !ps.codePath.equals(scanFile)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002611 // The path has changed from what was last scanned... check the
2612 // version of the new path against what we have stored to determine
2613 // what to do.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002614 if (pkg.mVersionCode < ps.versionCode) {
2615 // The system package has been updated and the code path does not match
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002616 // Ignore entry. Skip it.
2617 Log.i(TAG, "Package " + ps.name + " at " + scanFile
2618 + "ignored: updated version " + ps.versionCode
2619 + " better than this " + pkg.mVersionCode);
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002620 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2621 return null;
2622 } else {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002623 // The current app on the system partion is better than
2624 // what we have updated to on the data partition; switch
2625 // back to the system partition version.
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002626 // At this point, its safely assumed that package installation for
2627 // apps in system partition will go through. If not there won't be a working
2628 // version of the app
2629 synchronized (mPackages) {
2630 // Just remove the loaded entries from package lists.
2631 mPackages.remove(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002632 }
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002633 Slog.w(TAG, "Package " + ps.name + " at " + scanFile
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002634 + "reverting from " + ps.codePathString
2635 + ": new version " + pkg.mVersionCode
2636 + " better than installed " + ps.versionCode);
Kenny Root85387d72010-08-26 10:13:11 -07002637 InstallArgs args = new FileInstallArgs(ps.codePathString,
2638 ps.resourcePathString, ps.nativeLibraryPathString);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002639 args.cleanUpResourcesLI();
Dianne Hackborna33e3f72009-09-29 17:28:24 -07002640 mSettings.enableSystemPackageLP(ps.name);
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07002641 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002642 }
2643 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002644 if (updatedPkg != null) {
2645 // An updated system app will not have the PARSE_IS_SYSTEM flag set initially
2646 parseFlags |= PackageParser.PARSE_IS_SYSTEM;
2647 }
2648 // Verify certificates against what was last scanned
2649 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002650 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002651 return null;
2652 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 // The apk is forward locked (not public) if its code and resources
2654 // are kept in different files.
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002655 // TODO grab this value from PackageSettings
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002656 if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002657 parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
Suchi Amalapurapuf2c10722009-07-29 17:19:39 -07002658 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002659
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002660 String codePath = null;
2661 String resPath = null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002662 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) {
2663 if (ps != null && ps.resourcePathString != null) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002664 resPath = ps.resourcePathString;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002665 } else {
2666 // Should not happen at all. Just log an error.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002667 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002668 }
2669 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002670 resPath = pkg.mScanPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002671 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002672 codePath = pkg.mScanPath;
2673 // Set application objects path explicitly.
2674 setApplicationInfoPaths(pkg, codePath, resPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675 // Note that we invoke the following method only if we are about to unpack an application
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002676 return scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 }
2678
Kenny Root85387d72010-08-26 10:13:11 -07002679 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
2680 String destResPath) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08002681 pkg.mPath = pkg.mScanPath = destCodePath;
2682 pkg.applicationInfo.sourceDir = destCodePath;
2683 pkg.applicationInfo.publicSourceDir = destResPath;
2684 }
2685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 private static String fixProcessName(String defProcessName,
2687 String processName, int uid) {
2688 if (processName == null) {
2689 return defProcessName;
2690 }
2691 return processName;
2692 }
2693
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002694 private boolean verifySignaturesLP(PackageSetting pkgSetting,
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002695 PackageParser.Package pkg) {
2696 if (pkgSetting.signatures.mSignatures != null) {
2697 // Already existing package. Make sure signatures match
2698 if (checkSignaturesLP(pkgSetting.signatures.mSignatures, pkg.mSignatures) !=
2699 PackageManager.SIGNATURE_MATCH) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002700 Slog.e(TAG, "Package " + pkg.packageName
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002701 + " signatures do not match the previously installed version; ignoring!");
2702 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 return false;
2704 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07002705 }
2706 // Check for shared user signatures
2707 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
2708 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
2709 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
2710 Slog.e(TAG, "Package " + pkg.packageName
2711 + " has no signatures that match those in shared user "
2712 + pkgSetting.sharedUser.name + "; ignoring!");
2713 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
2714 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002716 }
2717 return true;
2718 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002719
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002720 public boolean performDexOpt(String packageName) {
2721 if (!mNoDexOpt) {
2722 return false;
2723 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002724
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002725 PackageParser.Package p;
2726 synchronized (mPackages) {
2727 p = mPackages.get(packageName);
2728 if (p == null || p.mDidDexOpt) {
2729 return false;
2730 }
2731 }
2732 synchronized (mInstallLock) {
2733 return performDexOptLI(p, false) == DEX_OPT_PERFORMED;
2734 }
2735 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002736
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002737 static final int DEX_OPT_SKIPPED = 0;
2738 static final int DEX_OPT_PERFORMED = 1;
2739 static final int DEX_OPT_FAILED = -1;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002740
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002741 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex) {
2742 boolean performed = false;
Marco Nelissend595c792009-07-02 15:23:26 -07002743 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0 && mInstaller != null) {
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002744 String path = pkg.mScanPath;
2745 int ret = 0;
2746 try {
2747 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002748 ret = mInstaller.dexopt(path, pkg.applicationInfo.uid,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002749 !isForwardLocked(pkg));
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002750 pkg.mDidDexOpt = true;
2751 performed = true;
2752 }
2753 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002754 Slog.w(TAG, "Apk not found for dexopt: " + path);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002755 ret = -1;
2756 } catch (IOException e) {
Suchi Amalapurapu73dafa12010-04-01 16:31:31 -07002757 Slog.w(TAG, "IOException reading apk: " + path, e);
2758 ret = -1;
2759 } catch (dalvik.system.StaleDexCacheError e) {
2760 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
2761 ret = -1;
2762 } catch (Exception e) {
2763 Slog.w(TAG, "Exception when doing dexopt : ", e);
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002764 ret = -1;
2765 }
2766 if (ret < 0) {
2767 //error from installer
2768 return DEX_OPT_FAILED;
2769 }
2770 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002771
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002772 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
2773 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08002774
2775 private static boolean useEncryptedFilesystemForPackage(PackageParser.Package pkg) {
2776 return Environment.isEncryptedFilesystemEnabled() &&
2777 ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_NEVER_ENCRYPT) == 0);
2778 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07002779
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002780 private boolean verifyPackageUpdate(PackageSetting oldPkg, PackageParser.Package newPkg) {
2781 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002782 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002783 + " to " + newPkg.packageName
2784 + ": old package not in system partition");
2785 return false;
2786 } else if (mPackages.get(oldPkg.name) != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002787 Slog.w(TAG, "Unable to update from " + oldPkg.name
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002788 + " to " + newPkg.packageName
2789 + ": old package still exists");
2790 return false;
2791 }
2792 return true;
2793 }
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08002794
2795 private File getDataPathForPackage(PackageParser.Package pkg) {
2796 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
2797 File dataPath;
2798 if (useEncryptedFSDir) {
2799 dataPath = new File(mSecureAppDataDir, pkg.packageName);
2800 } else {
2801 dataPath = new File(mAppDataDir, pkg.packageName);
2802 }
2803 return dataPath;
2804 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002805
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002806 private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
2807 int parseFlags, int scanMode) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002808 File scanFile = new File(pkg.mScanPath);
Suchi Amalapurapu7040ce72010-02-08 23:55:56 -08002809 if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
2810 pkg.applicationInfo.publicSourceDir == null) {
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002811 // Bail out. The resource and code paths haven't been set.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002812 Slog.w(TAG, " Code and resource paths haven't been set correctly");
Suchi Amalapurapu08be55b2010-02-08 16:30:06 -08002813 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
2814 return null;
2815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 mScanningPath = scanFile;
2817 if (pkg == null) {
2818 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME;
2819 return null;
2820 }
2821
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
2823 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
2824 }
2825
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002826 if (pkg.packageName.equals("android")) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002827 synchronized (mPackages) {
2828 if (mAndroidApplication != null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002829 Slog.w(TAG, "*************************************************");
2830 Slog.w(TAG, "Core android package being redefined. Skipping.");
2831 Slog.w(TAG, " file=" + mScanningPath);
2832 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2834 return null;
2835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002836
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 // Set up information for our fall-back user intent resolution
2838 // activity.
2839 mPlatformPackage = pkg;
2840 pkg.mVersionCode = mSdkVersion;
2841 mAndroidApplication = pkg.applicationInfo;
2842 mResolveActivity.applicationInfo = mAndroidApplication;
2843 mResolveActivity.name = ResolverActivity.class.getName();
2844 mResolveActivity.packageName = mAndroidApplication.packageName;
2845 mResolveActivity.processName = mAndroidApplication.processName;
2846 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
2847 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
2848 mResolveActivity.theme = com.android.internal.R.style.Theme_Dialog_Alert;
2849 mResolveActivity.exported = true;
2850 mResolveActivity.enabled = true;
2851 mResolveInfo.activityInfo = mResolveActivity;
2852 mResolveInfo.priority = 0;
2853 mResolveInfo.preferredOrder = 0;
2854 mResolveInfo.match = 0;
2855 mResolveComponentName = new ComponentName(
2856 mAndroidApplication.packageName, mResolveActivity.name);
2857 }
2858 }
2859
2860 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) Log.d(
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002861 TAG, "Scanning package " + pkg.packageName);
2862 if (mPackages.containsKey(pkg.packageName)
2863 || mSharedLibraries.containsKey(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002864 Slog.w(TAG, "*************************************************");
2865 Slog.w(TAG, "Application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 + " already installed. Skipping duplicate.");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002867 Slog.w(TAG, "*************************************************");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
2869 return null;
2870 }
2871
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002872 // Initialize package source and resource directories
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08002873 File destCodeFile = new File(pkg.applicationInfo.sourceDir);
2874 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08002875
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 SharedUserSetting suid = null;
2877 PackageSetting pkgSetting = null;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002878
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002879 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
2880 // Only system apps can use these features.
Dianne Hackbornc1552392010-03-03 16:19:01 -08002881 pkg.mOriginalPackages = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002882 pkg.mRealPackage = null;
2883 pkg.mAdoptPermissions = null;
2884 }
2885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002886 synchronized (mPackages) {
2887 // Check all shared libraries and map to their actual file path.
Dianne Hackborn49237342009-08-27 20:08:01 -07002888 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
2889 if (mTmpSharedLibraries == null ||
2890 mTmpSharedLibraries.length < mSharedLibraries.size()) {
2891 mTmpSharedLibraries = new String[mSharedLibraries.size()];
2892 }
2893 int num = 0;
2894 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
2895 for (int i=0; i<N; i++) {
2896 String file = mSharedLibraries.get(pkg.usesLibraries.get(i));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002898 Slog.e(TAG, "Package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 + " requires unavailable shared library "
Dianne Hackborn49237342009-08-27 20:08:01 -07002900 + pkg.usesLibraries.get(i) + "; failing!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
2902 return null;
2903 }
Dianne Hackborn49237342009-08-27 20:08:01 -07002904 mTmpSharedLibraries[num] = file;
2905 num++;
2906 }
2907 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
2908 for (int i=0; i<N; i++) {
2909 String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
2910 if (file == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002911 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002912 + " desires unavailable shared library "
2913 + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
2914 } else {
2915 mTmpSharedLibraries[num] = file;
2916 num++;
2917 }
2918 }
2919 if (num > 0) {
2920 pkg.usesLibraryFiles = new String[num];
2921 System.arraycopy(mTmpSharedLibraries, 0,
2922 pkg.usesLibraryFiles, 0, num);
2923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002924
Dianne Hackborn49237342009-08-27 20:08:01 -07002925 if (pkg.reqFeatures != null) {
2926 N = pkg.reqFeatures.size();
2927 for (int i=0; i<N; i++) {
2928 FeatureInfo fi = pkg.reqFeatures.get(i);
2929 if ((fi.flags&FeatureInfo.FLAG_REQUIRED) == 0) {
2930 // Don't care.
2931 continue;
2932 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002933
Dianne Hackborn49237342009-08-27 20:08:01 -07002934 if (fi.name != null) {
2935 if (mAvailableFeatures.get(fi.name) == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002936 Slog.e(TAG, "Package " + pkg.packageName
Dianne Hackborn49237342009-08-27 20:08:01 -07002937 + " requires unavailable feature "
2938 + fi.name + "; failing!");
2939 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_FEATURE;
2940 return null;
2941 }
2942 }
2943 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002944 }
2945 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08002946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002947 if (pkg.mSharedUserId != null) {
2948 suid = mSettings.getSharedUserLP(pkg.mSharedUserId,
2949 pkg.applicationInfo.flags, true);
2950 if (suid == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08002951 Slog.w(TAG, "Creating application package " + pkg.packageName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 + " for shared user failed");
2953 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
2954 return null;
2955 }
2956 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD) {
2957 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid="
2958 + suid.userId + "): packages=" + suid.packages);
2959 }
2960 }
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07002961
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002962 if (false) {
Dianne Hackbornc1552392010-03-03 16:19:01 -08002963 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002964 Log.w(TAG, "WAITING FOR DEBUGGER");
2965 Debug.waitForDebugger();
Dianne Hackbornc1552392010-03-03 16:19:01 -08002966 Log.i(TAG, "Package " + pkg.packageName + " from original packages"
2967 + pkg.mOriginalPackages);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002968 }
2969 }
2970
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08002971 // Check if we are renaming from an original package name.
2972 PackageSetting origPackage = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002973 String realName = null;
Dianne Hackbornc1552392010-03-03 16:19:01 -08002974 if (pkg.mOriginalPackages != null) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002975 // This package may need to be renamed to a previously
2976 // installed name. Let's check on that...
2977 String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
Dianne Hackbornc1552392010-03-03 16:19:01 -08002978 if (pkg.mOriginalPackages.contains(renamed)) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08002979 // This package had originally been installed as the
2980 // original name, and we have already taken care of
2981 // transitioning to the new one. Just update the new
2982 // one to continue using the old name.
2983 realName = pkg.mRealPackage;
2984 if (!pkg.packageName.equals(renamed)) {
2985 // Callers into this function may have already taken
2986 // care of renaming the package; only do it here if
2987 // it is not already done.
2988 pkg.setPackageName(renamed);
2989 }
2990
Dianne Hackbornc1552392010-03-03 16:19:01 -08002991 } else {
2992 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
2993 if ((origPackage=mSettings.peekPackageLP(
2994 pkg.mOriginalPackages.get(i))) != null) {
2995 // We do have the package already installed under its
2996 // original name... should we use it?
2997 if (!verifyPackageUpdate(origPackage, pkg)) {
2998 // New package is not compatible with original.
2999 origPackage = null;
3000 continue;
3001 } else if (origPackage.sharedUser != null) {
3002 // Make sure uid is compatible between packages.
3003 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003004 Slog.w(TAG, "Unable to migrate data from " + origPackage.name
Dianne Hackbornc1552392010-03-03 16:19:01 -08003005 + " to " + pkg.packageName + ": old uid "
3006 + origPackage.sharedUser.name
3007 + " differs from " + pkg.mSharedUserId);
3008 origPackage = null;
3009 continue;
3010 }
3011 } else {
3012 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
3013 + pkg.packageName + " to old name " + origPackage.name);
3014 }
3015 break;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003016 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003017 }
3018 }
3019 }
3020
3021 if (mTransferedPackages.contains(pkg.packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003022 Slog.w(TAG, "Package " + pkg.packageName
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003023 + " was transferred to another, but its .apk remains");
3024 }
3025
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003026 // Just create the setting, don't add it yet. For already existing packages
3027 // the PkgSetting exists already and doesn't have to be created.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003028 pkgSetting = mSettings.getPackageLP(pkg, origPackage, realName, suid, destCodeFile,
Kenny Root806cc132010-09-12 08:34:19 -07003029 destResourceFile, pkg.applicationInfo.nativeLibraryDir,
3030 pkg.applicationInfo.flags, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 if (pkgSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003032 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003033 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3034 return null;
3035 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003036
3037 if (pkgSetting.origPackage != null) {
3038 // If we are first transitioning from an original package,
3039 // fix up the new package's name now. We need to do this after
3040 // looking up the package under its new name, so getPackageLP
3041 // can take care of fiddling things correctly.
3042 pkg.setPackageName(origPackage.name);
3043
3044 // File a report about this.
3045 String msg = "New package " + pkgSetting.realName
3046 + " renamed to replace old package " + pkgSetting.name;
3047 reportSettingsProblem(Log.WARN, msg);
3048
3049 // Make a note of it.
3050 mTransferedPackages.add(origPackage.name);
3051
3052 // No longer need to retain this.
3053 pkgSetting.origPackage = null;
3054 }
3055
3056 if (realName != null) {
3057 // Make a note of it.
3058 mTransferedPackages.add(pkg.packageName);
3059 }
3060
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003061 if (mSettings.mDisabledSysPackages.get(pkg.packageName) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
3063 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003065 pkg.applicationInfo.uid = pkgSetting.userId;
3066 pkg.mExtras = pkgSetting;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003067
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003068 if (!verifySignaturesLP(pkgSetting, pkg)) {
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003069 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 return null;
3071 }
3072 // The signature has changed, but this package is in the system
3073 // image... let's recover!
Suchi Amalapurapuc4dd60f2009-03-24 21:10:53 -07003074 pkgSetting.signatures.mSignatures = pkg.mSignatures;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 // However... if this package is part of a shared user, but it
3076 // doesn't match the signature of the shared user, let's fail.
3077 // What this means is that you can't change the signatures
3078 // associated with an overall shared user, which doesn't seem all
3079 // that unreasonable.
3080 if (pkgSetting.sharedUser != null) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07003081 if (checkSignaturesLP(pkgSetting.sharedUser.signatures.mSignatures,
3082 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
3083 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003084 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
3085 return null;
3086 }
3087 }
Dianne Hackborn806da1d2010-03-18 16:50:07 -07003088 // File a report about this.
3089 String msg = "System package " + pkg.packageName
3090 + " signature changed; retaining data.";
3091 reportSettingsProblem(Log.WARN, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003093
The Android Open Source Project10592532009-03-18 17:39:46 -07003094 // Verify that this new package doesn't have any content providers
3095 // that conflict with existing packages. Only do this if the
3096 // package isn't already installed, since we don't want to break
3097 // things that are installed.
3098 if ((scanMode&SCAN_NEW_INSTALL) != 0) {
3099 int N = pkg.providers.size();
3100 int i;
3101 for (i=0; i<N; i++) {
3102 PackageParser.Provider p = pkg.providers.get(i);
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003103 if (p.info.authority != null) {
3104 String names[] = p.info.authority.split(";");
3105 for (int j = 0; j < names.length; j++) {
3106 if (mProviders.containsKey(names[j])) {
3107 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003108 Slog.w(TAG, "Can't install because provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003109 " (in package " + pkg.applicationInfo.packageName +
3110 ") is already used by "
3111 + ((other != null && other.getComponentName() != null)
3112 ? other.getComponentName().getPackageName() : "?"));
3113 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
3114 return null;
3115 }
The Android Open Source Project10592532009-03-18 17:39:46 -07003116 }
3117 }
3118 }
3119 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 }
3121
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003122 final String pkgName = pkg.packageName;
3123
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003124 if (pkg.mAdoptPermissions != null) {
3125 // This package wants to adopt ownership of permissions from
3126 // another package.
3127 for (int i=pkg.mAdoptPermissions.size()-1; i>=0; i--) {
3128 String origName = pkg.mAdoptPermissions.get(i);
3129 PackageSetting orig = mSettings.peekPackageLP(origName);
3130 if (orig != null) {
3131 if (verifyPackageUpdate(orig, pkg)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003132 Slog.i(TAG, "Adopting permissions from "
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003133 + origName + " to " + pkg.packageName);
3134 mSettings.transferPermissions(origName, pkg.packageName);
3135 }
3136 }
3137 }
3138 }
3139
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 long scanFileTime = scanFile.lastModified();
3141 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
3142 final boolean scanFileNewer = forceDex || scanFileTime != pkgSetting.getTimeStamp();
3143 pkg.applicationInfo.processName = fixProcessName(
3144 pkg.applicationInfo.packageName,
3145 pkg.applicationInfo.processName,
3146 pkg.applicationInfo.uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147
3148 File dataPath;
3149 if (mPlatformPackage == pkg) {
3150 // The system package is special.
3151 dataPath = new File (Environment.getDataDirectory(), "system");
3152 pkg.applicationInfo.dataDir = dataPath.getPath();
3153 } else {
3154 // This is a normal package, need to make its data directory.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003155 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(pkg);
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08003156 dataPath = getDataPathForPackage(pkg);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003157
3158 boolean uidError = false;
3159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 if (dataPath.exists()) {
3161 mOutPermissions[1] = 0;
3162 FileUtils.getPermissions(dataPath.getPath(), mOutPermissions);
Kenny Root85387d72010-08-26 10:13:11 -07003163
3164 // If we have mismatched owners for the data path, we have a
3165 // problem (unless we're running in the simulator.)
3166 if (mOutPermissions[1] != pkg.applicationInfo.uid && Process.supportsProcesses()) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 boolean recovered = false;
3168 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
3169 // If this is a system app, we can at least delete its
3170 // current data so the application will still work.
3171 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003172 int ret = mInstaller.remove(pkgName, useEncryptedFSDir);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003173 if (ret >= 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 // Old data gone!
3175 String msg = "System package " + pkg.packageName
3176 + " has changed from uid: "
3177 + mOutPermissions[1] + " to "
3178 + pkg.applicationInfo.uid + "; old data erased";
3179 reportSettingsProblem(Log.WARN, msg);
3180 recovered = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003181
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 // And now re-install the app.
Oscar Montemayora8529f62009-11-18 10:14:20 -08003183 ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 pkg.applicationInfo.uid);
3185 if (ret == -1) {
3186 // Ack should not happen!
3187 msg = "System package " + pkg.packageName
3188 + " could not have data directory re-created after delete.";
3189 reportSettingsProblem(Log.WARN, msg);
3190 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3191 return null;
3192 }
3193 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003195 if (!recovered) {
3196 mHasSystemUidErrors = true;
3197 }
3198 }
3199 if (!recovered) {
3200 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
3201 + pkg.applicationInfo.uid + "/fs_"
3202 + mOutPermissions[1];
Kenny Root85387d72010-08-26 10:13:11 -07003203 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 String msg = "Package " + pkg.packageName
3205 + " has mismatched uid: "
3206 + mOutPermissions[1] + " on disk, "
3207 + pkg.applicationInfo.uid + " in settings";
3208 synchronized (mPackages) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003209 mSettings.mReadMessages.append(msg);
3210 mSettings.mReadMessages.append('\n');
3211 uidError = true;
3212 if (!pkgSetting.uidError) {
3213 reportSettingsProblem(Log.ERROR, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003214 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 }
3216 }
3217 }
3218 pkg.applicationInfo.dataDir = dataPath.getPath();
3219 } else {
3220 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGV)
3221 Log.v(TAG, "Want this data dir: " + dataPath);
3222 //invoke installer to do the actual installation
3223 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08003224 int ret = mInstaller.install(pkgName, useEncryptedFSDir, pkg.applicationInfo.uid,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 pkg.applicationInfo.uid);
3226 if(ret < 0) {
3227 // Error from installer
3228 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
3229 return null;
3230 }
3231 } else {
3232 dataPath.mkdirs();
3233 if (dataPath.exists()) {
3234 FileUtils.setPermissions(
3235 dataPath.toString(),
3236 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
3237 pkg.applicationInfo.uid, pkg.applicationInfo.uid);
3238 }
3239 }
3240 if (dataPath.exists()) {
3241 pkg.applicationInfo.dataDir = dataPath.getPath();
3242 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003243 Slog.w(TAG, "Unable to create data directory: " + dataPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 pkg.applicationInfo.dataDir = null;
3245 }
3246 }
Kenny Root85387d72010-08-26 10:13:11 -07003247
Kenny Root806cc132010-09-12 08:34:19 -07003248 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
3249
Kenny Root85387d72010-08-26 10:13:11 -07003250 /*
3251 * Set the data dir to the default "/data/data/<package name>/lib"
3252 * if we got here without anyone telling us different (e.g., apps
3253 * stored on SD card have their native libraries stored in the ASEC
3254 * container with the APK).
Kenny Root806cc132010-09-12 08:34:19 -07003255 *
3256 * This happens during an upgrade from a package settings file that
3257 * doesn't have a native library path attribute at all.
Kenny Root85387d72010-08-26 10:13:11 -07003258 */
Kenny Root806cc132010-09-12 08:34:19 -07003259 if (pkgSetting.nativeLibraryPathString == null && pkg.applicationInfo.dataDir != null) {
3260 final String nativeLibraryPath = new File(dataPath, LIB_DIR_NAME).getPath();
3261 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
3262 pkgSetting.nativeLibraryPathString = nativeLibraryPath;
Kenny Root85387d72010-08-26 10:13:11 -07003263 }
3264
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08003265 pkgSetting.uidError = uidError;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003266 }
3267
Kenny Root85387d72010-08-26 10:13:11 -07003268 // If we're running in the simulator, we don't need to unpack anything.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 if (mInstaller != null) {
3270 String path = scanFile.getPath();
Kenny Root85387d72010-08-26 10:13:11 -07003271 /* Note: We don't want to unpack the native binaries for
3272 * system applications, unless they have been updated
3273 * (the binaries are already under /system/lib).
3274 * Also, don't unpack libs for apps on the external card
3275 * since they should have their libraries in the ASEC
3276 * container already.
3277 *
3278 * In other words, we're going to unpack the binaries
3279 * only for non-system apps and system app upgrades.
3280 */
3281 if ((!isSystemApp(pkg) || isUpdatedSystemApp(pkg)) && !isExternal(pkg)) {
3282 Log.i(TAG, path + " changed; unpacking");
3283 File sharedLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
Kenny Root85387d72010-08-26 10:13:11 -07003284 NativeLibraryHelper.copyNativeBinariesLI(scanFile, sharedLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 }
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003286 pkg.mScanPath = path;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003287
Dianne Hackborn5c1e00b2009-06-18 17:10:57 -07003288 if ((scanMode&SCAN_NO_DEX) == 0) {
3289 if (performDexOptLI(pkg, forceDex) == DEX_OPT_FAILED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
3291 return null;
3292 }
3293 }
3294 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 if (mFactoryTest && pkg.requestedPermissions.contains(
3297 android.Manifest.permission.FACTORY_TEST)) {
3298 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
3299 }
3300
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003301 // Request the ActivityManager to kill the process(only for existing packages)
3302 // so that we do not end up in a confused state while the user is still using the older
3303 // version of the application while the new one gets installed.
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003304 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003305 killApplication(pkg.applicationInfo.packageName,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003306 pkg.applicationInfo.uid);
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003307 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 synchronized (mPackages) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08003310 // We don't expect installation to fail beyond this point,
3311 if ((scanMode&SCAN_MONITOR) != 0) {
3312 mAppDirs.put(pkg.mPath, pkg);
3313 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 // Add the new setting to mSettings
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08003315 mSettings.insertPackageSettingLP(pkgSetting, pkg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316 // Add the new setting to mPackages
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07003317 mPackages.put(pkg.applicationInfo.packageName, pkg);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08003318 // Make sure we don't accidentally delete its data.
3319 mSettings.mPackagesToBeCleaned.remove(pkgName);
3320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 int N = pkg.providers.size();
3322 StringBuilder r = null;
3323 int i;
3324 for (i=0; i<N; i++) {
3325 PackageParser.Provider p = pkg.providers.get(i);
3326 p.info.processName = fixProcessName(pkg.applicationInfo.processName,
3327 p.info.processName, pkg.applicationInfo.uid);
3328 mProvidersByComponent.put(new ComponentName(p.info.packageName,
3329 p.info.name), p);
3330 p.syncable = p.info.isSyncable;
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003331 if (p.info.authority != null) {
3332 String names[] = p.info.authority.split(";");
3333 p.info.authority = null;
3334 for (int j = 0; j < names.length; j++) {
3335 if (j == 1 && p.syncable) {
3336 // We only want the first authority for a provider to possibly be
3337 // syncable, so if we already added this provider using a different
3338 // authority clear the syncable flag. We copy the provider before
3339 // changing it because the mProviders object contains a reference
3340 // to a provider that we don't want to change.
3341 // Only do this for the second authority since the resulting provider
3342 // object can be the same for all future authorities for this provider.
3343 p = new PackageParser.Provider(p);
3344 p.syncable = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 }
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003346 if (!mProviders.containsKey(names[j])) {
3347 mProviders.put(names[j], p);
3348 if (p.info.authority == null) {
3349 p.info.authority = names[j];
3350 } else {
3351 p.info.authority = p.info.authority + ";" + names[j];
3352 }
3353 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0 && Config.LOGD)
3354 Log.d(TAG, "Registered content provider: " + names[j] +
3355 ", className = " + p.info.name +
3356 ", isSyncable = " + p.info.isSyncable);
3357 } else {
3358 PackageParser.Provider other = mProviders.get(names[j]);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003359 Slog.w(TAG, "Skipping provider name " + names[j] +
Suchi Amalapurapu9444bea2010-03-05 10:46:11 -08003360 " (in package " + pkg.applicationInfo.packageName +
3361 "): name already used by "
3362 + ((other != null && other.getComponentName() != null)
3363 ? other.getComponentName().getPackageName() : "?"));
3364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 }
3366 }
3367 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3368 if (r == null) {
3369 r = new StringBuilder(256);
3370 } else {
3371 r.append(' ');
3372 }
3373 r.append(p.info.name);
3374 }
3375 }
3376 if (r != null) {
3377 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3378 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003379
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 N = pkg.services.size();
3381 r = null;
3382 for (i=0; i<N; i++) {
3383 PackageParser.Service s = pkg.services.get(i);
3384 s.info.processName = fixProcessName(pkg.applicationInfo.processName,
3385 s.info.processName, pkg.applicationInfo.uid);
3386 mServices.addService(s);
3387 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3388 if (r == null) {
3389 r = new StringBuilder(256);
3390 } else {
3391 r.append(' ');
3392 }
3393 r.append(s.info.name);
3394 }
3395 }
3396 if (r != null) {
3397 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3398 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 N = pkg.receivers.size();
3401 r = null;
3402 for (i=0; i<N; i++) {
3403 PackageParser.Activity a = pkg.receivers.get(i);
3404 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3405 a.info.processName, pkg.applicationInfo.uid);
3406 mReceivers.addActivity(a, "receiver");
3407 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3408 if (r == null) {
3409 r = new StringBuilder(256);
3410 } else {
3411 r.append(' ');
3412 }
3413 r.append(a.info.name);
3414 }
3415 }
3416 if (r != null) {
3417 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3418 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 N = pkg.activities.size();
3421 r = null;
3422 for (i=0; i<N; i++) {
3423 PackageParser.Activity a = pkg.activities.get(i);
3424 a.info.processName = fixProcessName(pkg.applicationInfo.processName,
3425 a.info.processName, pkg.applicationInfo.uid);
3426 mActivities.addActivity(a, "activity");
3427 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3428 if (r == null) {
3429 r = new StringBuilder(256);
3430 } else {
3431 r.append(' ');
3432 }
3433 r.append(a.info.name);
3434 }
3435 }
3436 if (r != null) {
3437 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3438 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 N = pkg.permissionGroups.size();
3441 r = null;
3442 for (i=0; i<N; i++) {
3443 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
3444 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
3445 if (cur == null) {
3446 mPermissionGroups.put(pg.info.name, pg);
3447 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3448 if (r == null) {
3449 r = new StringBuilder(256);
3450 } else {
3451 r.append(' ');
3452 }
3453 r.append(pg.info.name);
3454 }
3455 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003456 Slog.w(TAG, "Permission group " + pg.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003457 + pg.info.packageName + " ignored: original from "
3458 + cur.info.packageName);
3459 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3460 if (r == null) {
3461 r = new StringBuilder(256);
3462 } else {
3463 r.append(' ');
3464 }
3465 r.append("DUP:");
3466 r.append(pg.info.name);
3467 }
3468 }
3469 }
3470 if (r != null) {
3471 if (Config.LOGD) Log.d(TAG, " Permission Groups: " + r);
3472 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003473
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 N = pkg.permissions.size();
3475 r = null;
3476 for (i=0; i<N; i++) {
3477 PackageParser.Permission p = pkg.permissions.get(i);
3478 HashMap<String, BasePermission> permissionMap =
3479 p.tree ? mSettings.mPermissionTrees
3480 : mSettings.mPermissions;
3481 p.group = mPermissionGroups.get(p.info.group);
3482 if (p.info.group == null || p.group != null) {
3483 BasePermission bp = permissionMap.get(p.info.name);
3484 if (bp == null) {
3485 bp = new BasePermission(p.info.name, p.info.packageName,
3486 BasePermission.TYPE_NORMAL);
3487 permissionMap.put(p.info.name, bp);
3488 }
3489 if (bp.perm == null) {
3490 if (bp.sourcePackage == null
3491 || bp.sourcePackage.equals(p.info.packageName)) {
3492 BasePermission tree = findPermissionTreeLP(p.info.name);
3493 if (tree == null
3494 || tree.sourcePackage.equals(p.info.packageName)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003495 bp.packageSetting = pkgSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003496 bp.perm = p;
3497 bp.uid = pkg.applicationInfo.uid;
3498 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3499 if (r == null) {
3500 r = new StringBuilder(256);
3501 } else {
3502 r.append(' ');
3503 }
3504 r.append(p.info.name);
3505 }
3506 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003507 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003508 + p.info.packageName + " ignored: base tree "
3509 + tree.name + " is from package "
3510 + tree.sourcePackage);
3511 }
3512 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003513 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 + p.info.packageName + " ignored: original from "
3515 + bp.sourcePackage);
3516 }
3517 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3518 if (r == null) {
3519 r = new StringBuilder(256);
3520 } else {
3521 r.append(' ');
3522 }
3523 r.append("DUP:");
3524 r.append(p.info.name);
3525 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003526 if (bp.perm == p) {
3527 bp.protectionLevel = p.info.protectionLevel;
3528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003530 Slog.w(TAG, "Permission " + p.info.name + " from package "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 + p.info.packageName + " ignored: no group "
3532 + p.group);
3533 }
3534 }
3535 if (r != null) {
3536 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3537 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003538
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 N = pkg.instrumentation.size();
3540 r = null;
3541 for (i=0; i<N; i++) {
3542 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
3543 a.info.packageName = pkg.applicationInfo.packageName;
3544 a.info.sourceDir = pkg.applicationInfo.sourceDir;
3545 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
3546 a.info.dataDir = pkg.applicationInfo.dataDir;
Kenny Root85387d72010-08-26 10:13:11 -07003547 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003548 mInstrumentation.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
3550 if (r == null) {
3551 r = new StringBuilder(256);
3552 } else {
3553 r.append(' ');
3554 }
3555 r.append(a.info.name);
3556 }
3557 }
3558 if (r != null) {
3559 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3560 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003561
Dianne Hackborn854060af2009-07-09 18:14:31 -07003562 if (pkg.protectedBroadcasts != null) {
3563 N = pkg.protectedBroadcasts.size();
3564 for (i=0; i<N; i++) {
3565 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
3566 }
3567 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003568
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003569 pkgSetting.setTimeStamp(scanFileTime);
3570 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003572 return pkg;
3573 }
3574
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08003575 private void killApplication(String pkgName, int uid) {
3576 // Request the ActivityManager to kill the process(only for existing packages)
3577 // so that we do not end up in a confused state while the user is still using the older
3578 // version of the application while the new one gets installed.
3579 IActivityManager am = ActivityManagerNative.getDefault();
3580 if (am != null) {
3581 try {
3582 am.killApplicationWithUid(pkgName, uid);
3583 } catch (RemoteException e) {
3584 }
3585 }
3586 }
3587
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003588 // Return the path of the directory that will contain the native binaries
3589 // of a given installed package. This is relative to the data path.
3590 //
Kenny Root85387d72010-08-26 10:13:11 -07003591 private File getNativeBinaryDirForPackage(PackageParser.Package pkg) {
3592 final String nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
3593 if (nativeLibraryDir != null) {
3594 return new File(nativeLibraryDir);
3595 } else {
3596 // Fall back for old packages
3597 return new File(pkg.applicationInfo.dataDir, LIB_DIR_NAME);
3598 }
David 'Digit' Turner4f99e3c2010-04-12 16:11:15 -07003599 }
3600
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 void removePackageLI(PackageParser.Package pkg, boolean chatty) {
3602 if (chatty && Config.LOGD) Log.d(
3603 TAG, "Removing package " + pkg.applicationInfo.packageName );
3604
3605 synchronized (mPackages) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606 clearPackagePreferredActivitiesLP(pkg.packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003608 mPackages.remove(pkg.applicationInfo.packageName);
3609 if (pkg.mPath != null) {
3610 mAppDirs.remove(pkg.mPath);
3611 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003613 PackageSetting ps = (PackageSetting)pkg.mExtras;
3614 if (ps != null && ps.sharedUser != null) {
3615 // XXX don't do this until the data is removed.
3616 if (false) {
3617 ps.sharedUser.packages.remove(ps);
3618 if (ps.sharedUser.packages.size() == 0) {
3619 // Remove.
3620 }
3621 }
3622 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 int N = pkg.providers.size();
3625 StringBuilder r = null;
3626 int i;
3627 for (i=0; i<N; i++) {
3628 PackageParser.Provider p = pkg.providers.get(i);
3629 mProvidersByComponent.remove(new ComponentName(p.info.packageName,
3630 p.info.name));
3631 if (p.info.authority == null) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003632
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 /* The is another ContentProvider with this authority when
3634 * this app was installed so this authority is null,
3635 * Ignore it as we don't have to unregister the provider.
3636 */
3637 continue;
3638 }
3639 String names[] = p.info.authority.split(";");
3640 for (int j = 0; j < names.length; j++) {
3641 if (mProviders.get(names[j]) == p) {
3642 mProviders.remove(names[j]);
3643 if (chatty && Config.LOGD) Log.d(
3644 TAG, "Unregistered content provider: " + names[j] +
3645 ", className = " + p.info.name +
3646 ", isSyncable = " + p.info.isSyncable);
3647 }
3648 }
3649 if (chatty) {
3650 if (r == null) {
3651 r = new StringBuilder(256);
3652 } else {
3653 r.append(' ');
3654 }
3655 r.append(p.info.name);
3656 }
3657 }
3658 if (r != null) {
3659 if (Config.LOGD) Log.d(TAG, " Providers: " + r);
3660 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 N = pkg.services.size();
3663 r = null;
3664 for (i=0; i<N; i++) {
3665 PackageParser.Service s = pkg.services.get(i);
3666 mServices.removeService(s);
3667 if (chatty) {
3668 if (r == null) {
3669 r = new StringBuilder(256);
3670 } else {
3671 r.append(' ');
3672 }
3673 r.append(s.info.name);
3674 }
3675 }
3676 if (r != null) {
3677 if (Config.LOGD) Log.d(TAG, " Services: " + r);
3678 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 N = pkg.receivers.size();
3681 r = null;
3682 for (i=0; i<N; i++) {
3683 PackageParser.Activity a = pkg.receivers.get(i);
3684 mReceivers.removeActivity(a, "receiver");
3685 if (chatty) {
3686 if (r == null) {
3687 r = new StringBuilder(256);
3688 } else {
3689 r.append(' ');
3690 }
3691 r.append(a.info.name);
3692 }
3693 }
3694 if (r != null) {
3695 if (Config.LOGD) Log.d(TAG, " Receivers: " + r);
3696 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 N = pkg.activities.size();
3699 r = null;
3700 for (i=0; i<N; i++) {
3701 PackageParser.Activity a = pkg.activities.get(i);
3702 mActivities.removeActivity(a, "activity");
3703 if (chatty) {
3704 if (r == null) {
3705 r = new StringBuilder(256);
3706 } else {
3707 r.append(' ');
3708 }
3709 r.append(a.info.name);
3710 }
3711 }
3712 if (r != null) {
3713 if (Config.LOGD) Log.d(TAG, " Activities: " + r);
3714 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 N = pkg.permissions.size();
3717 r = null;
3718 for (i=0; i<N; i++) {
3719 PackageParser.Permission p = pkg.permissions.get(i);
3720 boolean tree = false;
3721 BasePermission bp = mSettings.mPermissions.get(p.info.name);
3722 if (bp == null) {
3723 tree = true;
3724 bp = mSettings.mPermissionTrees.get(p.info.name);
3725 }
3726 if (bp != null && bp.perm == p) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003727 bp.perm = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003728 if (chatty) {
3729 if (r == null) {
3730 r = new StringBuilder(256);
3731 } else {
3732 r.append(' ');
3733 }
3734 r.append(p.info.name);
3735 }
3736 }
3737 }
3738 if (r != null) {
3739 if (Config.LOGD) Log.d(TAG, " Permissions: " + r);
3740 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003742 N = pkg.instrumentation.size();
3743 r = null;
3744 for (i=0; i<N; i++) {
3745 PackageParser.Instrumentation a = pkg.instrumentation.get(i);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08003746 mInstrumentation.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003747 if (chatty) {
3748 if (r == null) {
3749 r = new StringBuilder(256);
3750 } else {
3751 r.append(' ');
3752 }
3753 r.append(a.info.name);
3754 }
3755 }
3756 if (r != null) {
3757 if (Config.LOGD) Log.d(TAG, " Instrumentation: " + r);
3758 }
3759 }
3760 }
3761
3762 private static final boolean isPackageFilename(String name) {
3763 return name != null && name.endsWith(".apk");
3764 }
3765
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003766 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
3767 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
3768 if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
3769 return true;
3770 }
3771 }
3772 return false;
3773 }
3774
3775 private void updatePermissionsLP(String changingPkg,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003776 PackageParser.Package pkgInfo, boolean grantPermissions,
3777 boolean replace, boolean replaceAll) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 // Make sure there are no dangling permission trees.
3779 Iterator<BasePermission> it = mSettings.mPermissionTrees
3780 .values().iterator();
3781 while (it.hasNext()) {
3782 BasePermission bp = it.next();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003783 if (bp.packageSetting == null) {
3784 // We may not yet have parsed the package, so just see if
3785 // we still know about its settings.
3786 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3787 }
3788 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003789 Slog.w(TAG, "Removing dangling permission tree: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003790 + " from package " + bp.sourcePackage);
3791 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003792 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3793 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3794 Slog.i(TAG, "Removing old permission tree: " + bp.name
3795 + " from package " + bp.sourcePackage);
3796 grantPermissions = true;
3797 it.remove();
3798 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 }
3800 }
3801
3802 // Make sure all dynamic permissions have been assigned to a package,
3803 // and make sure there are no dangling permissions.
3804 it = mSettings.mPermissions.values().iterator();
3805 while (it.hasNext()) {
3806 BasePermission bp = it.next();
3807 if (bp.type == BasePermission.TYPE_DYNAMIC) {
3808 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
3809 + bp.name + " pkg=" + bp.sourcePackage
3810 + " info=" + bp.pendingInfo);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003811 if (bp.packageSetting == null && bp.pendingInfo != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 BasePermission tree = findPermissionTreeLP(bp.name);
3813 if (tree != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003814 bp.packageSetting = tree.packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 bp.perm = new PackageParser.Permission(tree.perm.owner,
3816 new PermissionInfo(bp.pendingInfo));
3817 bp.perm.info.packageName = tree.perm.info.packageName;
3818 bp.perm.info.name = bp.name;
3819 bp.uid = tree.uid;
3820 }
3821 }
3822 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003823 if (bp.packageSetting == null) {
3824 // We may not yet have parsed the package, so just see if
3825 // we still know about its settings.
3826 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
3827 }
3828 if (bp.packageSetting == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003829 Slog.w(TAG, "Removing dangling permission: " + bp.name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003830 + " from package " + bp.sourcePackage);
3831 it.remove();
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003832 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
3833 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
3834 Slog.i(TAG, "Removing old permission: " + bp.name
3835 + " from package " + bp.sourcePackage);
3836 grantPermissions = true;
3837 it.remove();
3838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003839 }
3840 }
3841
3842 // Now update the permissions for all packages, in particular
3843 // replace the granted permissions of the system packages.
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003844 if (grantPermissions) {
3845 for (PackageParser.Package pkg : mPackages.values()) {
3846 if (pkg != pkgInfo) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07003847 grantPermissionsLP(pkg, replaceAll);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003848 }
3849 }
3850 }
3851
3852 if (pkgInfo != null) {
3853 grantPermissionsLP(pkgInfo, replace);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 }
3855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 private void grantPermissionsLP(PackageParser.Package pkg, boolean replace) {
3858 final PackageSetting ps = (PackageSetting)pkg.mExtras;
3859 if (ps == null) {
3860 return;
3861 }
3862 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003863 boolean changedPermission = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 if (replace) {
3866 ps.permissionsFixed = false;
3867 if (gp == ps) {
3868 gp.grantedPermissions.clear();
3869 gp.gids = mGlobalGids;
3870 }
3871 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003873 if (gp.gids == null) {
3874 gp.gids = mGlobalGids;
3875 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003877 final int N = pkg.requestedPermissions.size();
3878 for (int i=0; i<N; i++) {
3879 String name = pkg.requestedPermissions.get(i);
3880 BasePermission bp = mSettings.mPermissions.get(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003881 if (false) {
3882 if (gp != ps) {
3883 Log.i(TAG, "Package " + pkg.packageName + " checking " + name
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003884 + ": " + bp);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003885 }
3886 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003887 if (bp != null && bp.packageSetting != null) {
3888 final String perm = bp.name;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 boolean allowed;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003890 boolean allowedSig = false;
3891 if (bp.protectionLevel == PermissionInfo.PROTECTION_NORMAL
3892 || bp.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 allowed = true;
Dianne Hackborn6e52b5d2010-04-05 14:33:01 -07003894 } else if (bp.packageSetting == null) {
3895 // This permission is invalid; skip it.
3896 allowed = false;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003897 } else if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE
3898 || bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
3899 allowed = (checkSignaturesLP(bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 == PackageManager.SIGNATURE_MATCH)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07003901 || (checkSignaturesLP(mPlatformPackage.mSignatures, pkg.mSignatures)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 == PackageManager.SIGNATURE_MATCH);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003903 if (bp.protectionLevel == PermissionInfo.PROTECTION_SIGNATURE_OR_SYSTEM) {
Kenny Root85387d72010-08-26 10:13:11 -07003904 if (isSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 // For updated system applications, the signatureOrSystem permission
3906 // is granted only if it had been defined by the original application.
Kenny Root85387d72010-08-26 10:13:11 -07003907 if (isUpdatedSystemApp(pkg)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 PackageSetting sysPs = mSettings.getDisabledSystemPkg(pkg.packageName);
3909 if(sysPs.grantedPermissions.contains(perm)) {
3910 allowed = true;
3911 } else {
3912 allowed = false;
3913 }
3914 } else {
3915 allowed = true;
3916 }
3917 }
3918 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003919 if (allowed) {
3920 allowedSig = true;
3921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 } else {
3923 allowed = false;
3924 }
3925 if (false) {
3926 if (gp != ps) {
3927 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
3928 }
3929 }
3930 if (allowed) {
3931 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
3932 && ps.permissionsFixed) {
3933 // If this is an existing, non-system package, then
3934 // we can't add any new permissions to it.
Dianne Hackbornf657b632010-03-22 18:08:07 -07003935 if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 allowed = false;
Dianne Hackborn62da8462009-05-13 15:06:13 -07003937 // Except... if this is a permission that was added
3938 // to the platform (note: need to only do this when
3939 // updating the platform).
3940 final int NP = PackageParser.NEW_PERMISSIONS.length;
3941 for (int ip=0; ip<NP; ip++) {
3942 final PackageParser.NewPermissionInfo npi
3943 = PackageParser.NEW_PERMISSIONS[ip];
3944 if (npi.name.equals(perm)
3945 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
3946 allowed = true;
Dianne Hackbornf657b632010-03-22 18:08:07 -07003947 Log.i(TAG, "Auto-granting " + perm + " to old pkg "
Dianne Hackborn62da8462009-05-13 15:06:13 -07003948 + pkg.packageName);
3949 break;
3950 }
3951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003952 }
3953 }
3954 if (allowed) {
3955 if (!gp.grantedPermissions.contains(perm)) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003956 changedPermission = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003957 gp.grantedPermissions.add(perm);
3958 gp.gids = appendInts(gp.gids, bp.gids);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003959 } else if (!ps.haveGids) {
3960 gp.gids = appendInts(gp.gids, bp.gids);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 }
3962 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003963 Slog.w(TAG, "Not granting permission " + perm
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003964 + " to package " + pkg.packageName
3965 + " because it was previously installed without");
3966 }
3967 } else {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003968 if (gp.grantedPermissions.remove(perm)) {
3969 changedPermission = true;
3970 gp.gids = removeInts(gp.gids, bp.gids);
3971 Slog.i(TAG, "Un-granting permission " + perm
3972 + " from package " + pkg.packageName
3973 + " (protectionLevel=" + bp.protectionLevel
3974 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3975 + ")");
3976 } else {
3977 Slog.w(TAG, "Not granting permission " + perm
3978 + " to package " + pkg.packageName
3979 + " (protectionLevel=" + bp.protectionLevel
3980 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
3981 + ")");
3982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003983 }
3984 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08003985 Slog.w(TAG, "Unknown permission " + name
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003986 + " in package " + pkg.packageName);
3987 }
3988 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003989
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07003990 if ((changedPermission || replace) && !ps.permissionsFixed &&
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07003991 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) ||
3992 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 // This is the first that we have heard about this package, so the
3994 // permissions we have now selected are fixed until explicitly
3995 // changed.
3996 ps.permissionsFixed = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003997 }
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07003998 ps.haveGids = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003999 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 private final class ActivityIntentResolver
4002 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004003 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004004 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004005 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004006 }
4007
Mihai Preda074edef2009-05-18 17:13:31 +02004008 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004010 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4012 }
4013
Mihai Predaeae850c2009-05-13 10:13:48 +02004014 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4015 ArrayList<PackageParser.Activity> packageActivities) {
4016 if (packageActivities == null) {
4017 return null;
4018 }
4019 mFlags = flags;
4020 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4021 int N = packageActivities.size();
4022 ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut =
4023 new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(N);
Mihai Predac3320db2009-05-18 20:15:32 +02004024
4025 ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
Mihai Predaeae850c2009-05-13 10:13:48 +02004026 for (int i = 0; i < N; ++i) {
Mihai Predac3320db2009-05-18 20:15:32 +02004027 intentFilters = packageActivities.get(i).intents;
4028 if (intentFilters != null && intentFilters.size() > 0) {
4029 listCut.add(intentFilters);
4030 }
Mihai Predaeae850c2009-05-13 10:13:48 +02004031 }
4032 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4033 }
4034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004035 public final void addActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004036 mActivities.put(a.getComponentName(), a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 if (SHOW_INFO || Config.LOGV) Log.v(
4038 TAG, " " + type + " " +
4039 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4040 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4041 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004042 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004043 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4044 if (SHOW_INFO || Config.LOGV) {
4045 Log.v(TAG, " IntentFilter:");
4046 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4047 }
4048 if (!intent.debugCheck()) {
4049 Log.w(TAG, "==> For Activity " + a.info.name);
4050 }
4051 addFilter(intent);
4052 }
4053 }
4054
4055 public final void removeActivity(PackageParser.Activity a, String type) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004056 mActivities.remove(a.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 if (SHOW_INFO || Config.LOGV) Log.v(
4058 TAG, " " + type + " " +
4059 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
4060 if (SHOW_INFO || Config.LOGV) Log.v(TAG, " Class=" + a.info.name);
4061 int NI = a.intents.size();
Mihai Predaeae850c2009-05-13 10:13:48 +02004062 for (int j=0; j<NI; j++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 PackageParser.ActivityIntentInfo intent = a.intents.get(j);
4064 if (SHOW_INFO || Config.LOGV) {
4065 Log.v(TAG, " IntentFilter:");
4066 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4067 }
4068 removeFilter(intent);
4069 }
4070 }
4071
4072 @Override
4073 protected boolean allowFilterResult(
4074 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
4075 ActivityInfo filterAi = filter.activity.info;
4076 for (int i=dest.size()-1; i>=0; i--) {
4077 ActivityInfo destAi = dest.get(i).activityInfo;
4078 if (destAi.name == filterAi.name
4079 && destAi.packageName == filterAi.packageName) {
4080 return false;
4081 }
4082 }
4083 return true;
4084 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004085
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004086 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004087 protected String packageForFilter(PackageParser.ActivityIntentInfo info) {
4088 return info.activity.owner.packageName;
4089 }
4090
4091 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004092 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
4093 int match) {
4094 if (!mSettings.isEnabledLP(info.activity.info, mFlags)) {
4095 return null;
4096 }
4097 final PackageParser.Activity activity = info.activity;
4098 if (mSafeMode && (activity.info.applicationInfo.flags
4099 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4100 return null;
4101 }
4102 final ResolveInfo res = new ResolveInfo();
4103 res.activityInfo = PackageParser.generateActivityInfo(activity,
4104 mFlags);
4105 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4106 res.filter = info;
4107 }
4108 res.priority = info.getPriority();
4109 res.preferredOrder = activity.owner.mPreferredOrder;
4110 //System.out.println("Result: " + res.activityInfo.className +
4111 // " = " + res.priority);
4112 res.match = match;
4113 res.isDefault = info.hasDefault;
4114 res.labelRes = info.labelRes;
4115 res.nonLocalizedLabel = info.nonLocalizedLabel;
4116 res.icon = info.icon;
4117 return res;
4118 }
4119
4120 @Override
4121 protected void sortResults(List<ResolveInfo> results) {
4122 Collections.sort(results, mResolvePrioritySorter);
4123 }
4124
4125 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004126 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004127 PackageParser.ActivityIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004128 out.print(prefix); out.print(
4129 Integer.toHexString(System.identityHashCode(filter.activity)));
4130 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004131 out.print(filter.activity.getComponentShortName());
4132 out.print(" filter ");
4133 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 }
4135
4136// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4137// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4138// final List<ResolveInfo> retList = Lists.newArrayList();
4139// while (i.hasNext()) {
4140// final ResolveInfo resolveInfo = i.next();
4141// if (isEnabledLP(resolveInfo.activityInfo)) {
4142// retList.add(resolveInfo);
4143// }
4144// }
4145// return retList;
4146// }
4147
4148 // Keys are String (activity class name), values are Activity.
4149 private final HashMap<ComponentName, PackageParser.Activity> mActivities
4150 = new HashMap<ComponentName, PackageParser.Activity>();
4151 private int mFlags;
4152 }
4153
4154 private final class ServiceIntentResolver
4155 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
Mihai Preda074edef2009-05-18 17:13:31 +02004156 public List queryIntent(Intent intent, String resolvedType, boolean defaultOnly) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004157 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
Mihai Preda074edef2009-05-18 17:13:31 +02004158 return super.queryIntent(intent, resolvedType, defaultOnly);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 }
4160
Mihai Preda074edef2009-05-18 17:13:31 +02004161 public List queryIntent(Intent intent, String resolvedType, int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 mFlags = flags;
Mihai Preda074edef2009-05-18 17:13:31 +02004163 return super.queryIntent(intent, resolvedType,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0);
4165 }
4166
Dianne Hackbornc14b9ccd2009-06-17 18:02:12 -07004167 public List queryIntentForPackage(Intent intent, String resolvedType, int flags,
4168 ArrayList<PackageParser.Service> packageServices) {
4169 if (packageServices == null) {
4170 return null;
4171 }
4172 mFlags = flags;
4173 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
4174 int N = packageServices.size();
4175 ArrayList<ArrayList<PackageParser.ServiceIntentInfo>> listCut =
4176 new ArrayList<ArrayList<PackageParser.ServiceIntentInfo>>(N);
4177
4178 ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
4179 for (int i = 0; i < N; ++i) {
4180 intentFilters = packageServices.get(i).intents;
4181 if (intentFilters != null && intentFilters.size() > 0) {
4182 listCut.add(intentFilters);
4183 }
4184 }
4185 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
4186 }
4187
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 public final void addService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004189 mServices.put(s.getComponentName(), s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004190 if (SHOW_INFO || Config.LOGV) Log.v(
4191 TAG, " " + (s.info.nonLocalizedLabel != null
4192 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4193 if (SHOW_INFO || Config.LOGV) Log.v(
4194 TAG, " Class=" + s.info.name);
4195 int NI = s.intents.size();
4196 int j;
4197 for (j=0; j<NI; j++) {
4198 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4199 if (SHOW_INFO || Config.LOGV) {
4200 Log.v(TAG, " IntentFilter:");
4201 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4202 }
4203 if (!intent.debugCheck()) {
4204 Log.w(TAG, "==> For Service " + s.info.name);
4205 }
4206 addFilter(intent);
4207 }
4208 }
4209
4210 public final void removeService(PackageParser.Service s) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08004211 mServices.remove(s.getComponentName());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 if (SHOW_INFO || Config.LOGV) Log.v(
4213 TAG, " " + (s.info.nonLocalizedLabel != null
4214 ? s.info.nonLocalizedLabel : s.info.name) + ":");
4215 if (SHOW_INFO || Config.LOGV) Log.v(
4216 TAG, " Class=" + s.info.name);
4217 int NI = s.intents.size();
4218 int j;
4219 for (j=0; j<NI; j++) {
4220 PackageParser.ServiceIntentInfo intent = s.intents.get(j);
4221 if (SHOW_INFO || Config.LOGV) {
4222 Log.v(TAG, " IntentFilter:");
4223 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
4224 }
4225 removeFilter(intent);
4226 }
4227 }
4228
4229 @Override
4230 protected boolean allowFilterResult(
4231 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
4232 ServiceInfo filterSi = filter.service.info;
4233 for (int i=dest.size()-1; i>=0; i--) {
4234 ServiceInfo destAi = dest.get(i).serviceInfo;
4235 if (destAi.name == filterSi.name
4236 && destAi.packageName == filterSi.packageName) {
4237 return false;
4238 }
4239 }
4240 return true;
4241 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004244 protected String packageForFilter(PackageParser.ServiceIntentInfo info) {
4245 return info.service.owner.packageName;
4246 }
4247
4248 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
4250 int match) {
4251 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
4252 if (!mSettings.isEnabledLP(info.service.info, mFlags)) {
4253 return null;
4254 }
4255 final PackageParser.Service service = info.service;
4256 if (mSafeMode && (service.info.applicationInfo.flags
4257 &ApplicationInfo.FLAG_SYSTEM) == 0) {
4258 return null;
4259 }
4260 final ResolveInfo res = new ResolveInfo();
4261 res.serviceInfo = PackageParser.generateServiceInfo(service,
4262 mFlags);
4263 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
4264 res.filter = filter;
4265 }
4266 res.priority = info.getPriority();
4267 res.preferredOrder = service.owner.mPreferredOrder;
4268 //System.out.println("Result: " + res.activityInfo.className +
4269 // " = " + res.priority);
4270 res.match = match;
4271 res.isDefault = info.hasDefault;
4272 res.labelRes = info.labelRes;
4273 res.nonLocalizedLabel = info.nonLocalizedLabel;
4274 res.icon = info.icon;
4275 return res;
4276 }
4277
4278 @Override
4279 protected void sortResults(List<ResolveInfo> results) {
4280 Collections.sort(results, mResolvePrioritySorter);
4281 }
4282
4283 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004284 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004285 PackageParser.ServiceIntentInfo filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07004286 out.print(prefix); out.print(
4287 Integer.toHexString(System.identityHashCode(filter.service)));
4288 out.print(' ');
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004289 out.print(filter.service.getComponentShortName());
4290 out.print(" filter ");
4291 out.println(Integer.toHexString(System.identityHashCode(filter)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004292 }
4293
4294// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
4295// final Iterator<ResolveInfo> i = resolveInfoList.iterator();
4296// final List<ResolveInfo> retList = Lists.newArrayList();
4297// while (i.hasNext()) {
4298// final ResolveInfo resolveInfo = (ResolveInfo) i;
4299// if (isEnabledLP(resolveInfo.serviceInfo)) {
4300// retList.add(resolveInfo);
4301// }
4302// }
4303// return retList;
4304// }
4305
4306 // Keys are String (activity class name), values are Activity.
4307 private final HashMap<ComponentName, PackageParser.Service> mServices
4308 = new HashMap<ComponentName, PackageParser.Service>();
4309 private int mFlags;
4310 };
4311
4312 private static final Comparator<ResolveInfo> mResolvePrioritySorter =
4313 new Comparator<ResolveInfo>() {
4314 public int compare(ResolveInfo r1, ResolveInfo r2) {
4315 int v1 = r1.priority;
4316 int v2 = r2.priority;
4317 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
4318 if (v1 != v2) {
4319 return (v1 > v2) ? -1 : 1;
4320 }
4321 v1 = r1.preferredOrder;
4322 v2 = r2.preferredOrder;
4323 if (v1 != v2) {
4324 return (v1 > v2) ? -1 : 1;
4325 }
4326 if (r1.isDefault != r2.isDefault) {
4327 return r1.isDefault ? -1 : 1;
4328 }
4329 v1 = r1.match;
4330 v2 = r2.match;
4331 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
4332 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4333 }
4334 };
4335
4336 private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
4337 new Comparator<ProviderInfo>() {
4338 public int compare(ProviderInfo p1, ProviderInfo p2) {
4339 final int v1 = p1.initOrder;
4340 final int v2 = p2.initOrder;
4341 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
4342 }
4343 };
4344
Kenny Root93565c4b2010-06-18 15:46:06 -07004345 private static final boolean DEBUG_OBB = false;
4346
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004347 private static final void sendPackageBroadcast(String action, String pkg,
4348 Bundle extras, IIntentReceiver finishedReceiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004349 IActivityManager am = ActivityManagerNative.getDefault();
4350 if (am != null) {
4351 try {
4352 final Intent intent = new Intent(action,
4353 pkg != null ? Uri.fromParts("package", pkg, null) : null);
4354 if (extras != null) {
4355 intent.putExtras(extras);
4356 }
Dianne Hackbornde7faf62009-06-30 13:27:30 -07004357 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004358 am.broadcastIntent(null, intent, null, finishedReceiver,
4359 0, null, null, null, finishedReceiver != null, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 } catch (RemoteException ex) {
4361 }
4362 }
4363 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004364
4365 public String nextPackageToClean(String lastPackage) {
4366 synchronized (mPackages) {
4367 if (!mMediaMounted) {
4368 // If the external storage is no longer mounted at this point,
4369 // the caller may not have been able to delete all of this
4370 // packages files and can not delete any more. Bail.
4371 return null;
4372 }
4373 if (lastPackage != null) {
4374 mSettings.mPackagesToBeCleaned.remove(lastPackage);
4375 }
4376 return mSettings.mPackagesToBeCleaned.size() > 0
4377 ? mSettings.mPackagesToBeCleaned.get(0) : null;
4378 }
4379 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004380
Dianne Hackborne83cefce2010-02-04 17:38:14 -08004381 void schedulePackageCleaning(String packageName) {
4382 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, packageName));
4383 }
4384
4385 void startCleaningPackages() {
4386 synchronized (mPackages) {
4387 if (!mMediaMounted) {
4388 return;
4389 }
4390 if (mSettings.mPackagesToBeCleaned.size() <= 0) {
4391 return;
4392 }
4393 }
4394 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
4395 intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
4396 IActivityManager am = ActivityManagerNative.getDefault();
4397 if (am != null) {
4398 try {
4399 am.startService(null, intent, null);
4400 } catch (RemoteException e) {
4401 }
4402 }
4403 }
4404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004405 private final class AppDirObserver extends FileObserver {
4406 public AppDirObserver(String path, int mask, boolean isrom) {
4407 super(path, mask);
4408 mRootDir = path;
4409 mIsRom = isrom;
4410 }
4411
4412 public void onEvent(int event, String path) {
4413 String removedPackage = null;
4414 int removedUid = -1;
4415 String addedPackage = null;
4416 int addedUid = -1;
4417
4418 synchronized (mInstallLock) {
4419 String fullPathStr = null;
4420 File fullPath = null;
4421 if (path != null) {
4422 fullPath = new File(mRootDir, path);
4423 fullPathStr = fullPath.getPath();
4424 }
4425
4426 if (Config.LOGV) Log.v(
4427 TAG, "File " + fullPathStr + " changed: "
4428 + Integer.toHexString(event));
4429
4430 if (!isPackageFilename(path)) {
4431 if (Config.LOGV) Log.v(
4432 TAG, "Ignoring change of non-package file: " + fullPathStr);
4433 return;
4434 }
4435
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004436 // Ignore packages that are being installed or
4437 // have just been installed.
4438 if (ignoreCodePath(fullPathStr)) {
4439 return;
4440 }
4441 PackageParser.Package p = null;
4442 synchronized (mPackages) {
4443 p = mAppDirs.get(fullPathStr);
4444 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004445 if ((event&REMOVE_EVENTS) != 0) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004446 if (p != null) {
4447 removePackageLI(p, true);
4448 removedPackage = p.applicationInfo.packageName;
4449 removedUid = p.applicationInfo.uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004450 }
4451 }
4452
4453 if ((event&ADD_EVENTS) != 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004454 if (p == null) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08004455 p = scanPackageLI(fullPath,
Dianne Hackborn806da1d2010-03-18 16:50:07 -07004456 (mIsRom ? PackageParser.PARSE_IS_SYSTEM
4457 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004458 PackageParser.PARSE_CHATTY |
4459 PackageParser.PARSE_MUST_BE_APK,
Andrew Stadler48c02732010-01-15 00:03:41 -08004460 SCAN_MONITOR | SCAN_NO_PATHS);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004461 if (p != null) {
4462 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07004463 updatePermissionsLP(p.packageName, p,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07004464 p.permissions.size() > 0, false, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004465 }
4466 addedPackage = p.applicationInfo.packageName;
4467 addedUid = p.applicationInfo.uid;
4468 }
4469 }
4470 }
4471
4472 synchronized (mPackages) {
4473 mSettings.writeLP();
4474 }
4475 }
4476
4477 if (removedPackage != null) {
4478 Bundle extras = new Bundle(1);
4479 extras.putInt(Intent.EXTRA_UID, removedUid);
4480 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004481 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
4482 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004483 }
4484 if (addedPackage != null) {
4485 Bundle extras = new Bundle(1);
4486 extras.putInt(Intent.EXTRA_UID, addedUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07004487 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
4488 extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004489 }
4490 }
4491
4492 private final String mRootDir;
4493 private final boolean mIsRom;
4494 }
Jacek Surazski65e13172009-04-28 15:26:38 +02004495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004496 /* Called when a downloaded package installation has been confirmed by the user */
4497 public void installPackage(
4498 final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
Jacek Surazski65e13172009-04-28 15:26:38 +02004499 installPackage(packageURI, observer, flags, null);
4500 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004501
Jacek Surazski65e13172009-04-28 15:26:38 +02004502 /* Called when a downloaded package installation has been confirmed by the user */
4503 public void installPackage(
4504 final Uri packageURI, final IPackageInstallObserver observer, final int flags,
4505 final String installerPackageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004506 mContext.enforceCallingOrSelfPermission(
4507 android.Manifest.permission.INSTALL_PACKAGES, null);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08004508
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004509 Message msg = mHandler.obtainMessage(INIT_COPY);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004510 msg.obj = new InstallParams(packageURI, observer, flags,
4511 installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004512 mHandler.sendMessage(msg);
4513 }
4514
Christopher Tate1bb69062010-02-19 17:02:12 -08004515 public void finishPackageInstall(int token) {
4516 if (DEBUG_INSTALL) Log.v(TAG, "BM finishing package install for " + token);
4517 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4518 mHandler.sendMessage(msg);
4519 }
4520
Kenny Root93565c4b2010-06-18 15:46:06 -07004521 public void setPackageObbPath(String packageName, String path) {
4522 if (DEBUG_OBB)
4523 Log.v(TAG, "Setting .obb path for " + packageName + " to: " + path);
4524 PackageSetting pkgSetting;
4525 final int uid = Binder.getCallingUid();
Kenny Roote059b272010-07-12 08:36:07 -07004526 final int permission = mContext.checkCallingPermission(
4527 android.Manifest.permission.INSTALL_PACKAGES);
4528 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Kenny Root93565c4b2010-06-18 15:46:06 -07004529 synchronized (mPackages) {
4530 pkgSetting = mSettings.mPackages.get(packageName);
4531 if (pkgSetting == null) {
4532 throw new IllegalArgumentException("Unknown package: " + packageName);
4533 }
4534 if (!allowedByPermission && (uid != pkgSetting.userId)) {
4535 throw new SecurityException("Permission denial: attempt to set .obb file from pid="
4536 + Binder.getCallingPid() + ", uid=" + uid + ", package uid="
4537 + pkgSetting.userId);
4538 }
4539 pkgSetting.obbPathString = path;
4540 mSettings.writeLP();
4541 }
4542 }
4543
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004544 private void processPendingInstall(final InstallArgs args, final int currentStatus) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004545 // Queue up an async operation since the package installation may take a little while.
4546 mHandler.post(new Runnable() {
4547 public void run() {
4548 mHandler.removeCallbacks(this);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004549 // Result object to be returned
4550 PackageInstalledInfo res = new PackageInstalledInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004551 res.returnCode = currentStatus;
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004552 res.uid = -1;
4553 res.pkg = null;
4554 res.removedInfo = new PackageRemovedInfo();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004555 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004556 args.doPreInstall(res.returnCode);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004557 synchronized (mInstallLock) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004558 installPackageLI(args, true, res);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07004559 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004560 args.doPostInstall(res.returnCode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004561 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004562
4563 // A restore should be performed at this point if (a) the install
4564 // succeeded, (b) the operation is not an update, and (c) the new
4565 // package has a backupAgent defined.
4566 final boolean update = res.removedInfo.removedPackage != null;
Christopher Tate59eac4b2010-02-19 19:25:45 -08004567 boolean doRestore = (!update
4568 && res.pkg != null
4569 && res.pkg.applicationInfo.backupAgentName != null);
Christopher Tate1bb69062010-02-19 17:02:12 -08004570
4571 // Set up the post-install work request bookkeeping. This will be used
4572 // and cleaned up by the post-install event handling regardless of whether
4573 // there's a restore pass performed. Token values are >= 1.
4574 int token;
4575 if (mNextInstallToken < 0) mNextInstallToken = 1;
4576 token = mNextInstallToken++;
4577
4578 PostInstallData data = new PostInstallData(args, res);
4579 mRunningInstalls.put(token, data);
4580 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
4581
4582 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
4583 // Pass responsibility to the Backup Manager. It will perform a
4584 // restore if appropriate, then pass responsibility back to the
4585 // Package Manager to run the post-install observer callbacks
4586 // and broadcasts.
4587 IBackupManager bm = IBackupManager.Stub.asInterface(
4588 ServiceManager.getService(Context.BACKUP_SERVICE));
4589 if (bm != null) {
4590 if (DEBUG_INSTALL) Log.v(TAG, "token " + token
4591 + " to BM for possible restore");
4592 try {
4593 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
4594 } catch (RemoteException e) {
4595 // can't happen; the backup manager is local
4596 } catch (Exception e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004597 Slog.e(TAG, "Exception trying to enqueue restore", e);
Christopher Tate1bb69062010-02-19 17:02:12 -08004598 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004599 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004600 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004601 Slog.e(TAG, "Backup Manager not found!");
Christopher Tate1bb69062010-02-19 17:02:12 -08004602 doRestore = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004604 }
Christopher Tate1bb69062010-02-19 17:02:12 -08004605
4606 if (!doRestore) {
4607 // No restore possible, or the Backup Manager was mysteriously not
4608 // available -- just fire the post-install work request directly.
4609 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
4610 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
4611 mHandler.sendMessage(msg);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004613 }
4614 });
4615 }
4616
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004617 abstract class HandlerParams {
4618 final static int MAX_RETRIES = 4;
4619 int retry = 0;
4620 final void startCopy() {
4621 try {
4622 if (DEBUG_SD_INSTALL) Log.i(TAG, "startCopy");
4623 retry++;
4624 if (retry > MAX_RETRIES) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004625 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004626 mHandler.sendEmptyMessage(MCS_GIVE_UP);
4627 handleServiceError();
4628 return;
4629 } else {
4630 handleStartCopy();
4631 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_UNBIND");
4632 mHandler.sendEmptyMessage(MCS_UNBIND);
4633 }
4634 } catch (RemoteException e) {
4635 if (DEBUG_SD_INSTALL) Log.i(TAG, "Posting install MCS_RECONNECT");
4636 mHandler.sendEmptyMessage(MCS_RECONNECT);
4637 }
4638 handleReturnCode();
4639 }
4640
4641 final void serviceError() {
4642 if (DEBUG_SD_INSTALL) Log.i(TAG, "serviceError");
4643 handleServiceError();
4644 handleReturnCode();
4645 }
4646 abstract void handleStartCopy() throws RemoteException;
4647 abstract void handleServiceError();
4648 abstract void handleReturnCode();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004649 }
4650
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004651 class InstallParams extends HandlerParams {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004652 final IPackageInstallObserver observer;
4653 int flags;
4654 final Uri packageURI;
4655 final String installerPackageName;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004656 private InstallArgs mArgs;
4657 private int mRet;
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004658 InstallParams(Uri packageURI,
4659 IPackageInstallObserver observer, int flags,
4660 String installerPackageName) {
4661 this.packageURI = packageURI;
4662 this.flags = flags;
4663 this.observer = observer;
4664 this.installerPackageName = installerPackageName;
4665 }
4666
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004667 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
4668 String packageName = pkgLite.packageName;
4669 int installLocation = pkgLite.installLocation;
4670 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
4671 synchronized (mPackages) {
4672 PackageParser.Package pkg = mPackages.get(packageName);
4673 if (pkg != null) {
4674 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
4675 // Check for updated system application.
4676 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
4677 if (onSd) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004678 Slog.w(TAG, "Cannot install update to system app on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004679 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
4680 }
4681 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4682 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004683 if (onSd) {
4684 // Install flag overrides everything.
4685 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4686 }
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004687 // If current upgrade specifies particular preference
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004688 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
4689 // Application explicitly specified internal.
4690 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
4691 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
4692 // App explictly prefers external. Let policy decide
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004693 } else {
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004694 // Prefer previous location
Kenny Root85387d72010-08-26 10:13:11 -07004695 if (isExternal(pkg)) {
Suchi Amalapurapu90d8ee62010-03-18 11:38:35 -07004696 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4697 }
4698 return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004699 }
4700 }
4701 } else {
4702 // Invalid install. Return error code
4703 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
4704 }
4705 }
4706 }
4707 // All the special cases have been taken care of.
4708 // Return result based on recommended install location.
4709 if (onSd) {
4710 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
4711 }
4712 return pkgLite.recommendedInstallLocation;
4713 }
4714
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004715 /*
4716 * Invoke remote method to get package information and install
4717 * location values. Override install location based on default
4718 * policy if needed and then create install arguments based
4719 * on the install location.
4720 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004721 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu1f9e1b42010-02-26 13:14:31 -08004722 int ret = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004723 boolean fwdLocked = (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
4724 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004725 boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
4726 if (onInt && onSd) {
4727 // Check if both bits are set.
4728 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
4729 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4730 } else if (fwdLocked && onSd) {
4731 // Check for forward locked apps
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004732 Slog.w(TAG, "Cannot install fwd locked apps on sdcard");
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004733 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004734 } else {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004735 // Remote call to find out default install location
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004736 PackageInfoLite pkgLite = mContainerService.getMinimalPackageInfo(packageURI, flags);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004737 int loc = pkgLite.recommendedInstallLocation;
Suchi Amalapurapua2b6c372010-03-05 17:40:11 -08004738 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION){
4739 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
4740 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS){
4741 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
4742 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004743 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4744 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
4745 ret = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004746 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
4747 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004748 } else {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004749 // Override with defaults if needed.
4750 loc = installLocationPolicy(pkgLite, flags);
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004751 if (!onSd && !onInt) {
4752 // Override install location with flags
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004753 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
4754 // Set the flag to install on external media.
4755 flags |= PackageManager.INSTALL_EXTERNAL;
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004756 flags &= ~PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004757 } else {
4758 // Make sure the flag for installing on external
4759 // media is unset
Suchi Amalapurapu14b6abd2010-03-17 08:37:04 -07004760 flags |= PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004761 flags &= ~PackageManager.INSTALL_EXTERNAL;
4762 }
4763 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004764 }
4765 }
4766 // Create the file args now.
4767 mArgs = createInstallArgs(this);
4768 if (ret == PackageManager.INSTALL_SUCCEEDED) {
4769 // Create copy only if we are not in an erroneous state.
4770 // Remote call to initiate copy using temporary file
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004771 ret = mArgs.copyApk(mContainerService, true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004772 }
4773 mRet = ret;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004774 }
4775
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004776 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004777 void handleReturnCode() {
Kenny Root6f89fa02010-07-30 16:33:47 -07004778 // If mArgs is null, then MCS couldn't be reached. When it
4779 // reconnects, it will try again to install. At that point, this
4780 // will succeed.
4781 if (mArgs != null) {
4782 processPendingInstall(mArgs, mRet);
4783 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004784 }
4785
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004786 @Override
4787 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004788 mArgs = createInstallArgs(this);
4789 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004790 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004791 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004792
4793 /*
4794 * Utility class used in movePackage api.
4795 * srcArgs and targetArgs are not set for invalid flags and make
4796 * sure to do null checks when invoking methods on them.
4797 * We probably want to return ErrorPrams for both failed installs
4798 * and moves.
4799 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004800 class MoveParams extends HandlerParams {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004801 final IPackageMoveObserver observer;
4802 final int flags;
4803 final String packageName;
4804 final InstallArgs srcArgs;
4805 final InstallArgs targetArgs;
4806 int mRet;
Kenny Root85387d72010-08-26 10:13:11 -07004807
4808 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
4809 String packageName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004810 this.srcArgs = srcArgs;
4811 this.observer = observer;
4812 this.flags = flags;
4813 this.packageName = packageName;
4814 if (srcArgs != null) {
4815 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
Kenny Root85387d72010-08-26 10:13:11 -07004816 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004817 } else {
4818 targetArgs = null;
4819 }
4820 }
4821
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004822 public void handleStartCopy() throws RemoteException {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004823 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4824 // Check for storage space on target medium
4825 if (!targetArgs.checkFreeStorage(mContainerService)) {
4826 Log.w(TAG, "Insufficient storage to install");
4827 return;
4828 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004829 // Create the file args now.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004830 mRet = targetArgs.copyApk(mContainerService, false);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004831 targetArgs.doPreInstall(mRet);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004832 if (DEBUG_SD_INSTALL) {
4833 StringBuilder builder = new StringBuilder();
4834 if (srcArgs != null) {
4835 builder.append("src: ");
4836 builder.append(srcArgs.getCodePath());
4837 }
4838 if (targetArgs != null) {
4839 builder.append(" target : ");
4840 builder.append(targetArgs.getCodePath());
4841 }
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004842 Log.i(TAG, builder.toString());
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004843 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004844 }
4845
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004846 @Override
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004847 void handleReturnCode() {
4848 targetArgs.doPostInstall(mRet);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004849 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
4850 if (mRet == PackageManager.INSTALL_SUCCEEDED) {
4851 currentStatus = PackageManager.MOVE_SUCCEEDED;
4852 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
4853 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
4854 }
4855 processPendingMove(this, currentStatus);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004856 }
4857
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004858 @Override
4859 void handleServiceError() {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004860 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004861 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004862 }
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004863
4864 private InstallArgs createInstallArgs(InstallParams params) {
4865 if (installOnSd(params.flags)) {
4866 return new SdInstallArgs(params);
4867 } else {
4868 return new FileInstallArgs(params);
4869 }
4870 }
4871
Kenny Root85387d72010-08-26 10:13:11 -07004872 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
4873 String nativeLibraryPath) {
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004874 if (installOnSd(flags)) {
Kenny Root85387d72010-08-26 10:13:11 -07004875 return new SdInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004876 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004877 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004878 }
4879 }
4880
Kenny Root85387d72010-08-26 10:13:11 -07004881 // Used by package mover
4882 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004883 if (installOnSd(flags)) {
4884 String cid = getNextCodePath(null, pkgName, "/" + SdInstallArgs.RES_FILE_NAME);
4885 return new SdInstallArgs(packageURI, cid);
4886 } else {
Kenny Root85387d72010-08-26 10:13:11 -07004887 return new FileInstallArgs(packageURI, pkgName, dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004888 }
4889 }
4890
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004891 static abstract class InstallArgs {
4892 final IPackageInstallObserver observer;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004893 // Always refers to PackageManager flags only
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004894 final int flags;
4895 final Uri packageURI;
4896 final String installerPackageName;
4897
4898 InstallArgs(Uri packageURI,
4899 IPackageInstallObserver observer, int flags,
4900 String installerPackageName) {
4901 this.packageURI = packageURI;
4902 this.flags = flags;
4903 this.observer = observer;
4904 this.installerPackageName = installerPackageName;
4905 }
4906
4907 abstract void createCopyFile();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004908 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004909 abstract int doPreInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004910 abstract boolean doRename(int status, String pkgName, String oldCodePath);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004911 abstract int doPostInstall(int status);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004912 abstract String getCodePath();
4913 abstract String getResourcePath();
Kenny Root85387d72010-08-26 10:13:11 -07004914 abstract String getNativeLibraryPath();
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004915 // Need installer lock especially for dex file removal.
4916 abstract void cleanUpResourcesLI();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004917 abstract boolean doPostDeleteLI(boolean delete);
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004918 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004919 }
4920
4921 class FileInstallArgs extends InstallArgs {
4922 File installDir;
4923 String codeFileName;
4924 String resourceFileName;
Kenny Root85387d72010-08-26 10:13:11 -07004925 String libraryPath;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004926 boolean created = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004927
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004928 FileInstallArgs(InstallParams params) {
4929 super(params.packageURI, params.observer,
4930 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004931 }
4932
Kenny Root85387d72010-08-26 10:13:11 -07004933 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004934 super(null, null, 0, null);
4935 File codeFile = new File(fullCodePath);
4936 installDir = codeFile.getParentFile();
4937 codeFileName = fullCodePath;
4938 resourceFileName = fullResourcePath;
Kenny Root85387d72010-08-26 10:13:11 -07004939 libraryPath = nativeLibraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004940 }
4941
Kenny Root85387d72010-08-26 10:13:11 -07004942 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004943 super(packageURI, null, 0, null);
Kenny Root85387d72010-08-26 10:13:11 -07004944 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004945 String apkName = getNextCodePath(null, pkgName, ".apk");
4946 codeFileName = new File(installDir, apkName + ".apk").getPath();
4947 resourceFileName = getResourcePathFromCodePath();
Kenny Root85387d72010-08-26 10:13:11 -07004948 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004949 }
4950
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08004951 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
4952 return imcs.checkFreeStorage(false, packageURI);
4953 }
4954
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08004955 String getCodePath() {
4956 return codeFileName;
4957 }
4958
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004959 void createCopyFile() {
Kenny Root85387d72010-08-26 10:13:11 -07004960 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004961 codeFileName = createTempPackageFile(installDir).getPath();
4962 resourceFileName = getResourcePathFromCodePath();
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004963 created = true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004964 }
4965
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08004966 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004967 if (temp) {
4968 // Generate temp file name
4969 createCopyFile();
4970 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004971 // Get a ParcelFileDescriptor to write to the output file
4972 File codeFile = new File(codeFileName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004973 if (!created) {
4974 try {
4975 codeFile.createNewFile();
4976 // Set permissions
4977 if (!setPermissions()) {
4978 // Failed setting permissions.
4979 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4980 }
4981 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004982 Slog.w(TAG, "Failed to create file " + codeFile);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08004983 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4984 }
4985 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004986 ParcelFileDescriptor out = null;
4987 try {
Kenny Root85387d72010-08-26 10:13:11 -07004988 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004989 } catch (FileNotFoundException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08004990 Slog.e(TAG, "Failed to create file descritpor for : " + codeFileName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004991 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4992 }
4993 // Copy the resource now
4994 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4995 try {
4996 if (imcs.copyResource(packageURI, out)) {
4997 ret = PackageManager.INSTALL_SUCCEEDED;
4998 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08004999 } finally {
5000 try { if (out != null) out.close(); } catch (IOException e) {}
5001 }
Kenny Root85387d72010-08-26 10:13:11 -07005002
5003 if (!temp) {
5004 NativeLibraryHelper.copyNativeBinariesLI(codeFile, new File(libraryPath));
5005 }
5006
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005007 return ret;
5008 }
5009
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005010 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005011 if (status != PackageManager.INSTALL_SUCCEEDED) {
5012 cleanUp();
5013 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005014 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005015 }
5016
5017 boolean doRename(int status, final String pkgName, String oldCodePath) {
5018 if (status != PackageManager.INSTALL_SUCCEEDED) {
5019 cleanUp();
5020 return false;
5021 } else {
5022 // Rename based on packageName
5023 File codeFile = new File(getCodePath());
5024 String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
5025 File desFile = new File(installDir, apkName + ".apk");
5026 if (!codeFile.renameTo(desFile)) {
5027 return false;
5028 }
5029 // Reset paths since the file has been renamed.
5030 codeFileName = desFile.getPath();
5031 resourceFileName = getResourcePathFromCodePath();
5032 // Set permissions
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005033 if (!setPermissions()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005034 // Failed setting permissions.
5035 return false;
5036 }
5037 return true;
5038 }
5039 }
5040
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005041 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005042 if (status != PackageManager.INSTALL_SUCCEEDED) {
5043 cleanUp();
5044 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005045 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005046 }
5047
5048 String getResourcePath() {
5049 return resourceFileName;
5050 }
5051
5052 String getResourcePathFromCodePath() {
5053 String codePath = getCodePath();
5054 if ((flags & PackageManager.INSTALL_FORWARD_LOCK) != 0) {
5055 String apkNameOnly = getApkName(codePath);
5056 return mAppInstallDir.getPath() + "/" + apkNameOnly + ".zip";
5057 } else {
5058 return codePath;
5059 }
5060 }
5061
Kenny Root85387d72010-08-26 10:13:11 -07005062 @Override
5063 String getNativeLibraryPath() {
5064 return libraryPath;
5065 }
5066
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005067 private boolean cleanUp() {
5068 boolean ret = true;
5069 String sourceDir = getCodePath();
5070 String publicSourceDir = getResourcePath();
5071 if (sourceDir != null) {
5072 File sourceFile = new File(sourceDir);
5073 if (!sourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005074 Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005075 ret = false;
5076 }
5077 // Delete application's code and resources
5078 sourceFile.delete();
5079 }
5080 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
5081 final File publicSourceFile = new File(publicSourceDir);
5082 if (!publicSourceFile.exists()) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005083 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005084 }
5085 if (publicSourceFile.exists()) {
5086 publicSourceFile.delete();
5087 }
5088 }
5089 return ret;
5090 }
5091
5092 void cleanUpResourcesLI() {
5093 String sourceDir = getCodePath();
5094 if (cleanUp() && mInstaller != null) {
5095 int retCode = mInstaller.rmdex(sourceDir);
5096 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005097 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005098 + " at location "
5099 + sourceDir + ", retcode=" + retCode);
5100 // we don't consider this to be a failure of the core package deletion
5101 }
5102 }
Kenny Root85387d72010-08-26 10:13:11 -07005103 if (libraryPath != null) {
Kenny Root8f7cc022010-09-12 09:04:56 -07005104 NativeLibraryHelper.removeNativeBinariesLI(libraryPath);
Kenny Root85387d72010-08-26 10:13:11 -07005105 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005106 }
5107
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005108 private boolean setPermissions() {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005109 // TODO Do this in a more elegant way later on. for now just a hack
Kenny Root85387d72010-08-26 10:13:11 -07005110 if (!isFwdLocked()) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005111 final int filePermissions =
5112 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
5113 |FileUtils.S_IROTH;
5114 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
5115 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005116 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005117 getCodePath()
5118 + ". The return code was: " + retCode);
5119 // TODO Define new internal error
5120 return false;
5121 }
5122 return true;
5123 }
5124 return true;
5125 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005126
5127 boolean doPostDeleteLI(boolean delete) {
Kenny Root85387d72010-08-26 10:13:11 -07005128 // XXX err, shouldn't we respect the delete flag?
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005129 cleanUpResourcesLI();
5130 return true;
5131 }
Kenny Root85387d72010-08-26 10:13:11 -07005132
5133 private boolean isFwdLocked() {
5134 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
5135 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005136 }
5137
5138 class SdInstallArgs extends InstallArgs {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005139 static final String RES_FILE_NAME = "pkg.apk";
5140
Kenny Root85387d72010-08-26 10:13:11 -07005141 String cid;
5142 String packagePath;
5143 String libraryPath;
5144
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005145 SdInstallArgs(InstallParams params) {
5146 super(params.packageURI, params.observer,
5147 params.flags, params.installerPackageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005148 }
5149
Kenny Root85387d72010-08-26 10:13:11 -07005150 SdInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005151 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005152 // Extract cid from fullCodePath
5153 int eidx = fullCodePath.lastIndexOf("/");
5154 String subStr1 = fullCodePath.substring(0, eidx);
5155 int sidx = subStr1.lastIndexOf("/");
5156 cid = subStr1.substring(sidx+1, eidx);
Kenny Root85387d72010-08-26 10:13:11 -07005157 setCachePath(subStr1);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005158 }
5159
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005160 SdInstallArgs(String cid) {
Dianne Hackbornaa77de12010-05-14 22:33:54 -07005161 super(null, null, PackageManager.INSTALL_EXTERNAL, null);
5162 this.cid = cid;
Kenny Root85387d72010-08-26 10:13:11 -07005163 setCachePath(PackageHelper.getSdDir(cid));
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005164 }
5165
5166 SdInstallArgs(Uri packageURI, String cid) {
5167 super(packageURI, null, PackageManager.INSTALL_EXTERNAL, null);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005168 this.cid = cid;
5169 }
5170
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005171 void createCopyFile() {
5172 cid = getTempContainerId();
5173 }
5174
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08005175 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
5176 return imcs.checkFreeStorage(true, packageURI);
5177 }
5178
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005179 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005180 if (temp) {
5181 createCopyFile();
5182 }
Kenny Root85387d72010-08-26 10:13:11 -07005183 String newCachePath = imcs.copyResourceToContainer(
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005184 packageURI, cid,
5185 getEncryptKey(), RES_FILE_NAME);
Kenny Root85387d72010-08-26 10:13:11 -07005186 if (newCachePath != null) {
5187 setCachePath(newCachePath);
5188 return PackageManager.INSTALL_SUCCEEDED;
5189 } else {
5190 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5191 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005192 }
5193
5194 @Override
5195 String getCodePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005196 return packagePath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005197 }
5198
5199 @Override
5200 String getResourcePath() {
Kenny Root85387d72010-08-26 10:13:11 -07005201 return packagePath;
5202 }
5203
5204 @Override
5205 String getNativeLibraryPath() {
5206 return libraryPath;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005207 }
5208
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005209 int doPreInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005210 if (status != PackageManager.INSTALL_SUCCEEDED) {
5211 // Destroy container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005212 PackageHelper.destroySdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005213 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005214 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005215 if (!mounted) {
Kenny Root85387d72010-08-26 10:13:11 -07005216 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
5217 Process.SYSTEM_UID);
5218 if (newCachePath != null) {
5219 setCachePath(newCachePath);
5220 } else {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005221 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
5222 }
5223 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005224 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005225 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005226 }
5227
5228 boolean doRename(int status, final String pkgName,
5229 String oldCodePath) {
5230 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005231 String newCachePath = null;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005232 if (PackageHelper.isContainerMounted(cid)) {
5233 // Unmount the container
5234 if (!PackageHelper.unMountSdDir(cid)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005235 Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005236 return false;
5237 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005238 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005239 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
Suchi Amalapurapuc7537ee2010-03-24 09:27:19 -07005240 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
5241 " which might be stale. Will try to clean up.");
5242 // Clean up the stale container and proceed to recreate.
5243 if (!PackageHelper.destroySdDir(newCacheId)) {
5244 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
5245 return false;
5246 }
5247 // Successfully cleaned up stale container. Try to rename again.
5248 if (!PackageHelper.renameSdDir(cid, newCacheId)) {
5249 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
5250 + " inspite of cleaning it up.");
5251 return false;
5252 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005253 }
5254 if (!PackageHelper.isContainerMounted(newCacheId)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005255 Slog.w(TAG, "Mounting container " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005256 newCachePath = PackageHelper.mountSdDir(newCacheId,
5257 getEncryptKey(), Process.SYSTEM_UID);
5258 } else {
5259 newCachePath = PackageHelper.getSdDir(newCacheId);
5260 }
5261 if (newCachePath == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005262 Slog.w(TAG, "Failed to get cache path for " + newCacheId);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005263 return false;
5264 }
5265 Log.i(TAG, "Succesfully renamed " + cid +
Kenny Root85387d72010-08-26 10:13:11 -07005266 " to " + newCacheId +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005267 " at new path: " + newCachePath);
5268 cid = newCacheId;
Kenny Root85387d72010-08-26 10:13:11 -07005269 setCachePath(newCachePath);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08005270 return true;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005271 }
5272
Kenny Root85387d72010-08-26 10:13:11 -07005273 private void setCachePath(String newCachePath) {
5274 File cachePath = new File(newCachePath);
5275 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
5276 packagePath = new File(cachePath, RES_FILE_NAME).getPath();
5277 }
5278
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005279 int doPostInstall(int status) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005280 if (status != PackageManager.INSTALL_SUCCEEDED) {
5281 cleanUp();
5282 } else {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005283 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005284 if (!mounted) {
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005285 PackageHelper.mountSdDir(cid,
5286 getEncryptKey(), Process.myUid());
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005287 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005288 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005289 return status;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005290 }
5291
5292 private void cleanUp() {
5293 // Destroy secure container
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005294 PackageHelper.destroySdDir(cid);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005295 }
5296
5297 void cleanUpResourcesLI() {
5298 String sourceFile = getCodePath();
5299 // Remove dex file
5300 if (mInstaller != null) {
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005301 int retCode = mInstaller.rmdex(sourceFile);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005302 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005303 Slog.w(TAG, "Couldn't remove dex file for package: "
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005304 + " at location "
5305 + sourceFile.toString() + ", retcode=" + retCode);
5306 // we don't consider this to be a failure of the core package deletion
5307 }
5308 }
5309 cleanUp();
5310 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005311
5312 boolean matchContainer(String app) {
5313 if (cid.startsWith(app)) {
5314 return true;
5315 }
5316 return false;
5317 }
5318
5319 String getPackageName() {
5320 int idx = cid.lastIndexOf("-");
5321 if (idx == -1) {
5322 return cid;
5323 }
5324 return cid.substring(0, idx);
5325 }
5326
5327 boolean doPostDeleteLI(boolean delete) {
5328 boolean ret = false;
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005329 boolean mounted = PackageHelper.isContainerMounted(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005330 if (mounted) {
5331 // Unmount first
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08005332 ret = PackageHelper.unMountSdDir(cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005333 }
5334 if (ret && delete) {
5335 cleanUpResourcesLI();
5336 }
5337 return ret;
5338 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005339 };
5340
5341 // Utility method used to create code paths based on package name and available index.
5342 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
5343 String idxStr = "";
5344 int idx = 1;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005345 // Fall back to default value of idx=1 if prefix is not
5346 // part of oldCodePath
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005347 if (oldCodePath != null) {
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005348 String subStr = oldCodePath;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005349 // Drop the suffix right away
Bjorn Bringert5fd5bfe2010-01-29 12:11:30 +00005350 if (subStr.endsWith(suffix)) {
5351 subStr = subStr.substring(0, subStr.length() - suffix.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005352 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005353 // If oldCodePath already contains prefix find out the
5354 // ending index to either increment or decrement.
5355 int sidx = subStr.lastIndexOf(prefix);
5356 if (sidx != -1) {
5357 subStr = subStr.substring(sidx + prefix.length());
5358 if (subStr != null) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005359 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
5360 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005361 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08005362 try {
5363 idx = Integer.parseInt(subStr);
5364 if (idx <= 1) {
5365 idx++;
5366 } else {
5367 idx--;
5368 }
5369 } catch(NumberFormatException e) {
5370 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005371 }
5372 }
5373 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005374 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005375 return prefix + idxStr;
5376 }
5377
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005378 // Utility method used to ignore ADD/REMOVE events
5379 // by directory observer.
5380 private static boolean ignoreCodePath(String fullPathStr) {
5381 String apkName = getApkName(fullPathStr);
5382 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
5383 if (idx != -1 && ((idx+1) < apkName.length())) {
5384 // Make sure the package ends with a numeral
5385 String version = apkName.substring(idx+1);
5386 try {
5387 Integer.parseInt(version);
5388 return true;
5389 } catch (NumberFormatException e) {}
5390 }
5391 return false;
5392 }
5393
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005394 // Utility method that returns the relative package path with respect
5395 // to the installation directory. Like say for /data/data/com.test-1.apk
5396 // string com.test-1 is returned.
5397 static String getApkName(String codePath) {
5398 if (codePath == null) {
5399 return null;
5400 }
5401 int sidx = codePath.lastIndexOf("/");
5402 int eidx = codePath.lastIndexOf(".");
5403 if (eidx == -1) {
5404 eidx = codePath.length();
5405 } else if (eidx == 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005406 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005407 return null;
5408 }
5409 return codePath.substring(sidx+1, eidx);
5410 }
5411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005412 class PackageInstalledInfo {
5413 String name;
5414 int uid;
5415 PackageParser.Package pkg;
5416 int returnCode;
5417 PackageRemovedInfo removedInfo;
5418 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005420 /*
5421 * Install a non-existing package.
5422 */
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005423 private void installNewPackageLI(PackageParser.Package pkg,
5424 int parseFlags,
5425 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005426 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005427 // Remember this for later, in case we need to rollback this install
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005428 String pkgName = pkg.packageName;
Oscar Montemayora8529f62009-11-18 10:14:20 -08005429
Suchi Amalapurapud32c8022010-03-04 17:18:14 -08005430 boolean dataDirExists = getDataPathForPackage(pkg).exists();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005431 res.name = pkgName;
5432 synchronized(mPackages) {
Dianne Hackborne259bc72010-03-30 19:24:44 -07005433 if (mSettings.mRenamedPackages.containsKey(pkgName)) {
5434 // A package with the same name is already installed, though
5435 // it has been renamed to an older name. The package we
5436 // are trying to install should be installed as an update to
5437 // the existing one, but that has not been requested, so bail.
5438 Slog.w(TAG, "Attempt to re-install " + pkgName
5439 + " without first uninstalling package running as "
5440 + mSettings.mRenamedPackages.get(pkgName));
5441 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5442 return;
5443 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005444 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005445 // Don't allow installation over an existing package with the same name.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005446 Slog.w(TAG, "Attempt to re-install " + pkgName
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005447 + " without first uninstalling.");
5448 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
5449 return;
5450 }
5451 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005452 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005453 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005454 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005455 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005456 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5457 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5458 }
5459 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005460 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005461 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005462 res);
5463 // delete the partially installed application. the data directory will have to be
5464 // restored if it was already existing
5465 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
5466 // remove package from internal structures. Note that we want deletePackageX to
5467 // delete the package data and cache directories that it created in
5468 // scanPackageLocked, unless those directories existed before we even tried to
5469 // install.
5470 deletePackageLI(
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005471 pkgName, false,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005472 dataDirExists ? PackageManager.DONT_DELETE_DATA : 0,
5473 res.removedInfo);
5474 }
5475 }
5476 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005477
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005478 private void replacePackageLI(PackageParser.Package pkg,
5479 int parseFlags,
5480 int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005481 String installerPackageName, PackageInstalledInfo res) {
5482
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005483 PackageParser.Package oldPackage;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005484 String pkgName = pkg.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005485 // First find the old package info and check signatures
5486 synchronized(mPackages) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07005487 oldPackage = mPackages.get(pkgName);
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005488 if (checkSignaturesLP(oldPackage.mSignatures, pkg.mSignatures)
Dianne Hackborn766cbfe2009-08-12 18:33:39 -07005489 != PackageManager.SIGNATURE_MATCH) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005490 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5491 return;
5492 }
5493 }
Kenny Root85387d72010-08-26 10:13:11 -07005494 boolean sysPkg = (isSystemApp(oldPackage));
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005495 if (sysPkg) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005496 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005497 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005498 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005499 }
5500 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005501
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005502 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005503 PackageParser.Package pkg,
5504 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005505 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005506 PackageParser.Package newPackage = null;
5507 String pkgName = deletedPackage.packageName;
5508 boolean deletedPkg = true;
5509 boolean updatedSettings = false;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005510
Jacek Surazski65e13172009-04-28 15:26:38 +02005511 String oldInstallerPackageName = null;
5512 synchronized (mPackages) {
5513 oldInstallerPackageName = mSettings.getInstallerPackageName(pkgName);
5514 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005516 // First delete the existing package while retaining the data directory
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005517 if (!deletePackageLI(pkgName, true, PackageManager.DONT_DELETE_DATA,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005518 res.removedInfo)) {
5519 // If the existing package was'nt successfully deleted
5520 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5521 deletedPkg = false;
5522 } else {
5523 // Successfully deleted the old package. Now proceed with re-installation
5524 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005525 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005526 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005527 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005528 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5529 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
Suchi Amalapurapu110fea72010-01-14 17:50:23 -08005530 }
5531 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005532 updateSettingsLI(newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005533 installerPackageName,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005534 res);
5535 updatedSettings = true;
5536 }
5537 }
5538
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005539 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005540 // remove package from internal structures. Note that we want deletePackageX to
5541 // delete the package data and cache directories that it created in
5542 // scanPackageLocked, unless those directories existed before we even tried to
5543 // install.
5544 if(updatedSettings) {
5545 deletePackageLI(
5546 pkgName, true,
5547 PackageManager.DONT_DELETE_DATA,
5548 res.removedInfo);
5549 }
5550 // Since we failed to install the new package we need to restore the old
5551 // package that we deleted.
5552 if(deletedPkg) {
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005553 File restoreFile = new File(deletedPackage.mPath);
5554 if (restoreFile == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005555 Slog.e(TAG, "Failed allocating storage when restoring pkg : " + pkgName);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005556 return;
5557 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005558 // Parse old package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005559 boolean oldOnSd = isExternal(deletedPackage);
5560 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY |
5561 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5562 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
5563 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE;
5564 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode) == null) {
5565 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
5566 return;
5567 }
5568 // Restore of old package succeeded. Update permissions.
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005569 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005570 updatePermissionsLP(deletedPackage.packageName, deletedPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005571 true, false, false);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005572 mSettings.writeLP();
5573 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005574 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005575 }
5576 }
5577 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005579 private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005580 PackageParser.Package pkg,
5581 int parseFlags, int scanMode,
Jacek Surazski65e13172009-04-28 15:26:38 +02005582 String installerPackageName, PackageInstalledInfo res) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005583 PackageParser.Package newPackage = null;
5584 boolean updatedSettings = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005585 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005586 PackageParser.PARSE_IS_SYSTEM;
5587 String packageName = deletedPackage.packageName;
5588 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
5589 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005590 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005591 return;
5592 }
5593 PackageParser.Package oldPkg;
5594 PackageSetting oldPkgSetting;
5595 synchronized (mPackages) {
5596 oldPkg = mPackages.get(packageName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005597 oldPkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598 if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
5599 (oldPkgSetting == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005600 Slog.w(TAG, "Couldn't find package:"+packageName+" information");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005601 return;
5602 }
5603 }
5604 res.removedInfo.uid = oldPkg.applicationInfo.uid;
5605 res.removedInfo.removedPackage = packageName;
5606 // Remove existing system package
5607 removePackageLI(oldPkg, true);
5608 synchronized (mPackages) {
5609 res.removedInfo.removedUid = mSettings.disableSystemPackageLP(packageName);
5610 }
5611
5612 // Successfully disabled the old package. Now proceed with re-installation
5613 mLastScanError = PackageManager.INSTALL_SUCCEEDED;
5614 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005615 newPackage = scanPackageLI(pkg, parseFlags, scanMode);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005616 if (newPackage == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005617 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005618 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
5619 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
5620 }
5621 } else {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005622 updateSettingsLI(newPackage, installerPackageName, res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005623 updatedSettings = true;
5624 }
5625
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005626 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005627 // Re installation failed. Restore old information
5628 // Remove new pkg information
Dianne Hackborn62da8462009-05-13 15:06:13 -07005629 if (newPackage != null) {
5630 removePackageLI(newPackage, true);
5631 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005632 // Add back the old system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005633 scanPackageLI(oldPkg, parseFlags,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005634 SCAN_MONITOR
The Android Open Source Project10592532009-03-18 17:39:46 -07005635 | SCAN_UPDATE_SIGNATURE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005636 // Restore the old system information in Settings
5637 synchronized(mPackages) {
5638 if(updatedSettings) {
5639 mSettings.enableSystemPackageLP(packageName);
Jacek Surazski65e13172009-04-28 15:26:38 +02005640 mSettings.setInstallerPackageName(packageName,
5641 oldPkgSetting.installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005642 }
5643 mSettings.writeLP();
5644 }
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005645 } else {
5646 // If this is an update to an existing update, setup
5647 // to remove the existing update.
5648 synchronized (mPackages) {
5649 PackageSetting ps = mSettings.getDisabledSystemPkg(packageName);
5650 if (ps != null && ps.codePathString != null &&
5651 !ps.codePathString.equals(oldPkgSetting.codePathString)) {
5652 int installFlags = 0;
5653 res.removedInfo.args = createInstallArgs(0, oldPkgSetting.codePathString,
Kenny Root85387d72010-08-26 10:13:11 -07005654 oldPkgSetting.resourcePathString, oldPkgSetting.nativeLibraryPathString);
Suchi Amalapurapuc1d07d92010-05-05 13:37:12 -07005655 }
5656 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005657 }
5658 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005659
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005660 // Utility method used to move dex files during install.
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005661 private int moveDexFilesLI(PackageParser.Package newPackage) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005662 int retCode;
5663 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
5664 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath);
5665 if (retCode != 0) {
Kenny Roote2f74172010-08-04 13:35:33 -07005666 if (mNoDexOpt) {
5667 /*
5668 * If we're in an engineering build, programs are lazily run
5669 * through dexopt. If the .dex file doesn't exist yet, it
5670 * will be created when the program is run next.
5671 */
5672 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath);
5673 } else {
5674 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath);
5675 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5676 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005677 }
5678 }
5679 return PackageManager.INSTALL_SUCCEEDED;
5680 }
5681
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005682 private void updateSettingsLI(PackageParser.Package newPackage,
Jacek Surazski65e13172009-04-28 15:26:38 +02005683 String installerPackageName, PackageInstalledInfo res) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005684 String pkgName = newPackage.packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005685 synchronized (mPackages) {
5686 //write settings. the installStatus will be incomplete at this stage.
5687 //note that the new package setting would have already been
5688 //added to mPackages. It hasn't been persisted yet.
5689 mSettings.setInstallStatus(pkgName, PKG_INSTALL_INCOMPLETE);
5690 mSettings.writeLP();
5691 }
5692
Suchi Amalapurapuf7f5dda2010-03-23 10:34:28 -07005693 if ((res.returnCode = moveDexFilesLI(newPackage))
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005694 != PackageManager.INSTALL_SUCCEEDED) {
5695 // Discontinue if moving dex files failed.
5696 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005697 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08005698 if((res.returnCode = setPermissionsLI(newPackage))
5699 != PackageManager.INSTALL_SUCCEEDED) {
5700 if (mInstaller != null) {
5701 mInstaller.rmdex(newPackage.mScanPath);
5702 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005703 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005704 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005705 Log.d(TAG, "New package installed in " + newPackage.mPath);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005706 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005707 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07005708 updatePermissionsLP(newPackage.packageName, newPackage,
Dianne Hackborn92cfa102010-04-28 11:00:44 -07005709 newPackage.permissions.size() > 0, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005710 res.name = pkgName;
5711 res.uid = newPackage.applicationInfo.uid;
5712 res.pkg = newPackage;
5713 mSettings.setInstallStatus(pkgName, PKG_INSTALL_COMPLETE);
Jacek Surazski65e13172009-04-28 15:26:38 +02005714 mSettings.setInstallerPackageName(pkgName, installerPackageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005715 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5716 //to update install status
5717 mSettings.writeLP();
5718 }
5719 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005720
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005721 private void installPackageLI(InstallArgs args,
5722 boolean newInstall, PackageInstalledInfo res) {
5723 int pFlags = args.flags;
5724 String installerPackageName = args.installerPackageName;
5725 File tmpPackageFile = new File(args.getCodePath());
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005726 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
Suchi Amalapurapu5b993ce2010-02-12 09:43:29 -08005727 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005728 boolean replace = false;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005729 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005730 | (newInstall ? SCAN_NEW_INSTALL : 0);
Suchi Amalapurapuee5ece42009-09-15 13:41:47 -07005731 // Result object to be returned
5732 res.returnCode = PackageManager.INSTALL_SUCCEEDED;
5733
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005734 // Retrieve PackageSettings and parse package
5735 int parseFlags = PackageParser.PARSE_CHATTY |
5736 (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) |
5737 (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
5738 parseFlags |= mDefParseFlags;
5739 PackageParser pp = new PackageParser(tmpPackageFile.getPath());
5740 pp.setSeparateProcesses(mSeparateProcesses);
5741 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
5742 null, mMetrics, parseFlags);
5743 if (pkg == null) {
5744 res.returnCode = pp.getParseError();
5745 return;
5746 }
5747 String pkgName = res.name = pkg.packageName;
5748 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
5749 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
5750 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
5751 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005752 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005753 }
5754 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) {
5755 res.returnCode = pp.getParseError();
5756 return;
5757 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005758 // Get rid of all references to package scan path via parser.
5759 pp = null;
5760 String oldCodePath = null;
5761 boolean systemApp = false;
5762 synchronized (mPackages) {
5763 // Check if installing already existing package
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005764 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5765 String oldName = mSettings.mRenamedPackages.get(pkgName);
Dianne Hackbornc1552392010-03-03 16:19:01 -08005766 if (pkg.mOriginalPackages != null
5767 && pkg.mOriginalPackages.contains(oldName)
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005768 && mPackages.containsKey(oldName)) {
5769 // This package is derived from an original package,
5770 // and this device has been updating from that original
5771 // name. We must continue using the original name, so
5772 // rename the new package here.
Dianne Hackbornc1552392010-03-03 16:19:01 -08005773 pkg.setPackageName(oldName);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005774 pkgName = pkg.packageName;
5775 replace = true;
5776 } else if (mPackages.containsKey(pkgName)) {
5777 // This package, under its official name, already exists
5778 // on the device; we should replace it.
5779 replace = true;
5780 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005781 }
5782 PackageSetting ps = mSettings.mPackages.get(pkgName);
5783 if (ps != null) {
5784 oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
5785 if (ps.pkg != null && ps.pkg.applicationInfo != null) {
5786 systemApp = (ps.pkg.applicationInfo.flags &
5787 ApplicationInfo.FLAG_SYSTEM) != 0;
Dianne Hackbornade3eca2009-05-11 18:54:45 -07005788 }
5789 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005790 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005791
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005792 if (systemApp && onSd) {
5793 // Disable updates to system apps on sdcard
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005794 Slog.w(TAG, "Cannot install updates to system apps on sdcard");
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005795 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
5796 return;
5797 }
Suchi Amalapurapucf6eaea2010-02-23 19:37:45 -08005798
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005799 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
5800 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5801 return;
5802 }
5803 // Set application objects path explicitly after the rename
5804 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
Kenny Root85387d72010-08-26 10:13:11 -07005805 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08005806 if (replace) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08005807 replacePackageLI(pkg, parseFlags, scanMode,
5808 installerPackageName, res);
5809 } else {
5810 installNewPackageLI(pkg, parseFlags, scanMode,
5811 installerPackageName,res);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005812 }
5813 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005814
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005815 private int setPermissionsLI(PackageParser.Package newPackage) {
5816 String pkgName = newPackage.packageName;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005817 int retCode = 0;
5818 // TODO Gross hack but fix later. Ideally move this to be a post installation
5819 // check after alloting uid.
Kenny Root85387d72010-08-26 10:13:11 -07005820 if (isForwardLocked(newPackage)) {
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005821 File destResourceFile = new File(newPackage.applicationInfo.publicSourceDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005822 try {
5823 extractPublicFiles(newPackage, destResourceFile);
5824 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005825 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 -08005826 " forward-locked app.");
5827 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5828 } finally {
5829 //TODO clean up the extracted public files
5830 }
5831 if (mInstaller != null) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005832 retCode = mInstaller.setForwardLockPerm(getApkName(newPackage.mPath),
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005833 newPackage.applicationInfo.uid);
5834 } else {
5835 final int filePermissions =
5836 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005837 retCode = FileUtils.setPermissions(newPackage.mPath, filePermissions, -1,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005838 newPackage.applicationInfo.uid);
5839 }
5840 } else {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005841 // The permissions on the resource file was set when it was copied for
5842 // non forward locked apps and apps on sdcard
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005843 }
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005845 if (retCode != 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005846 Slog.e(TAG, "Couldn't set new package file permissions for " +
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08005847 newPackage.mPath
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005848 + ". The return code was: " + retCode);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005849 // TODO Define new internal error
5850 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005851 }
5852 return PackageManager.INSTALL_SUCCEEDED;
5853 }
5854
Kenny Root85387d72010-08-26 10:13:11 -07005855 private static boolean isForwardLocked(PackageParser.Package pkg) {
5856 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005857 }
5858
Kenny Root85387d72010-08-26 10:13:11 -07005859 private static boolean isExternal(PackageParser.Package pkg) {
5860 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
5861 }
5862
5863 private static boolean isSystemApp(PackageParser.Package pkg) {
5864 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
5865 }
5866
5867 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
5868 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
Suchi Amalapurapuae181712010-03-30 14:01:02 -07005869 }
5870
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005871 private void extractPublicFiles(PackageParser.Package newPackage,
5872 File publicZipFile) throws IOException {
5873 final ZipOutputStream publicZipOutStream =
5874 new ZipOutputStream(new FileOutputStream(publicZipFile));
5875 final ZipFile privateZip = new ZipFile(newPackage.mPath);
5876
5877 // Copy manifest, resources.arsc and res directory to public zip
5878
5879 final Enumeration<? extends ZipEntry> privateZipEntries = privateZip.entries();
5880 while (privateZipEntries.hasMoreElements()) {
5881 final ZipEntry zipEntry = privateZipEntries.nextElement();
5882 final String zipEntryName = zipEntry.getName();
5883 if ("AndroidManifest.xml".equals(zipEntryName)
5884 || "resources.arsc".equals(zipEntryName)
5885 || zipEntryName.startsWith("res/")) {
5886 try {
5887 copyZipEntry(zipEntry, privateZip, publicZipOutStream);
5888 } catch (IOException e) {
5889 try {
5890 publicZipOutStream.close();
5891 throw e;
5892 } finally {
5893 publicZipFile.delete();
5894 }
5895 }
5896 }
5897 }
5898
5899 publicZipOutStream.close();
5900 FileUtils.setPermissions(
5901 publicZipFile.getAbsolutePath(),
5902 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP|FileUtils.S_IROTH,
5903 -1, -1);
5904 }
5905
5906 private static void copyZipEntry(ZipEntry zipEntry,
5907 ZipFile inZipFile,
5908 ZipOutputStream outZipStream) throws IOException {
5909 byte[] buffer = new byte[4096];
5910 int num;
5911
5912 ZipEntry newEntry;
5913 if (zipEntry.getMethod() == ZipEntry.STORED) {
5914 // Preserve the STORED method of the input entry.
5915 newEntry = new ZipEntry(zipEntry);
5916 } else {
5917 // Create a new entry so that the compressed len is recomputed.
5918 newEntry = new ZipEntry(zipEntry.getName());
5919 }
5920 outZipStream.putNextEntry(newEntry);
5921
5922 InputStream data = inZipFile.getInputStream(zipEntry);
5923 while ((num = data.read(buffer)) > 0) {
5924 outZipStream.write(buffer, 0, num);
5925 }
5926 outZipStream.flush();
5927 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005928
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005929 private void deleteTempPackageFiles() {
5930 FilenameFilter filter = new FilenameFilter() {
5931 public boolean accept(File dir, String name) {
5932 return name.startsWith("vmdl") && name.endsWith(".tmp");
5933 }
5934 };
5935 String tmpFilesList[] = mAppInstallDir.list(filter);
5936 if(tmpFilesList == null) {
5937 return;
5938 }
5939 for(int i = 0; i < tmpFilesList.length; i++) {
5940 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]);
5941 tmpFile.delete();
5942 }
5943 }
5944
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005945 private File createTempPackageFile(File installDir) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005946 File tmpPackageFile;
5947 try {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08005948 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005949 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005950 Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005951 return null;
5952 }
5953 try {
5954 FileUtils.setPermissions(
5955 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
5956 -1, -1);
5957 } catch (IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08005958 Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005959 return null;
5960 }
5961 return tmpPackageFile;
5962 }
5963
5964 public void deletePackage(final String packageName,
5965 final IPackageDeleteObserver observer,
5966 final int flags) {
5967 mContext.enforceCallingOrSelfPermission(
5968 android.Manifest.permission.DELETE_PACKAGES, null);
5969 // Queue up an async operation since the package deletion may take a little while.
5970 mHandler.post(new Runnable() {
5971 public void run() {
5972 mHandler.removeCallbacks(this);
5973 final boolean succeded = deletePackageX(packageName, true, true, flags);
5974 if (observer != null) {
5975 try {
5976 observer.packageDeleted(succeded);
5977 } catch (RemoteException e) {
5978 Log.i(TAG, "Observer no longer exists.");
5979 } //end catch
5980 } //end if
5981 } //end run
5982 });
5983 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005984
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005985 /**
5986 * This method is an internal method that could be get invoked either
5987 * to delete an installed package or to clean up a failed installation.
5988 * After deleting an installed package, a broadcast is sent to notify any
5989 * listeners that the package has been installed. For cleaning up a failed
Doug Zongkerab5c49c2009-12-04 10:31:43 -08005990 * installation, the broadcast is not necessary since the package's
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005991 * installation wouldn't have sent the initial broadcast either
5992 * The key steps in deleting a package are
5993 * deleting the package information in internal structures like mPackages,
5994 * deleting the packages base directories through installd
5995 * updating mSettings to reflect current status
5996 * persisting settings for later use
5997 * sending a broadcast if necessary
5998 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005999 private boolean deletePackageX(String packageName, boolean sendBroadCast,
6000 boolean deleteCodeAndResources, int flags) {
6001 PackageRemovedInfo info = new PackageRemovedInfo();
Romain Guy96f43572009-03-24 20:27:49 -07006002 boolean res;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006003
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006004 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
6005 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
6006 try {
6007 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006008 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08006009 return false;
6010 }
6011 } catch (RemoteException e) {
6012 }
6013
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006014 synchronized (mInstallLock) {
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006015 res = deletePackageLI(packageName, deleteCodeAndResources,
6016 flags | REMOVE_CHATTY, info);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006017 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006018
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006019 if(res && sendBroadCast) {
Romain Guy96f43572009-03-24 20:27:49 -07006020 boolean systemUpdate = info.isRemovedPackageSystemUpdate;
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006021 info.sendBroadcast(deleteCodeAndResources, systemUpdate);
Romain Guy96f43572009-03-24 20:27:49 -07006022
6023 // If the removed package was a system update, the old system packaged
6024 // was re-enabled; we need to broadcast this information
6025 if (systemUpdate) {
6026 Bundle extras = new Bundle(1);
6027 extras.putInt(Intent.EXTRA_UID, info.removedUid >= 0 ? info.removedUid : info.uid);
6028 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6029
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006030 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, extras, null);
6031 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, extras, null);
Romain Guy96f43572009-03-24 20:27:49 -07006032 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006033 }
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006034 // Force a gc here.
6035 Runtime.getRuntime().gc();
6036 // Delete the resources here after sending the broadcast to let
6037 // other processes clean up before deleting resources.
6038 if (info.args != null) {
6039 synchronized (mInstallLock) {
6040 info.args.doPostDeleteLI(deleteCodeAndResources);
6041 }
6042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006043 return res;
6044 }
6045
6046 static class PackageRemovedInfo {
6047 String removedPackage;
6048 int uid = -1;
6049 int removedUid = -1;
Romain Guy96f43572009-03-24 20:27:49 -07006050 boolean isRemovedPackageSystemUpdate = false;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006051 // Clean up resources deleted packages.
6052 InstallArgs args = null;
Romain Guy96f43572009-03-24 20:27:49 -07006053
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006054 void sendBroadcast(boolean fullRemove, boolean replacing) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006055 Bundle extras = new Bundle(1);
6056 extras.putInt(Intent.EXTRA_UID, removedUid >= 0 ? removedUid : uid);
6057 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
6058 if (replacing) {
6059 extras.putBoolean(Intent.EXTRA_REPLACING, true);
6060 }
6061 if (removedPackage != null) {
Suchi Amalapurapudeb693702010-04-14 19:17:14 -07006062 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006063 }
6064 if (removedUid >= 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006065 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006066 }
6067 }
6068 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006070 /*
6071 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
6072 * flag is not set, the data directory is removed as well.
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006073 * 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 -08006074 * delete a partially installed application.
6075 */
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006076 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006077 int flags) {
6078 String packageName = p.packageName;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006079 if (outInfo != null) {
6080 outInfo.removedPackage = packageName;
6081 }
Dianne Hackborn399cccb2010-04-13 22:57:49 -07006082 removePackageLI(p, (flags&REMOVE_CHATTY) != 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006083 // Retrieve object to delete permissions for shared user later on
6084 PackageSetting deletedPs;
6085 synchronized (mPackages) {
6086 deletedPs = mSettings.mPackages.get(packageName);
6087 }
6088 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006089 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006090 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006091 int retCode = mInstaller.remove(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006092 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006093 Slog.w(TAG, "Couldn't remove app data or cache directory for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006094 + packageName + ", retcode=" + retCode);
6095 // we don't consider this to be a failure of the core package deletion
6096 }
6097 } else {
Kenny Root85387d72010-08-26 10:13:11 -07006098 // for simulator
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006099 PackageParser.Package pkg = mPackages.get(packageName);
6100 File dataDir = new File(pkg.applicationInfo.dataDir);
6101 dataDir.delete();
6102 }
Dianne Hackbornfb1f1032010-07-29 13:57:56 -07006103 schedulePackageCleaning(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006104 }
6105 synchronized (mPackages) {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006106 if (deletedPs != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006107 if ((flags&PackageManager.DONT_DELETE_DATA) == 0) {
6108 if (outInfo != null) {
6109 outInfo.removedUid = mSettings.removePackageLP(packageName);
6110 }
6111 if (deletedPs != null) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006112 updatePermissionsLP(deletedPs.name, null, false, false, false);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006113 if (deletedPs.sharedUser != null) {
6114 // remove permissions associated with package
6115 mSettings.updateSharedUserPermsLP(deletedPs, mGlobalGids);
6116 }
6117 }
6118 }
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08006119 // remove from preferred activities.
6120 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
6121 for (PreferredActivity pa : mSettings.mPreferredActivities.filterSet()) {
6122 if (pa.mActivity.getPackageName().equals(deletedPs.name)) {
6123 removed.add(pa);
6124 }
6125 }
6126 for (PreferredActivity pa : removed) {
6127 mSettings.mPreferredActivities.removeFilter(pa);
6128 }
6129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006130 // Save settings now
Dianne Hackborne83cefce2010-02-04 17:38:14 -08006131 mSettings.writeLP();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006132 }
6133 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006135 /*
6136 * Tries to delete system package.
6137 */
6138 private boolean deleteSystemPackageLI(PackageParser.Package p,
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006139 int flags, PackageRemovedInfo outInfo) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006140 ApplicationInfo applicationInfo = p.applicationInfo;
6141 //applicable for non-partially installed applications only
6142 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006143 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006144 return false;
6145 }
6146 PackageSetting ps = null;
6147 // Confirm if the system package has been updated
6148 // An updated system app can be deleted. This will also have to restore
6149 // the system pkg from system partition
6150 synchronized (mPackages) {
6151 ps = mSettings.getDisabledSystemPkg(p.packageName);
6152 }
6153 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006154 Slog.w(TAG, "Attempt to delete system package "+ p.packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006155 return false;
6156 } else {
6157 Log.i(TAG, "Deleting system pkg from data partition");
6158 }
6159 // Delete the updated package
Romain Guy96f43572009-03-24 20:27:49 -07006160 outInfo.isRemovedPackageSystemUpdate = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006161 final boolean deleteCodeAndResources;
6162 if (ps.versionCode < p.mVersionCode) {
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006163 // Delete code and resources for downgrades
6164 deleteCodeAndResources = true;
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006165 flags &= ~PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006166 } else {
6167 // Preserve data by setting flag
Kenny Root7c1bd7f2010-09-01 13:44:11 -07006168 deleteCodeAndResources = false;
6169 flags |= PackageManager.DONT_DELETE_DATA;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07006170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006171 boolean ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
6172 if (!ret) {
6173 return false;
6174 }
6175 synchronized (mPackages) {
6176 // Reinstate the old system package
6177 mSettings.enableSystemPackageLP(p.packageName);
Kenny Root8f7cc022010-09-12 09:04:56 -07006178 // Remove any native libraries from the upgraded package.
6179 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006180 }
6181 // Install the system package
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006182 PackageParser.Package newPkg = scanPackageLI(ps.codePath,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006183 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM,
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006184 SCAN_MONITOR | SCAN_NO_PATHS);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006186 if (newPkg == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006187 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006188 return false;
6189 }
6190 synchronized (mPackages) {
Dianne Hackborn92cfa102010-04-28 11:00:44 -07006191 updatePermissionsLP(newPkg.packageName, newPkg, true, true, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006192 mSettings.writeLP();
6193 }
6194 return true;
6195 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006197 private boolean deleteInstalledPackageLI(PackageParser.Package p,
6198 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6199 ApplicationInfo applicationInfo = p.applicationInfo;
6200 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006201 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006202 return false;
6203 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07006204 if (outInfo != null) {
6205 outInfo.uid = applicationInfo.uid;
6206 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006207
6208 // Delete package data from internal structures and also remove data if flag is set
6209 removePackageDataLI(p, outInfo, flags);
6210
6211 // Delete application code and resources
6212 if (deleteCodeAndResources) {
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006213 // TODO can pick up from PackageSettings as well
Kenny Root85387d72010-08-26 10:13:11 -07006214 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0;
6215 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0;
6216 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir,
6217 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006218 }
6219 return true;
6220 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006222 /*
6223 * This method handles package deletion in general
6224 */
6225 private boolean deletePackageLI(String packageName,
6226 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo) {
6227 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006228 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006229 return false;
6230 }
6231 PackageParser.Package p;
6232 boolean dataOnly = false;
6233 synchronized (mPackages) {
6234 p = mPackages.get(packageName);
6235 if (p == null) {
6236 //this retrieves partially installed apps
6237 dataOnly = true;
6238 PackageSetting ps = mSettings.mPackages.get(packageName);
6239 if (ps == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006240 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006241 return false;
6242 }
6243 p = ps.pkg;
6244 }
6245 }
6246 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006247 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006248 return false;
6249 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006251 if (dataOnly) {
6252 // Delete application data first
6253 removePackageDataLI(p, outInfo, flags);
6254 return true;
6255 }
6256 // At this point the package should have ApplicationInfo associated with it
6257 if (p.applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006258 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006259 return false;
6260 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006261 boolean ret = false;
Kenny Root85387d72010-08-26 10:13:11 -07006262 if (isSystemApp(p)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006263 Log.i(TAG, "Removing system package:"+p.packageName);
6264 // When an updated system application is deleted we delete the existing resources as well and
6265 // fall back to existing code in system partition
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006266 ret = deleteSystemPackageLI(p, flags, outInfo);
6267 } else {
6268 Log.i(TAG, "Removing non-system package:"+p.packageName);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08006269 // Kill application pre-emptively especially for apps on sd.
6270 killApplication(packageName, p.applicationInfo.uid);
Jeff Brown07330792010-03-30 19:57:08 -07006271 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006272 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08006273 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006274 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006275
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006276 public void clearApplicationUserData(final String packageName,
6277 final IPackageDataObserver observer) {
6278 mContext.enforceCallingOrSelfPermission(
6279 android.Manifest.permission.CLEAR_APP_USER_DATA, null);
6280 // Queue up an async operation since the package deletion may take a little while.
6281 mHandler.post(new Runnable() {
6282 public void run() {
6283 mHandler.removeCallbacks(this);
6284 final boolean succeeded;
6285 synchronized (mInstallLock) {
6286 succeeded = clearApplicationUserDataLI(packageName);
6287 }
6288 if (succeeded) {
6289 // invoke DeviceStorageMonitor's update method to clear any notifications
6290 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService)
6291 ServiceManager.getService(DeviceStorageMonitorService.SERVICE);
6292 if (dsm != null) {
6293 dsm.updateMemory();
6294 }
6295 }
6296 if(observer != null) {
6297 try {
6298 observer.onRemoveCompleted(packageName, succeeded);
6299 } catch (RemoteException e) {
6300 Log.i(TAG, "Observer no longer exists.");
6301 }
6302 } //end if observer
6303 } //end run
6304 });
6305 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006307 private boolean clearApplicationUserDataLI(String packageName) {
6308 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006309 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006310 return false;
6311 }
6312 PackageParser.Package p;
6313 boolean dataOnly = false;
6314 synchronized (mPackages) {
6315 p = mPackages.get(packageName);
6316 if(p == null) {
6317 dataOnly = true;
6318 PackageSetting ps = mSettings.mPackages.get(packageName);
6319 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006320 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006321 return false;
6322 }
6323 p = ps.pkg;
6324 }
6325 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006326 boolean useEncryptedFSDir = false;
6327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006328 if(!dataOnly) {
6329 //need to check this only for fully installed applications
6330 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006331 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006332 return false;
6333 }
6334 final ApplicationInfo applicationInfo = p.applicationInfo;
6335 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006336 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006337 return false;
6338 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006339 useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006340 }
6341 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006342 int retCode = mInstaller.clearUserData(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006343 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006344 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006345 + packageName);
6346 return false;
6347 }
6348 }
6349 return true;
6350 }
6351
6352 public void deleteApplicationCacheFiles(final String packageName,
6353 final IPackageDataObserver observer) {
6354 mContext.enforceCallingOrSelfPermission(
6355 android.Manifest.permission.DELETE_CACHE_FILES, null);
6356 // Queue up an async operation since the package deletion may take a little while.
6357 mHandler.post(new Runnable() {
6358 public void run() {
6359 mHandler.removeCallbacks(this);
6360 final boolean succeded;
6361 synchronized (mInstallLock) {
6362 succeded = deleteApplicationCacheFilesLI(packageName);
6363 }
6364 if(observer != null) {
6365 try {
6366 observer.onRemoveCompleted(packageName, succeded);
6367 } catch (RemoteException e) {
6368 Log.i(TAG, "Observer no longer exists.");
6369 }
6370 } //end if observer
6371 } //end run
6372 });
6373 }
6374
6375 private boolean deleteApplicationCacheFilesLI(String packageName) {
6376 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006377 Slog.w(TAG, "Attempt to delete null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006378 return false;
6379 }
6380 PackageParser.Package p;
6381 synchronized (mPackages) {
6382 p = mPackages.get(packageName);
6383 }
6384 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006385 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006386 return false;
6387 }
6388 final ApplicationInfo applicationInfo = p.applicationInfo;
6389 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006390 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006391 return false;
6392 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006393 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006394 if (mInstaller != null) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08006395 int retCode = mInstaller.deleteCacheFiles(packageName, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006396 if (retCode < 0) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006397 Slog.w(TAG, "Couldn't remove cache files for package: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006398 + packageName);
6399 return false;
6400 }
6401 }
6402 return true;
6403 }
6404
6405 public void getPackageSizeInfo(final String packageName,
6406 final IPackageStatsObserver observer) {
6407 mContext.enforceCallingOrSelfPermission(
6408 android.Manifest.permission.GET_PACKAGE_SIZE, null);
6409 // Queue up an async operation since the package deletion may take a little while.
6410 mHandler.post(new Runnable() {
6411 public void run() {
6412 mHandler.removeCallbacks(this);
6413 PackageStats lStats = new PackageStats(packageName);
6414 final boolean succeded;
6415 synchronized (mInstallLock) {
6416 succeded = getPackageSizeInfoLI(packageName, lStats);
6417 }
6418 if(observer != null) {
6419 try {
6420 observer.onGetStatsCompleted(lStats, succeded);
6421 } catch (RemoteException e) {
6422 Log.i(TAG, "Observer no longer exists.");
6423 }
6424 } //end if observer
6425 } //end run
6426 });
6427 }
6428
6429 private boolean getPackageSizeInfoLI(String packageName, PackageStats pStats) {
6430 if (packageName == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006431 Slog.w(TAG, "Attempt to get size of null packageName.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006432 return false;
6433 }
6434 PackageParser.Package p;
6435 boolean dataOnly = false;
6436 synchronized (mPackages) {
6437 p = mPackages.get(packageName);
6438 if(p == null) {
6439 dataOnly = true;
6440 PackageSetting ps = mSettings.mPackages.get(packageName);
6441 if((ps == null) || (ps.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006442 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006443 return false;
6444 }
6445 p = ps.pkg;
6446 }
6447 }
6448 String publicSrcDir = null;
6449 if(!dataOnly) {
6450 final ApplicationInfo applicationInfo = p.applicationInfo;
6451 if (applicationInfo == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006452 Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006453 return false;
6454 }
6455 publicSrcDir = isForwardLocked(p) ? applicationInfo.publicSourceDir : null;
6456 }
Oscar Montemayora8529f62009-11-18 10:14:20 -08006457 boolean useEncryptedFSDir = useEncryptedFilesystemForPackage(p);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006458 if (mInstaller != null) {
6459 int res = mInstaller.getSizeInfo(packageName, p.mPath,
Oscar Montemayora8529f62009-11-18 10:14:20 -08006460 publicSrcDir, pStats, useEncryptedFSDir);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006461 if (res < 0) {
6462 return false;
6463 } else {
6464 return true;
6465 }
6466 }
6467 return true;
6468 }
6469
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006470
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006471 public void addPackageToPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006472 Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006473 }
6474
6475 public void removePackageFromPreferred(String packageName) {
Dianne Hackborn8377fc02010-06-07 15:54:58 -07006476 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006477 }
6478
6479 public List<PackageInfo> getPreferredPackages(int flags) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08006480 return new ArrayList<PackageInfo>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006481 }
6482
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006483 int getUidTargetSdkVersionLockedLP(int uid) {
6484 Object obj = mSettings.getUserIdLP(uid);
6485 if (obj instanceof SharedUserSetting) {
6486 SharedUserSetting sus = (SharedUserSetting)obj;
6487 final int N = sus.packages.size();
6488 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
6489 Iterator<PackageSetting> it = sus.packages.iterator();
6490 int i=0;
6491 while (it.hasNext()) {
6492 PackageSetting ps = it.next();
6493 if (ps.pkg != null) {
6494 int v = ps.pkg.applicationInfo.targetSdkVersion;
6495 if (v < vers) vers = v;
6496 }
6497 }
6498 return vers;
6499 } else if (obj instanceof PackageSetting) {
6500 PackageSetting ps = (PackageSetting)obj;
6501 if (ps.pkg != null) {
6502 return ps.pkg.applicationInfo.targetSdkVersion;
6503 }
6504 }
6505 return Build.VERSION_CODES.CUR_DEVELOPMENT;
6506 }
6507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006508 public void addPreferredActivity(IntentFilter filter, int match,
6509 ComponentName[] set, ComponentName activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006510 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006511 if (mContext.checkCallingOrSelfPermission(
6512 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6513 != PackageManager.PERMISSION_GRANTED) {
6514 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6515 < Build.VERSION_CODES.FROYO) {
6516 Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
6517 + Binder.getCallingUid());
6518 return;
6519 }
6520 mContext.enforceCallingOrSelfPermission(
6521 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6522 }
6523
6524 Slog.i(TAG, "Adding preferred activity " + activity + ":");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006525 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6526 mSettings.mPreferredActivities.addFilter(
6527 new PreferredActivity(filter, match, set, activity));
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006528 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006529 }
6530 }
6531
Satish Sampath8dbe6122009-06-02 23:35:54 +01006532 public void replacePreferredActivity(IntentFilter filter, int match,
6533 ComponentName[] set, ComponentName activity) {
Satish Sampath8dbe6122009-06-02 23:35:54 +01006534 if (filter.countActions() != 1) {
6535 throw new IllegalArgumentException(
6536 "replacePreferredActivity expects filter to have only 1 action.");
6537 }
6538 if (filter.countCategories() != 1) {
6539 throw new IllegalArgumentException(
6540 "replacePreferredActivity expects filter to have only 1 category.");
6541 }
6542 if (filter.countDataAuthorities() != 0
6543 || filter.countDataPaths() != 0
6544 || filter.countDataSchemes() != 0
6545 || filter.countDataTypes() != 0) {
6546 throw new IllegalArgumentException(
6547 "replacePreferredActivity expects filter to have no data authorities, " +
6548 "paths, schemes or types.");
6549 }
6550 synchronized (mPackages) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006551 if (mContext.checkCallingOrSelfPermission(
6552 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6553 != PackageManager.PERMISSION_GRANTED) {
6554 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6555 < Build.VERSION_CODES.FROYO) {
6556 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
6557 + Binder.getCallingUid());
6558 return;
6559 }
6560 mContext.enforceCallingOrSelfPermission(
6561 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6562 }
6563
Satish Sampath8dbe6122009-06-02 23:35:54 +01006564 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6565 String action = filter.getAction(0);
6566 String category = filter.getCategory(0);
6567 while (it.hasNext()) {
6568 PreferredActivity pa = it.next();
6569 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) {
6570 it.remove();
6571 Log.i(TAG, "Removed preferred activity " + pa.mActivity + ":");
6572 filter.dump(new LogPrinter(Log.INFO, TAG), " ");
6573 }
6574 }
6575 addPreferredActivity(filter, match, set, activity);
6576 }
6577 }
6578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006579 public void clearPackagePreferredActivities(String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006580 synchronized (mPackages) {
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006581 int uid = Binder.getCallingUid();
6582 PackageParser.Package pkg = mPackages.get(packageName);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006583 if (pkg == null || pkg.applicationInfo.uid != uid) {
6584 if (mContext.checkCallingOrSelfPermission(
6585 android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
6586 != PackageManager.PERMISSION_GRANTED) {
6587 if (getUidTargetSdkVersionLockedLP(Binder.getCallingUid())
6588 < Build.VERSION_CODES.FROYO) {
6589 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
6590 + Binder.getCallingUid());
6591 return;
6592 }
6593 mContext.enforceCallingOrSelfPermission(
6594 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
6595 }
Dianne Hackborn2ee89ea2010-03-10 18:27:09 -08006596 }
6597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006598 if (clearPackagePreferredActivitiesLP(packageName)) {
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006599 scheduleWriteSettingsLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006600 }
6601 }
6602 }
6603
6604 boolean clearPackagePreferredActivitiesLP(String packageName) {
6605 boolean changed = false;
6606 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6607 while (it.hasNext()) {
6608 PreferredActivity pa = it.next();
6609 if (pa.mActivity.getPackageName().equals(packageName)) {
6610 it.remove();
6611 changed = true;
6612 }
6613 }
6614 return changed;
6615 }
6616
6617 public int getPreferredActivities(List<IntentFilter> outFilters,
6618 List<ComponentName> outActivities, String packageName) {
6619
6620 int num = 0;
6621 synchronized (mPackages) {
6622 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator();
6623 while (it.hasNext()) {
6624 PreferredActivity pa = it.next();
6625 if (packageName == null
6626 || pa.mActivity.getPackageName().equals(packageName)) {
6627 if (outFilters != null) {
6628 outFilters.add(new IntentFilter(pa));
6629 }
6630 if (outActivities != null) {
6631 outActivities.add(pa.mActivity);
6632 }
6633 }
6634 }
6635 }
6636
6637 return num;
6638 }
6639
6640 public void setApplicationEnabledSetting(String appPackageName,
6641 int newState, int flags) {
6642 setEnabledSetting(appPackageName, null, newState, flags);
6643 }
6644
6645 public void setComponentEnabledSetting(ComponentName componentName,
6646 int newState, int flags) {
6647 setEnabledSetting(componentName.getPackageName(),
6648 componentName.getClassName(), newState, flags);
6649 }
6650
6651 private void setEnabledSetting(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006652 final String packageName, String className, int newState, final int flags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006653 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
6654 || newState == COMPONENT_ENABLED_STATE_ENABLED
6655 || newState == COMPONENT_ENABLED_STATE_DISABLED)) {
6656 throw new IllegalArgumentException("Invalid new component state: "
6657 + newState);
6658 }
6659 PackageSetting pkgSetting;
6660 final int uid = Binder.getCallingUid();
6661 final int permission = mContext.checkCallingPermission(
6662 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
6663 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006664 boolean sendNow = false;
6665 boolean isApp = (className == null);
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006666 String componentName = isApp ? packageName : className;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006667 int packageUid = -1;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006668 ArrayList<String> components;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006669 synchronized (mPackages) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006670 pkgSetting = mSettings.mPackages.get(packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006671 if (pkgSetting == null) {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006672 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006673 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006674 "Unknown package: " + packageName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006675 }
6676 throw new IllegalArgumentException(
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006677 "Unknown component: " + packageName
6678 + "/" + className);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006679 }
6680 if (!allowedByPermission && (uid != pkgSetting.userId)) {
6681 throw new SecurityException(
6682 "Permission Denial: attempt to change component state from pid="
6683 + Binder.getCallingPid()
6684 + ", uid=" + uid + ", package uid=" + pkgSetting.userId);
6685 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006686 if (className == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006687 // We're dealing with an application/package level state change
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006688 if (pkgSetting.enabled == newState) {
6689 // Nothing to do
6690 return;
6691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006692 pkgSetting.enabled = newState;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07006693 pkgSetting.pkg.mSetEnabled = newState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006694 } else {
6695 // We're dealing with a component level state change
6696 switch (newState) {
6697 case COMPONENT_ENABLED_STATE_ENABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006698 if (!pkgSetting.enableComponentLP(className)) {
6699 return;
6700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006701 break;
6702 case COMPONENT_ENABLED_STATE_DISABLED:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006703 if (!pkgSetting.disableComponentLP(className)) {
6704 return;
6705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006706 break;
6707 case COMPONENT_ENABLED_STATE_DEFAULT:
Dianne Hackbornd7c09682010-03-30 10:42:20 -07006708 if (!pkgSetting.restoreComponentLP(className)) {
6709 return;
6710 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006711 break;
6712 default:
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08006713 Slog.e(TAG, "Invalid new component state: " + newState);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006714 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006715 }
6716 }
6717 mSettings.writeLP();
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006718 packageUid = pkgSetting.userId;
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006719 components = mPendingBroadcasts.get(packageName);
6720 boolean newPackage = components == null;
6721 if (newPackage) {
6722 components = new ArrayList<String>();
6723 }
6724 if (!components.contains(componentName)) {
6725 components.add(componentName);
6726 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006727 if ((flags&PackageManager.DONT_KILL_APP) == 0) {
6728 sendNow = true;
6729 // Purge entry from pending broadcast list if another one exists already
6730 // since we are sending one right away.
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006731 mPendingBroadcasts.remove(packageName);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006732 } else {
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006733 if (newPackage) {
6734 mPendingBroadcasts.put(packageName, components);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006735 }
6736 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
6737 // Schedule a message
6738 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
6739 }
6740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006741 }
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006743 long callingId = Binder.clearCallingIdentity();
6744 try {
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006745 if (sendNow) {
6746 sendPackageChangedBroadcast(packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006747 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006749 } finally {
6750 Binder.restoreCallingIdentity(callingId);
6751 }
6752 }
6753
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006754 private void sendPackageChangedBroadcast(String packageName,
Dianne Hackborn86a72da2009-11-11 20:12:41 -08006755 boolean killFlag, ArrayList<String> componentNames, int packageUid) {
6756 if (false) Log.v(TAG, "Sending package changed: package=" + packageName
6757 + " components=" + componentNames);
6758 Bundle extras = new Bundle(4);
6759 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
6760 String nameList[] = new String[componentNames.size()];
6761 componentNames.toArray(nameList);
6762 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006763 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
6764 extras.putInt(Intent.EXTRA_UID, packageUid);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07006765 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null);
Suchi Amalapurapu0214e942009-09-02 11:03:18 -07006766 }
6767
Jacek Surazski65e13172009-04-28 15:26:38 +02006768 public String getInstallerPackageName(String packageName) {
6769 synchronized (mPackages) {
6770 PackageSetting pkg = mSettings.mPackages.get(packageName);
6771 if (pkg == null) {
6772 throw new IllegalArgumentException("Unknown package: " + packageName);
6773 }
6774 return pkg.installerPackageName;
6775 }
6776 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006777
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006778 public int getApplicationEnabledSetting(String appPackageName) {
6779 synchronized (mPackages) {
6780 PackageSetting pkg = mSettings.mPackages.get(appPackageName);
6781 if (pkg == null) {
6782 throw new IllegalArgumentException("Unknown package: " + appPackageName);
6783 }
6784 return pkg.enabled;
6785 }
6786 }
6787
6788 public int getComponentEnabledSetting(ComponentName componentName) {
6789 synchronized (mPackages) {
6790 final String packageNameStr = componentName.getPackageName();
6791 PackageSetting pkg = mSettings.mPackages.get(packageNameStr);
6792 if (pkg == null) {
6793 throw new IllegalArgumentException("Unknown component: " + componentName);
6794 }
6795 final String classNameStr = componentName.getClassName();
6796 return pkg.currentEnabledStateLP(classNameStr);
6797 }
6798 }
6799
6800 public void enterSafeMode() {
6801 if (!mSystemReady) {
6802 mSafeMode = true;
6803 }
6804 }
6805
6806 public void systemReady() {
6807 mSystemReady = true;
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006808
6809 // Read the compatibilty setting when the system is ready.
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006810 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt(
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006811 mContext.getContentResolver(),
6812 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1;
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006813 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006814 if (DEBUG_SETTINGS) {
Mitsuru Oshima69fff4a2009-07-21 09:51:05 -07006815 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
Mitsuru Oshimae5fb3282009-06-09 21:16:08 -07006816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006817 }
6818
6819 public boolean isSafeMode() {
6820 return mSafeMode;
6821 }
6822
6823 public boolean hasSystemUidErrors() {
6824 return mHasSystemUidErrors;
6825 }
6826
6827 static String arrayToString(int[] array) {
6828 StringBuffer buf = new StringBuffer(128);
6829 buf.append('[');
6830 if (array != null) {
6831 for (int i=0; i<array.length; i++) {
6832 if (i > 0) buf.append(", ");
6833 buf.append(array[i]);
6834 }
6835 }
6836 buf.append(']');
6837 return buf.toString();
6838 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006839
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006840 @Override
6841 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
6842 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
6843 != PackageManager.PERMISSION_GRANTED) {
6844 pw.println("Permission Denial: can't dump ActivityManager from from pid="
6845 + Binder.getCallingPid()
6846 + ", uid=" + Binder.getCallingUid()
6847 + " without permission "
6848 + android.Manifest.permission.DUMP);
6849 return;
6850 }
6851
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006852 String packageName = null;
6853
6854 int opti = 0;
6855 while (opti < args.length) {
6856 String opt = args[opti];
6857 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
6858 break;
6859 }
6860 opti++;
6861 if ("-a".equals(opt)) {
6862 // Right now we only know how to print all.
6863 } else if ("-h".equals(opt)) {
6864 pw.println("Package manager dump options:");
6865 pw.println(" [-h] [cmd] ...");
6866 pw.println(" cmd may be one of:");
6867 pw.println(" [package.name]: info about given package");
6868 return;
6869 } else {
6870 pw.println("Unknown argument: " + opt + "; use -h for help");
6871 }
6872 }
6873
6874 // Is the caller requesting to dump a particular piece of data?
6875 if (opti < args.length) {
6876 String cmd = args[opti];
6877 opti++;
6878 // Is this a package name?
6879 if ("android".equals(cmd) || cmd.contains(".")) {
6880 packageName = cmd;
6881 }
6882 }
6883
6884 boolean printedTitle = false;
6885
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006886 synchronized (mPackages) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006887 if (mActivities.dump(pw, "Activity Resolver Table:", " ", packageName)) {
6888 printedTitle = true;
6889 }
6890 if (mReceivers.dump(pw, printedTitle
6891 ? "\nReceiver Resolver Table:" : "Receiver Resolver Table:",
6892 " ", packageName)) {
6893 printedTitle = true;
6894 }
6895 if (mServices.dump(pw, printedTitle
6896 ? "\nService Resolver Table:" : "Service Resolver Table:",
6897 " ", packageName)) {
6898 printedTitle = true;
6899 }
6900 if (mSettings.mPreferredActivities.dump(pw, printedTitle
6901 ? "\nPreferred Activities:" : "Preferred Activities:",
6902 " ", packageName)) {
6903 printedTitle = true;
6904 }
6905 boolean printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006906 {
6907 for (BasePermission p : mSettings.mPermissions.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006908 if (packageName != null && !packageName.equals(p.sourcePackage)) {
6909 continue;
6910 }
6911 if (!printedSomething) {
6912 if (printedTitle) pw.println(" ");
6913 pw.println("Permissions:");
6914 printedSomething = true;
6915 printedTitle = true;
6916 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006917 pw.print(" Permission ["); pw.print(p.name); pw.print("] (");
6918 pw.print(Integer.toHexString(System.identityHashCode(p)));
6919 pw.println("):");
6920 pw.print(" sourcePackage="); pw.println(p.sourcePackage);
6921 pw.print(" uid="); pw.print(p.uid);
6922 pw.print(" gids="); pw.print(arrayToString(p.gids));
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006923 pw.print(" type="); pw.print(p.type);
6924 pw.print(" prot="); pw.println(p.protectionLevel);
6925 if (p.packageSetting != null) {
6926 pw.print(" packageSetting="); pw.println(p.packageSetting);
6927 }
6928 if (p.perm != null) {
6929 pw.print(" perm="); pw.println(p.perm);
6930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006931 }
6932 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006933 printedSomething = false;
6934 SharedUserSetting packageSharedUser = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006935 {
6936 for (PackageSetting ps : mSettings.mPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07006937 if (packageName != null && !packageName.equals(ps.realName)
6938 && !packageName.equals(ps.name)) {
6939 continue;
6940 }
6941 if (!printedSomething) {
6942 if (printedTitle) pw.println(" ");
6943 pw.println("Packages:");
6944 printedSomething = true;
6945 printedTitle = true;
6946 }
6947 packageSharedUser = ps.sharedUser;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006948 pw.print(" Package [");
6949 pw.print(ps.realName != null ? ps.realName : ps.name);
6950 pw.print("] (");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006951 pw.print(Integer.toHexString(System.identityHashCode(ps)));
6952 pw.println("):");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08006953 if (ps.realName != null) {
6954 pw.print(" compat name="); pw.println(ps.name);
6955 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006956 pw.print(" userId="); pw.print(ps.userId);
6957 pw.print(" gids="); pw.println(arrayToString(ps.gids));
6958 pw.print(" sharedUser="); pw.println(ps.sharedUser);
6959 pw.print(" pkg="); pw.println(ps.pkg);
6960 pw.print(" codePath="); pw.println(ps.codePathString);
6961 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
Kenny Root85387d72010-08-26 10:13:11 -07006962 pw.print(" nativeLibraryPath="); pw.println(ps.nativeLibraryPathString);
Kenny Root93565c4b2010-06-18 15:46:06 -07006963 pw.print(" obbPath="); pw.println(ps.obbPathString);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08006964 if (ps.pkg != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07006965 pw.print(" dataDir="); pw.println(ps.pkg.applicationInfo.dataDir);
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006966 pw.print(" targetSdk="); pw.println(ps.pkg.applicationInfo.targetSdkVersion);
Kenny Root85387d72010-08-26 10:13:11 -07006967 if (ps.pkg.mOperationPending) {
6968 pw.println(" mOperationPending=true");
6969 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006970 pw.print(" supportsScreens=[");
6971 boolean first = true;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006972 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07006973 ApplicationInfo.FLAG_SUPPORTS_SMALL_SCREENS) != 0) {
6974 if (!first) pw.print(", ");
6975 first = false;
6976 pw.print("small");
6977 }
6978 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006979 ApplicationInfo.FLAG_SUPPORTS_NORMAL_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006980 if (!first) pw.print(", ");
6981 first = false;
6982 pw.print("medium");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006983 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006984 if ((ps.pkg.applicationInfo.flags &
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006985 ApplicationInfo.FLAG_SUPPORTS_LARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006986 if (!first) pw.print(", ");
6987 first = false;
6988 pw.print("large");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006989 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006990 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07006991 ApplicationInfo.FLAG_SUPPORTS_XLARGE_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006992 if (!first) pw.print(", ");
6993 first = false;
Dianne Hackborn14cee9f2010-04-23 17:51:26 -07006994 pw.print("xlarge");
Mitsuru Oshima841f13c2009-07-17 17:23:31 -07006995 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08006996 if ((ps.pkg.applicationInfo.flags &
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07006997 ApplicationInfo.FLAG_RESIZEABLE_FOR_SCREENS) != 0) {
Dianne Hackborn11b822d2009-07-21 20:03:02 -07006998 if (!first) pw.print(", ");
6999 first = false;
7000 pw.print("resizeable");
Dianne Hackbornc4db95c2009-07-21 17:46:02 -07007001 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007002 if ((ps.pkg.applicationInfo.flags &
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007003 ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES) != 0) {
7004 if (!first) pw.print(", ");
7005 first = false;
7006 pw.print("anyDensity");
7007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007008 }
Dianne Hackborn11b822d2009-07-21 20:03:02 -07007009 pw.println("]");
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007010 pw.print(" timeStamp="); pw.println(ps.getTimeStampStr());
7011 pw.print(" signatures="); pw.println(ps.signatures);
7012 pw.print(" permissionsFixed="); pw.print(ps.permissionsFixed);
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007013 pw.print(" haveGids="); pw.println(ps.haveGids);
7014 pw.print(" pkgFlags=0x"); pw.print(Integer.toHexString(ps.pkgFlags));
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007015 pw.print(" installStatus="); pw.print(ps.installStatus);
7016 pw.print(" enabled="); pw.println(ps.enabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007017 if (ps.disabledComponents.size() > 0) {
7018 pw.println(" disabledComponents:");
7019 for (String s : ps.disabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007020 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007021 }
7022 }
7023 if (ps.enabledComponents.size() > 0) {
7024 pw.println(" enabledComponents:");
7025 for (String s : ps.enabledComponents) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007026 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007027 }
7028 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007029 if (ps.grantedPermissions.size() > 0) {
7030 pw.println(" grantedPermissions:");
7031 for (String s : ps.grantedPermissions) {
7032 pw.print(" "); pw.println(s);
7033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007035 }
7036 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007037 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007038 if (mSettings.mRenamedPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007039 for (HashMap.Entry<String, String> e
7040 : mSettings.mRenamedPackages.entrySet()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007041 if (packageName != null && !packageName.equals(e.getKey())
7042 && !packageName.equals(e.getValue())) {
7043 continue;
7044 }
7045 if (!printedSomething) {
7046 if (printedTitle) pw.println(" ");
7047 pw.println("Renamed packages:");
7048 printedSomething = true;
7049 printedTitle = true;
7050 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007051 pw.print(" "); pw.print(e.getKey()); pw.print(" -> ");
7052 pw.println(e.getValue());
7053 }
7054 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007055 printedSomething = false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007056 if (mSettings.mDisabledSysPackages.size() > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007057 for (PackageSetting ps : mSettings.mDisabledSysPackages.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007058 if (packageName != null && !packageName.equals(ps.realName)
7059 && !packageName.equals(ps.name)) {
7060 continue;
7061 }
7062 if (!printedSomething) {
7063 if (printedTitle) pw.println(" ");
7064 pw.println("Hidden system packages:");
7065 printedSomething = true;
7066 printedTitle = true;
7067 }
7068 pw.print(" Package [");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007069 pw.print(ps.realName != null ? ps.realName : ps.name);
7070 pw.print("] (");
7071 pw.print(Integer.toHexString(System.identityHashCode(ps)));
7072 pw.println("):");
7073 if (ps.realName != null) {
7074 pw.print(" compat name="); pw.println(ps.name);
7075 }
7076 pw.print(" userId="); pw.println(ps.userId);
7077 pw.print(" sharedUser="); pw.println(ps.sharedUser);
7078 pw.print(" codePath="); pw.println(ps.codePathString);
7079 pw.print(" resourcePath="); pw.println(ps.resourcePathString);
7080 }
7081 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007082 printedSomething = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007083 {
7084 for (SharedUserSetting su : mSettings.mSharedUsers.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007085 if (packageName != null && su != packageSharedUser) {
7086 continue;
7087 }
7088 if (!printedSomething) {
7089 if (printedTitle) pw.println(" ");
7090 pw.println("Shared users:");
7091 printedSomething = true;
7092 printedTitle = true;
7093 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007094 pw.print(" SharedUser ["); pw.print(su.name); pw.print("] (");
7095 pw.print(Integer.toHexString(System.identityHashCode(su)));
7096 pw.println("):");
7097 pw.print(" userId="); pw.print(su.userId);
7098 pw.print(" gids="); pw.println(arrayToString(su.gids));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007099 pw.println(" grantedPermissions:");
7100 for (String s : su.grantedPermissions) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007101 pw.print(" "); pw.println(s);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007103 }
7104 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007105
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007106 if (packageName == null) {
7107 if (printedTitle) pw.println(" ");
7108 printedTitle = true;
7109 pw.println("Settings parse messages:");
7110 pw.println(mSettings.mReadMessages.toString());
7111
7112 pw.println(" ");
7113 pw.println("Package warning messages:");
7114 File fname = getSettingsProblemFile();
7115 FileInputStream in;
7116 try {
7117 in = new FileInputStream(fname);
7118 int avail = in.available();
7119 byte[] data = new byte[avail];
7120 in.read(data);
7121 pw.println(new String(data));
7122 } catch (FileNotFoundException e) {
7123 } catch (IOException e) {
7124 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007126 }
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007127
7128 synchronized (mProviders) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007129 boolean printedSomething = false;
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007130 for (PackageParser.Provider p : mProviders.values()) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007131 if (packageName != null && !packageName.equals(p.info.packageName)) {
7132 continue;
7133 }
7134 if (!printedSomething) {
7135 if (printedTitle) pw.println(" ");
7136 pw.println("Registered ContentProviders:");
7137 printedSomething = true;
7138 printedTitle = true;
7139 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007140 pw.print(" ["); pw.print(p.info.authority); pw.print("]: ");
Jeff Hamilton5bfc64f2009-08-18 12:25:30 -05007141 pw.println(p.toString());
7142 }
7143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007144 }
7145
7146 static final class BasePermission {
7147 final static int TYPE_NORMAL = 0;
7148 final static int TYPE_BUILTIN = 1;
7149 final static int TYPE_DYNAMIC = 2;
7150
7151 final String name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007152 String sourcePackage;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007153 PackageSettingBase packageSetting;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007154 final int type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007155 int protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007156 PackageParser.Permission perm;
7157 PermissionInfo pendingInfo;
7158 int uid;
7159 int[] gids;
7160
7161 BasePermission(String _name, String _sourcePackage, int _type) {
7162 name = _name;
7163 sourcePackage = _sourcePackage;
7164 type = _type;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007165 // Default to most conservative protection level.
7166 protectionLevel = PermissionInfo.PROTECTION_SIGNATURE;
7167 }
7168
7169 public String toString() {
7170 return "BasePermission{"
7171 + Integer.toHexString(System.identityHashCode(this))
7172 + " " + name + "}";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007173 }
7174 }
7175
7176 static class PackageSignatures {
7177 private Signature[] mSignatures;
7178
7179 PackageSignatures(Signature[] sigs) {
7180 assignSignatures(sigs);
7181 }
7182
7183 PackageSignatures() {
7184 }
7185
7186 void writeXml(XmlSerializer serializer, String tagName,
7187 ArrayList<Signature> pastSignatures) throws IOException {
7188 if (mSignatures == null) {
7189 return;
7190 }
7191 serializer.startTag(null, tagName);
7192 serializer.attribute(null, "count",
7193 Integer.toString(mSignatures.length));
7194 for (int i=0; i<mSignatures.length; i++) {
7195 serializer.startTag(null, "cert");
7196 final Signature sig = mSignatures[i];
7197 final int sigHash = sig.hashCode();
7198 final int numPast = pastSignatures.size();
7199 int j;
7200 for (j=0; j<numPast; j++) {
7201 Signature pastSig = pastSignatures.get(j);
7202 if (pastSig.hashCode() == sigHash && pastSig.equals(sig)) {
7203 serializer.attribute(null, "index", Integer.toString(j));
7204 break;
7205 }
7206 }
7207 if (j >= numPast) {
7208 pastSignatures.add(sig);
7209 serializer.attribute(null, "index", Integer.toString(numPast));
7210 serializer.attribute(null, "key", sig.toCharsString());
7211 }
7212 serializer.endTag(null, "cert");
7213 }
7214 serializer.endTag(null, tagName);
7215 }
7216
7217 void readXml(XmlPullParser parser, ArrayList<Signature> pastSignatures)
7218 throws IOException, XmlPullParserException {
7219 String countStr = parser.getAttributeValue(null, "count");
7220 if (countStr == null) {
7221 reportSettingsProblem(Log.WARN,
7222 "Error in package manager settings: <signatures> has"
7223 + " no count at " + parser.getPositionDescription());
7224 XmlUtils.skipCurrentTag(parser);
7225 }
7226 final int count = Integer.parseInt(countStr);
7227 mSignatures = new Signature[count];
7228 int pos = 0;
7229
7230 int outerDepth = parser.getDepth();
7231 int type;
7232 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7233 && (type != XmlPullParser.END_TAG
7234 || parser.getDepth() > outerDepth)) {
7235 if (type == XmlPullParser.END_TAG
7236 || type == XmlPullParser.TEXT) {
7237 continue;
7238 }
7239
7240 String tagName = parser.getName();
7241 if (tagName.equals("cert")) {
7242 if (pos < count) {
7243 String index = parser.getAttributeValue(null, "index");
7244 if (index != null) {
7245 try {
7246 int idx = Integer.parseInt(index);
7247 String key = parser.getAttributeValue(null, "key");
7248 if (key == null) {
7249 if (idx >= 0 && idx < pastSignatures.size()) {
7250 Signature sig = pastSignatures.get(idx);
7251 if (sig != null) {
7252 mSignatures[pos] = pastSignatures.get(idx);
7253 pos++;
7254 } else {
7255 reportSettingsProblem(Log.WARN,
7256 "Error in package manager settings: <cert> "
7257 + "index " + index + " is not defined at "
7258 + parser.getPositionDescription());
7259 }
7260 } else {
7261 reportSettingsProblem(Log.WARN,
7262 "Error in package manager settings: <cert> "
7263 + "index " + index + " is out of bounds at "
7264 + parser.getPositionDescription());
7265 }
7266 } else {
7267 while (pastSignatures.size() <= idx) {
7268 pastSignatures.add(null);
7269 }
7270 Signature sig = new Signature(key);
7271 pastSignatures.set(idx, sig);
7272 mSignatures[pos] = sig;
7273 pos++;
7274 }
7275 } catch (NumberFormatException e) {
7276 reportSettingsProblem(Log.WARN,
7277 "Error in package manager settings: <cert> "
7278 + "index " + index + " is not a number at "
7279 + parser.getPositionDescription());
7280 }
7281 } else {
7282 reportSettingsProblem(Log.WARN,
7283 "Error in package manager settings: <cert> has"
7284 + " no index at " + parser.getPositionDescription());
7285 }
7286 } else {
7287 reportSettingsProblem(Log.WARN,
7288 "Error in package manager settings: too "
7289 + "many <cert> tags, expected " + count
7290 + " at " + parser.getPositionDescription());
7291 }
7292 } else {
7293 reportSettingsProblem(Log.WARN,
7294 "Unknown element under <cert>: "
7295 + parser.getName());
7296 }
7297 XmlUtils.skipCurrentTag(parser);
7298 }
7299
7300 if (pos < count) {
7301 // Should never happen -- there is an error in the written
7302 // settings -- but if it does we don't want to generate
7303 // a bad array.
7304 Signature[] newSigs = new Signature[pos];
7305 System.arraycopy(mSignatures, 0, newSigs, 0, pos);
7306 mSignatures = newSigs;
7307 }
7308 }
7309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007310 private void assignSignatures(Signature[] sigs) {
7311 if (sigs == null) {
7312 mSignatures = null;
7313 return;
7314 }
7315 mSignatures = new Signature[sigs.length];
7316 for (int i=0; i<sigs.length; i++) {
7317 mSignatures[i] = sigs[i];
7318 }
7319 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007321 @Override
7322 public String toString() {
7323 StringBuffer buf = new StringBuffer(128);
7324 buf.append("PackageSignatures{");
7325 buf.append(Integer.toHexString(System.identityHashCode(this)));
7326 buf.append(" [");
7327 if (mSignatures != null) {
7328 for (int i=0; i<mSignatures.length; i++) {
7329 if (i > 0) buf.append(", ");
7330 buf.append(Integer.toHexString(
7331 System.identityHashCode(mSignatures[i])));
7332 }
7333 }
7334 buf.append("]}");
7335 return buf.toString();
7336 }
7337 }
7338
7339 static class PreferredActivity extends IntentFilter {
7340 final int mMatch;
7341 final String[] mSetPackages;
7342 final String[] mSetClasses;
7343 final String[] mSetComponents;
7344 final ComponentName mActivity;
7345 final String mShortActivity;
7346 String mParseError;
7347
7348 PreferredActivity(IntentFilter filter, int match, ComponentName[] set,
7349 ComponentName activity) {
7350 super(filter);
7351 mMatch = match&IntentFilter.MATCH_CATEGORY_MASK;
7352 mActivity = activity;
7353 mShortActivity = activity.flattenToShortString();
7354 mParseError = null;
7355 if (set != null) {
7356 final int N = set.length;
7357 String[] myPackages = new String[N];
7358 String[] myClasses = new String[N];
7359 String[] myComponents = new String[N];
7360 for (int i=0; i<N; i++) {
7361 ComponentName cn = set[i];
7362 if (cn == null) {
7363 mSetPackages = null;
7364 mSetClasses = null;
7365 mSetComponents = null;
7366 return;
7367 }
7368 myPackages[i] = cn.getPackageName().intern();
7369 myClasses[i] = cn.getClassName().intern();
7370 myComponents[i] = cn.flattenToShortString().intern();
7371 }
7372 mSetPackages = myPackages;
7373 mSetClasses = myClasses;
7374 mSetComponents = myComponents;
7375 } else {
7376 mSetPackages = null;
7377 mSetClasses = null;
7378 mSetComponents = null;
7379 }
7380 }
7381
7382 PreferredActivity(XmlPullParser parser) throws XmlPullParserException,
7383 IOException {
7384 mShortActivity = parser.getAttributeValue(null, "name");
7385 mActivity = ComponentName.unflattenFromString(mShortActivity);
7386 if (mActivity == null) {
7387 mParseError = "Bad activity name " + mShortActivity;
7388 }
7389 String matchStr = parser.getAttributeValue(null, "match");
7390 mMatch = matchStr != null ? Integer.parseInt(matchStr, 16) : 0;
7391 String setCountStr = parser.getAttributeValue(null, "set");
7392 int setCount = setCountStr != null ? Integer.parseInt(setCountStr) : 0;
7393
7394 String[] myPackages = setCount > 0 ? new String[setCount] : null;
7395 String[] myClasses = setCount > 0 ? new String[setCount] : null;
7396 String[] myComponents = setCount > 0 ? new String[setCount] : null;
7397
7398 int setPos = 0;
7399
7400 int outerDepth = parser.getDepth();
7401 int type;
7402 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
7403 && (type != XmlPullParser.END_TAG
7404 || parser.getDepth() > outerDepth)) {
7405 if (type == XmlPullParser.END_TAG
7406 || type == XmlPullParser.TEXT) {
7407 continue;
7408 }
7409
7410 String tagName = parser.getName();
7411 //Log.i(TAG, "Parse outerDepth=" + outerDepth + " depth="
7412 // + parser.getDepth() + " tag=" + tagName);
7413 if (tagName.equals("set")) {
7414 String name = parser.getAttributeValue(null, "name");
7415 if (name == null) {
7416 if (mParseError == null) {
7417 mParseError = "No name in set tag in preferred activity "
7418 + mShortActivity;
7419 }
7420 } else if (setPos >= setCount) {
7421 if (mParseError == null) {
7422 mParseError = "Too many set tags in preferred activity "
7423 + mShortActivity;
7424 }
7425 } else {
7426 ComponentName cn = ComponentName.unflattenFromString(name);
7427 if (cn == null) {
7428 if (mParseError == null) {
7429 mParseError = "Bad set name " + name + " in preferred activity "
7430 + mShortActivity;
7431 }
7432 } else {
7433 myPackages[setPos] = cn.getPackageName();
7434 myClasses[setPos] = cn.getClassName();
7435 myComponents[setPos] = name;
7436 setPos++;
7437 }
7438 }
7439 XmlUtils.skipCurrentTag(parser);
7440 } else if (tagName.equals("filter")) {
7441 //Log.i(TAG, "Starting to parse filter...");
7442 readFromXml(parser);
7443 //Log.i(TAG, "Finished filter: outerDepth=" + outerDepth + " depth="
7444 // + parser.getDepth() + " tag=" + parser.getName());
7445 } else {
7446 reportSettingsProblem(Log.WARN,
7447 "Unknown element under <preferred-activities>: "
7448 + parser.getName());
7449 XmlUtils.skipCurrentTag(parser);
7450 }
7451 }
7452
7453 if (setPos != setCount) {
7454 if (mParseError == null) {
7455 mParseError = "Not enough set tags (expected " + setCount
7456 + " but found " + setPos + ") in " + mShortActivity;
7457 }
7458 }
7459
7460 mSetPackages = myPackages;
7461 mSetClasses = myClasses;
7462 mSetComponents = myComponents;
7463 }
7464
7465 public void writeToXml(XmlSerializer serializer) throws IOException {
7466 final int NS = mSetClasses != null ? mSetClasses.length : 0;
7467 serializer.attribute(null, "name", mShortActivity);
7468 serializer.attribute(null, "match", Integer.toHexString(mMatch));
7469 serializer.attribute(null, "set", Integer.toString(NS));
7470 for (int s=0; s<NS; s++) {
7471 serializer.startTag(null, "set");
7472 serializer.attribute(null, "name", mSetComponents[s]);
7473 serializer.endTag(null, "set");
7474 }
7475 serializer.startTag(null, "filter");
7476 super.writeToXml(serializer);
7477 serializer.endTag(null, "filter");
7478 }
7479
7480 boolean sameSet(List<ResolveInfo> query, int priority) {
7481 if (mSetPackages == null) return false;
7482 final int NQ = query.size();
7483 final int NS = mSetPackages.length;
7484 int numMatch = 0;
7485 for (int i=0; i<NQ; i++) {
7486 ResolveInfo ri = query.get(i);
7487 if (ri.priority != priority) continue;
7488 ActivityInfo ai = ri.activityInfo;
7489 boolean good = false;
7490 for (int j=0; j<NS; j++) {
7491 if (mSetPackages[j].equals(ai.packageName)
7492 && mSetClasses[j].equals(ai.name)) {
7493 numMatch++;
7494 good = true;
7495 break;
7496 }
7497 }
7498 if (!good) return false;
7499 }
7500 return numMatch == NS;
7501 }
7502 }
7503
7504 static class GrantedPermissions {
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007505 int pkgFlags;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007507 HashSet<String> grantedPermissions = new HashSet<String>();
7508 int[] gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007510 GrantedPermissions(int pkgFlags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08007511 setFlags(pkgFlags);
7512 }
7513
7514 void setFlags(int pkgFlags) {
Jeff Brown07330792010-03-30 19:57:08 -07007515 this.pkgFlags = pkgFlags & (
7516 ApplicationInfo.FLAG_SYSTEM |
7517 ApplicationInfo.FLAG_FORWARD_LOCK |
Jeff Browna749f862010-03-31 00:43:36 -07007518 ApplicationInfo.FLAG_EXTERNAL_STORAGE |
Jeff Brown767225d2010-03-30 23:49:17 -07007519 ApplicationInfo.FLAG_NEVER_ENCRYPT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007520 }
7521 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007522
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007523 /**
7524 * Settings base class for pending and resolved classes.
7525 */
7526 static class PackageSettingBase extends GrantedPermissions {
7527 final String name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007528 final String realName;
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007529 File codePath;
7530 String codePathString;
7531 File resourcePath;
7532 String resourcePathString;
Kenny Root85387d72010-08-26 10:13:11 -07007533 String nativeLibraryPathString;
Kenny Root93565c4b2010-06-18 15:46:06 -07007534 String obbPathString;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007535 private long timeStamp;
7536 private String timeStampString = "0";
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007537 int versionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007538
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007539 boolean uidError;
7540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007541 PackageSignatures signatures = new PackageSignatures();
7542
7543 boolean permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007544 boolean haveGids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007546 /* Explicitly disabled components */
7547 HashSet<String> disabledComponents = new HashSet<String>(0);
7548 /* Explicitly enabled components */
7549 HashSet<String> enabledComponents = new HashSet<String>(0);
7550 int enabled = COMPONENT_ENABLED_STATE_DEFAULT;
7551 int installStatus = PKG_INSTALL_COMPLETE;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007552
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007553 PackageSettingBase origPackage;
7554
Jacek Surazski65e13172009-04-28 15:26:38 +02007555 /* package name of the app that installed this package */
7556 String installerPackageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007557
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007558 PackageSettingBase(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007559 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007560 super(pkgFlags);
7561 this.name = name;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007562 this.realName = realName;
Kenny Root806cc132010-09-12 08:34:19 -07007563 init(codePath, resourcePath, nativeLibraryPathString, pVersionCode);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007564 }
7565
Kenny Root806cc132010-09-12 08:34:19 -07007566 void init(File codePath, File resourcePath, String nativeLibraryPathString,
7567 int pVersionCode) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007568 this.codePath = codePath;
7569 this.codePathString = codePath.toString();
7570 this.resourcePath = resourcePath;
7571 this.resourcePathString = resourcePath.toString();
Kenny Root806cc132010-09-12 08:34:19 -07007572 this.nativeLibraryPathString = nativeLibraryPathString;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007573 this.versionCode = pVersionCode;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007574 }
Kenny Root85387d72010-08-26 10:13:11 -07007575
Jacek Surazski65e13172009-04-28 15:26:38 +02007576 public void setInstallerPackageName(String packageName) {
7577 installerPackageName = packageName;
7578 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007579
Jacek Surazski65e13172009-04-28 15:26:38 +02007580 String getInstallerPackageName() {
7581 return installerPackageName;
7582 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007584 public void setInstallStatus(int newStatus) {
7585 installStatus = newStatus;
7586 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007588 public int getInstallStatus() {
7589 return installStatus;
7590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007592 public void setTimeStamp(long newStamp) {
7593 if (newStamp != timeStamp) {
7594 timeStamp = newStamp;
7595 timeStampString = Long.toString(newStamp);
7596 }
7597 }
7598
7599 public void setTimeStamp(long newStamp, String newStampStr) {
7600 timeStamp = newStamp;
7601 timeStampString = newStampStr;
7602 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007603
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007604 public long getTimeStamp() {
7605 return timeStamp;
7606 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007607
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007608 public String getTimeStampStr() {
7609 return timeStampString;
7610 }
7611
7612 public void copyFrom(PackageSettingBase base) {
7613 grantedPermissions = base.grantedPermissions;
7614 gids = base.gids;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007616 timeStamp = base.timeStamp;
7617 timeStampString = base.timeStampString;
7618 signatures = base.signatures;
7619 permissionsFixed = base.permissionsFixed;
Dianne Hackbornbbfd58a2010-03-23 11:49:59 -07007620 haveGids = base.haveGids;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007621 disabledComponents = base.disabledComponents;
7622 enabledComponents = base.enabledComponents;
7623 enabled = base.enabled;
7624 installStatus = base.installStatus;
7625 }
7626
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007627 boolean enableComponentLP(String componentClassName) {
7628 boolean changed = disabledComponents.remove(componentClassName);
7629 changed |= enabledComponents.add(componentClassName);
7630 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007631 }
7632
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007633 boolean disableComponentLP(String componentClassName) {
7634 boolean changed = enabledComponents.remove(componentClassName);
7635 changed |= disabledComponents.add(componentClassName);
7636 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007637 }
7638
Dianne Hackbornd7c09682010-03-30 10:42:20 -07007639 boolean restoreComponentLP(String componentClassName) {
7640 boolean changed = enabledComponents.remove(componentClassName);
7641 changed |= disabledComponents.remove(componentClassName);
7642 return changed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007643 }
7644
7645 int currentEnabledStateLP(String componentName) {
7646 if (enabledComponents.contains(componentName)) {
7647 return COMPONENT_ENABLED_STATE_ENABLED;
7648 } else if (disabledComponents.contains(componentName)) {
7649 return COMPONENT_ENABLED_STATE_DISABLED;
7650 } else {
7651 return COMPONENT_ENABLED_STATE_DEFAULT;
7652 }
7653 }
7654 }
7655
7656 /**
7657 * Settings data for a particular package we know about.
7658 */
7659 static final class PackageSetting extends PackageSettingBase {
7660 int userId;
7661 PackageParser.Package pkg;
7662 SharedUserSetting sharedUser;
7663
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007664 PackageSetting(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007665 String nativeLibraryPathString, int pVersionCode, int pkgFlags) {
7666 super(name, realName, codePath, resourcePath, nativeLibraryPathString, pVersionCode,
7667 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007668 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007669
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007670 @Override
7671 public String toString() {
7672 return "PackageSetting{"
7673 + Integer.toHexString(System.identityHashCode(this))
7674 + " " + name + "/" + userId + "}";
7675 }
7676 }
7677
7678 /**
7679 * Settings data for a particular shared user ID we know about.
7680 */
7681 static final class SharedUserSetting extends GrantedPermissions {
7682 final String name;
7683 int userId;
7684 final HashSet<PackageSetting> packages = new HashSet<PackageSetting>();
7685 final PackageSignatures signatures = new PackageSignatures();
7686
7687 SharedUserSetting(String _name, int _pkgFlags) {
7688 super(_pkgFlags);
7689 name = _name;
7690 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007692 @Override
7693 public String toString() {
7694 return "SharedUserSetting{"
7695 + Integer.toHexString(System.identityHashCode(this))
7696 + " " + name + "/" + userId + "}";
7697 }
7698 }
7699
7700 /**
7701 * Holds information about dynamic settings.
7702 */
7703 private static final class Settings {
7704 private final File mSettingsFilename;
7705 private final File mBackupSettingsFilename;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007706 private final File mPackageListFilename;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007707 private final HashMap<String, PackageSetting> mPackages =
7708 new HashMap<String, PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007709 // List of replaced system applications
7710 final HashMap<String, PackageSetting> mDisabledSysPackages =
7711 new HashMap<String, PackageSetting>();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007712
Dianne Hackbornf22221f2010-04-05 18:35:42 -07007713 // These are the last platform API version we were using for
7714 // the apps installed on internal and external storage. It is
7715 // used to grant newer permissions one time during a system upgrade.
7716 int mInternalSdkPlatform;
7717 int mExternalSdkPlatform;
7718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007719 // The user's preferred activities associated with particular intent
7720 // filters.
7721 private final IntentResolver<PreferredActivity, PreferredActivity> mPreferredActivities =
7722 new IntentResolver<PreferredActivity, PreferredActivity>() {
7723 @Override
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007724 protected String packageForFilter(PreferredActivity filter) {
7725 return filter.mActivity.getPackageName();
7726 }
7727 @Override
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007728 protected void dumpFilter(PrintWriter out, String prefix,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007729 PreferredActivity filter) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007730 out.print(prefix); out.print(
7731 Integer.toHexString(System.identityHashCode(filter)));
7732 out.print(' ');
7733 out.print(filter.mActivity.flattenToShortString());
7734 out.print(" match=0x");
7735 out.println( Integer.toHexString(filter.mMatch));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007736 if (filter.mSetComponents != null) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007737 out.print(prefix); out.println(" Selected from:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007738 for (int i=0; i<filter.mSetComponents.length; i++) {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07007739 out.print(prefix); out.print(" ");
7740 out.println(filter.mSetComponents[i]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007741 }
7742 }
7743 }
7744 };
7745 private final HashMap<String, SharedUserSetting> mSharedUsers =
7746 new HashMap<String, SharedUserSetting>();
7747 private final ArrayList<Object> mUserIds = new ArrayList<Object>();
7748 private final SparseArray<Object> mOtherUserIds =
7749 new SparseArray<Object>();
7750
7751 // For reading/writing settings file.
7752 private final ArrayList<Signature> mPastSignatures =
7753 new ArrayList<Signature>();
7754
7755 // Mapping from permission names to info about them.
7756 final HashMap<String, BasePermission> mPermissions =
7757 new HashMap<String, BasePermission>();
7758
7759 // Mapping from permission tree names to info about them.
7760 final HashMap<String, BasePermission> mPermissionTrees =
7761 new HashMap<String, BasePermission>();
7762
Dianne Hackborne83cefce2010-02-04 17:38:14 -08007763 // Packages that have been uninstalled and still need their external
7764 // storage data deleted.
7765 final ArrayList<String> mPackagesToBeCleaned = new ArrayList<String>();
7766
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007767 // Packages that have been renamed since they were first installed.
7768 // Keys are the new names of the packages, values are the original
7769 // names. The packages appear everwhere else under their original
7770 // names.
7771 final HashMap<String, String> mRenamedPackages = new HashMap<String, String>();
7772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007773 private final StringBuilder mReadMessages = new StringBuilder();
7774
7775 private static final class PendingPackage extends PackageSettingBase {
7776 final int sharedId;
7777
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007778 PendingPackage(String name, String realName, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007779 String nativeLibraryPathString, int sharedId, int pVersionCode, int pkgFlags) {
7780 super(name, realName, codePath, resourcePath, nativeLibraryPathString,
7781 pVersionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007782 this.sharedId = sharedId;
7783 }
7784 }
7785 private final ArrayList<PendingPackage> mPendingPackages
7786 = new ArrayList<PendingPackage>();
7787
7788 Settings() {
7789 File dataDir = Environment.getDataDirectory();
7790 File systemDir = new File(dataDir, "system");
Oscar Montemayora8529f62009-11-18 10:14:20 -08007791 // TODO(oam): This secure dir creation needs to be moved somewhere else (later)
7792 File systemSecureDir = new File(dataDir, "secure/system");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007793 systemDir.mkdirs();
Oscar Montemayora8529f62009-11-18 10:14:20 -08007794 systemSecureDir.mkdirs();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007795 FileUtils.setPermissions(systemDir.toString(),
7796 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7797 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7798 -1, -1);
Oscar Montemayora8529f62009-11-18 10:14:20 -08007799 FileUtils.setPermissions(systemSecureDir.toString(),
7800 FileUtils.S_IRWXU|FileUtils.S_IRWXG
7801 |FileUtils.S_IROTH|FileUtils.S_IXOTH,
7802 -1, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007803 mSettingsFilename = new File(systemDir, "packages.xml");
7804 mBackupSettingsFilename = new File(systemDir, "packages-backup.xml");
David 'Digit' Turneradd13762010-02-03 17:34:58 -08007805 mPackageListFilename = new File(systemDir, "packages.list");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007806 }
7807
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007808 PackageSetting getPackageLP(PackageParser.Package pkg, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007809 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007810 String nativeLibraryPathString, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007811 final String name = pkg.packageName;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007812 PackageSetting p = getPackageLP(name, origPackage, realName, sharedUser, codePath,
Kenny Root806cc132010-09-12 08:34:19 -07007813 resourcePath, nativeLibraryPathString, pkg.mVersionCode, pkgFlags, create, add);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007814 return p;
7815 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007816
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007817 PackageSetting peekPackageLP(String name) {
7818 return mPackages.get(name);
7819 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007820 PackageSetting p = mPackages.get(name);
7821 if (p != null && p.codePath.getPath().equals(codePath)) {
7822 return p;
7823 }
7824 return null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07007825 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007826 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007827
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007828 void setInstallStatus(String pkgName, int status) {
7829 PackageSetting p = mPackages.get(pkgName);
7830 if(p != null) {
7831 if(p.getInstallStatus() != status) {
7832 p.setInstallStatus(status);
7833 }
7834 }
7835 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007836
Jacek Surazski65e13172009-04-28 15:26:38 +02007837 void setInstallerPackageName(String pkgName,
7838 String installerPkgName) {
7839 PackageSetting p = mPackages.get(pkgName);
7840 if(p != null) {
7841 p.setInstallerPackageName(installerPkgName);
7842 }
7843 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007844
Jacek Surazski65e13172009-04-28 15:26:38 +02007845 String getInstallerPackageName(String pkgName) {
7846 PackageSetting p = mPackages.get(pkgName);
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007847 return (p == null) ? null : p.getInstallerPackageName();
Jacek Surazski65e13172009-04-28 15:26:38 +02007848 }
7849
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007850 int getInstallStatus(String pkgName) {
7851 PackageSetting p = mPackages.get(pkgName);
7852 if(p != null) {
7853 return p.getInstallStatus();
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007855 return -1;
7856 }
7857
7858 SharedUserSetting getSharedUserLP(String name,
7859 int pkgFlags, boolean create) {
7860 SharedUserSetting s = mSharedUsers.get(name);
7861 if (s == null) {
7862 if (!create) {
7863 return null;
7864 }
7865 s = new SharedUserSetting(name, pkgFlags);
7866 if (MULTIPLE_APPLICATION_UIDS) {
7867 s.userId = newUserIdLP(s);
7868 } else {
7869 s.userId = FIRST_APPLICATION_UID;
7870 }
7871 Log.i(TAG, "New shared user " + name + ": id=" + s.userId);
7872 // < 0 means we couldn't assign a userid; fall out and return
7873 // s, which is currently null
7874 if (s.userId >= 0) {
7875 mSharedUsers.put(name, s);
7876 }
7877 }
7878
7879 return s;
7880 }
7881
7882 int disableSystemPackageLP(String name) {
7883 PackageSetting p = mPackages.get(name);
7884 if(p == null) {
7885 Log.w(TAG, "Package:"+name+" is not an installed package");
7886 return -1;
7887 }
7888 PackageSetting dp = mDisabledSysPackages.get(name);
7889 // always make sure the system package code and resource paths dont change
7890 if(dp == null) {
7891 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7892 p.pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7893 }
7894 mDisabledSysPackages.put(name, p);
7895 }
7896 return removePackageLP(name);
7897 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007899 PackageSetting enableSystemPackageLP(String name) {
7900 PackageSetting p = mDisabledSysPackages.get(name);
7901 if(p == null) {
7902 Log.w(TAG, "Package:"+name+" is not disabled");
7903 return null;
7904 }
7905 // Reset flag in ApplicationInfo object
7906 if((p.pkg != null) && (p.pkg.applicationInfo != null)) {
7907 p.pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
7908 }
Kenny Root806cc132010-09-12 08:34:19 -07007909 PackageSetting ret = addPackageLP(name, p.realName, p.codePath, p.resourcePath,
7910 p.nativeLibraryPathString, p.userId, p.versionCode, p.pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007911 mDisabledSysPackages.remove(name);
7912 return ret;
7913 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08007914
Kenny Root806cc132010-09-12 08:34:19 -07007915 PackageSetting addPackageLP(String name, String realName, File codePath, File resourcePath,
7916 String nativeLibraryPathString, int uid, int vc, int pkgFlags) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007917 PackageSetting p = mPackages.get(name);
7918 if (p != null) {
7919 if (p.userId == uid) {
7920 return p;
7921 }
7922 reportSettingsProblem(Log.ERROR,
7923 "Adding duplicate package, keeping first: " + name);
7924 return null;
7925 }
Kenny Root806cc132010-09-12 08:34:19 -07007926 p = new PackageSetting(name, realName, codePath, resourcePath, nativeLibraryPathString,
7927 vc, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007928 p.userId = uid;
7929 if (addUserIdLP(uid, p, name)) {
7930 mPackages.put(name, p);
7931 return p;
7932 }
7933 return null;
7934 }
7935
7936 SharedUserSetting addSharedUserLP(String name, int uid, int pkgFlags) {
7937 SharedUserSetting s = mSharedUsers.get(name);
7938 if (s != null) {
7939 if (s.userId == uid) {
7940 return s;
7941 }
7942 reportSettingsProblem(Log.ERROR,
7943 "Adding duplicate shared user, keeping first: " + name);
7944 return null;
7945 }
7946 s = new SharedUserSetting(name, pkgFlags);
7947 s.userId = uid;
7948 if (addUserIdLP(uid, s, name)) {
7949 mSharedUsers.put(name, s);
7950 return s;
7951 }
7952 return null;
7953 }
7954
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007955 // Transfer ownership of permissions from one package to another.
7956 private void transferPermissions(String origPkg, String newPkg) {
7957 // Transfer ownership of permissions to the new package.
7958 for (int i=0; i<2; i++) {
7959 HashMap<String, BasePermission> permissions =
7960 i == 0 ? mPermissionTrees : mPermissions;
7961 for (BasePermission bp : permissions.values()) {
7962 if (origPkg.equals(bp.sourcePackage)) {
7963 if (DEBUG_UPGRADE) Log.v(TAG,
7964 "Moving permission " + bp.name
7965 + " from pkg " + bp.sourcePackage
7966 + " to " + newPkg);
7967 bp.sourcePackage = newPkg;
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007968 bp.packageSetting = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007969 bp.perm = null;
7970 if (bp.pendingInfo != null) {
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07007971 bp.pendingInfo.packageName = newPkg;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08007972 }
7973 bp.uid = 0;
7974 bp.gids = null;
7975 }
7976 }
7977 }
7978 }
7979
7980 private PackageSetting getPackageLP(String name, PackageSetting origPackage,
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08007981 String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
Kenny Root806cc132010-09-12 08:34:19 -07007982 String nativeLibraryPathString, int vc, int pkgFlags, boolean create, boolean add) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007983 PackageSetting p = mPackages.get(name);
7984 if (p != null) {
7985 if (!p.codePath.equals(codePath)) {
7986 // Check to see if its a disabled system app
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007987 if((p != null) && ((p.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
Suchi Amalapurapub24a9672009-07-01 14:04:43 -07007988 // This is an updated system app with versions in both system
7989 // and data partition. Just let the most recent version
7990 // take precedence.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007991 Slog.w(TAG, "Trying to update system app code path from " +
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07007992 p.codePathString + " to " + codePath.toString());
Suchi Amalapurapuea5c0442009-07-13 10:36:15 -07007993 } else {
Dianne Hackborn9e0f5d92010-02-22 15:05:42 -08007994 // Just a change in the code path is not an issue, but
7995 // let's log a message about it.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08007996 Slog.i(TAG, "Package " + name + " codePath changed from " + p.codePath
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007997 + " to " + codePath + "; Retaining data and using new");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08007998 }
Dianne Hackborna33e3f72009-09-29 17:28:24 -07007999 }
8000 if (p.sharedUser != sharedUser) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008001 reportSettingsProblem(Log.WARN,
8002 "Package " + name + " shared user changed from "
8003 + (p.sharedUser != null ? p.sharedUser.name : "<nothing>")
8004 + " to "
8005 + (sharedUser != null ? sharedUser.name : "<nothing>")
8006 + "; replacing with new");
8007 p = null;
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008008 } else {
8009 if ((pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0) {
8010 // If what we are scanning is a system package, then
8011 // make it so, regardless of whether it was previously
8012 // installed only in the data partition.
8013 p.pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008015 }
8016 }
8017 if (p == null) {
8018 // Create a new PackageSettings entry. this can end up here because
8019 // of code path mismatch or user id mismatch of an updated system partition
8020 if (!create) {
8021 return null;
8022 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008023 if (origPackage != null) {
8024 // We are consuming the data from an existing package.
Kenny Root806cc132010-09-12 08:34:19 -07008025 p = new PackageSetting(origPackage.name, name, codePath, resourcePath,
8026 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008027 if (DEBUG_UPGRADE) Log.v(TAG, "Package " + name
8028 + " is adopting original package " + origPackage.name);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008029 // Note that we will retain the new package's signature so
8030 // that we can keep its data.
8031 PackageSignatures s = p.signatures;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008032 p.copyFrom(origPackage);
Dianne Hackborn4b450412010-03-11 16:20:08 -08008033 p.signatures = s;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008034 p.sharedUser = origPackage.sharedUser;
8035 p.userId = origPackage.userId;
8036 p.origPackage = origPackage;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008037 mRenamedPackages.put(name, origPackage.name);
8038 name = origPackage.name;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008039 // Update new package state.
8040 p.setTimeStamp(codePath.lastModified());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008041 } else {
Kenny Root806cc132010-09-12 08:34:19 -07008042 p = new PackageSetting(name, realName, codePath, resourcePath,
8043 nativeLibraryPathString, vc, pkgFlags);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008044 p.setTimeStamp(codePath.lastModified());
8045 p.sharedUser = sharedUser;
8046 if (sharedUser != null) {
8047 p.userId = sharedUser.userId;
8048 } else if (MULTIPLE_APPLICATION_UIDS) {
8049 // Clone the setting here for disabled system packages
8050 PackageSetting dis = mDisabledSysPackages.get(name);
8051 if (dis != null) {
8052 // For disabled packages a new setting is created
8053 // from the existing user id. This still has to be
8054 // added to list of user id's
8055 // Copy signatures from previous setting
8056 if (dis.signatures.mSignatures != null) {
8057 p.signatures.mSignatures = dis.signatures.mSignatures.clone();
8058 }
8059 p.userId = dis.userId;
8060 // Clone permissions
8061 p.grantedPermissions = new HashSet<String>(dis.grantedPermissions);
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008062 // Clone component info
8063 p.disabledComponents = new HashSet<String>(dis.disabledComponents);
8064 p.enabledComponents = new HashSet<String>(dis.enabledComponents);
8065 // Add new setting to list of user ids
8066 addUserIdLP(p.userId, p, name);
8067 } else {
8068 // Assign new user id
8069 p.userId = newUserIdLP(p);
8070 }
8071 } else {
8072 p.userId = FIRST_APPLICATION_UID;
8073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008074 }
8075 if (p.userId < 0) {
8076 reportSettingsProblem(Log.WARN,
8077 "Package " + name + " could not be assigned a valid uid");
8078 return null;
8079 }
8080 if (add) {
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008081 // Finish adding new package by adding it and updating shared
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008082 // user preferences
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008083 addPackageSettingLP(p, name, sharedUser);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008084 }
8085 }
8086 return p;
8087 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008088
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008089 private void insertPackageSettingLP(PackageSetting p, PackageParser.Package pkg) {
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008090 p.pkg = pkg;
Dianne Hackborn46730fc2010-07-24 16:32:42 -07008091 pkg.mSetEnabled = p.enabled;
Kenny Root85387d72010-08-26 10:13:11 -07008092 final String codePath = pkg.applicationInfo.sourceDir;
8093 final String resourcePath = pkg.applicationInfo.publicSourceDir;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008094 // Update code path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008095 if (!codePath.equalsIgnoreCase(p.codePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008096 Slog.w(TAG, "Code path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008097 " changing from " + p.codePathString + " to " + codePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008098 p.codePath = new File(codePath);
8099 p.codePathString = codePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008100 }
8101 //Update resource path if needed
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008102 if (!resourcePath.equalsIgnoreCase(p.resourcePathString)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008103 Slog.w(TAG, "Resource path for pkg : " + p.pkg.packageName +
Dianne Hackborna33e3f72009-09-29 17:28:24 -07008104 " changing from " + p.resourcePathString + " to " + resourcePath);
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08008105 p.resourcePath = new File(resourcePath);
8106 p.resourcePathString = resourcePath;
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008107 }
Kenny Root85387d72010-08-26 10:13:11 -07008108 // Update the native library path if needed
8109 final String nativeLibraryPath = pkg.applicationInfo.nativeLibraryDir;
8110 if (nativeLibraryPath != null
8111 && !nativeLibraryPath.equalsIgnoreCase(p.nativeLibraryPathString)) {
8112 p.nativeLibraryPathString = nativeLibraryPath;
8113 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008114 // Update version code if needed
8115 if (pkg.mVersionCode != p.versionCode) {
8116 p.versionCode = pkg.mVersionCode;
8117 }
Suchi Amalapurapuae181712010-03-30 14:01:02 -07008118 // Update signatures if needed.
8119 if (p.signatures.mSignatures == null) {
8120 p.signatures.assignSignatures(pkg.mSignatures);
8121 }
8122 // If this app defines a shared user id initialize
8123 // the shared user signatures as well.
8124 if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
8125 p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
8126 }
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008127 addPackageSettingLP(p, pkg.packageName, p.sharedUser);
8128 }
8129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008130 // Utility method that adds a PackageSetting to mPackages and
8131 // completes updating the shared user attributes
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008132 private void addPackageSettingLP(PackageSetting p, String name,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008133 SharedUserSetting sharedUser) {
8134 mPackages.put(name, p);
8135 if (sharedUser != null) {
8136 if (p.sharedUser != null && p.sharedUser != sharedUser) {
8137 reportSettingsProblem(Log.ERROR,
8138 "Package " + p.name + " was user "
8139 + p.sharedUser + " but is now " + sharedUser
8140 + "; I am not changing its files so it will probably fail!");
8141 p.sharedUser.packages.remove(p);
8142 } else if (p.userId != sharedUser.userId) {
8143 reportSettingsProblem(Log.ERROR,
8144 "Package " + p.name + " was user id " + p.userId
8145 + " but is now user " + sharedUser
8146 + " with id " + sharedUser.userId
8147 + "; I am not changing its files so it will probably fail!");
8148 }
8149
8150 sharedUser.packages.add(p);
8151 p.sharedUser = sharedUser;
8152 p.userId = sharedUser.userId;
8153 }
8154 }
8155
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008156 /*
8157 * Update the shared user setting when a package using
8158 * specifying the shared user id is removed. The gids
8159 * associated with each permission of the deleted package
8160 * are removed from the shared user's gid list only if its
8161 * not in use by other permissions of packages in the
8162 * shared user setting.
8163 */
8164 private void updateSharedUserPermsLP(PackageSetting deletedPs, int[] globalGids) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008165 if ( (deletedPs == null) || (deletedPs.pkg == null)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008166 Slog.i(TAG, "Trying to update info for null package. Just ignoring");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008167 return;
8168 }
8169 // No sharedUserId
8170 if (deletedPs.sharedUser == null) {
8171 return;
8172 }
8173 SharedUserSetting sus = deletedPs.sharedUser;
8174 // Update permissions
8175 for (String eachPerm: deletedPs.pkg.requestedPermissions) {
8176 boolean used = false;
8177 if (!sus.grantedPermissions.contains (eachPerm)) {
8178 continue;
8179 }
8180 for (PackageSetting pkg:sus.packages) {
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008181 if (pkg.pkg != null &&
Dianne Hackbornf657b632010-03-22 18:08:07 -07008182 !pkg.pkg.packageName.equals(deletedPs.pkg.packageName) &&
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008183 pkg.pkg.requestedPermissions.contains(eachPerm)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008184 used = true;
8185 break;
8186 }
8187 }
8188 if (!used) {
8189 // can safely delete this permission from list
8190 sus.grantedPermissions.remove(eachPerm);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008191 }
8192 }
8193 // Update gids
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008194 int newGids[] = globalGids;
8195 for (String eachPerm : sus.grantedPermissions) {
8196 BasePermission bp = mPermissions.get(eachPerm);
Suchi Amalapurapud83006c2009-10-28 23:39:46 -07008197 if (bp != null) {
8198 newGids = appendInts(newGids, bp.gids);
8199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008200 }
8201 sus.gids = newGids;
8202 }
Suchi Amalapurapu2ed287b2009-08-05 12:43:00 -07008203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008204 private int removePackageLP(String name) {
8205 PackageSetting p = mPackages.get(name);
8206 if (p != null) {
8207 mPackages.remove(name);
8208 if (p.sharedUser != null) {
8209 p.sharedUser.packages.remove(p);
8210 if (p.sharedUser.packages.size() == 0) {
8211 mSharedUsers.remove(p.sharedUser.name);
8212 removeUserIdLP(p.sharedUser.userId);
8213 return p.sharedUser.userId;
8214 }
8215 } else {
8216 removeUserIdLP(p.userId);
8217 return p.userId;
8218 }
8219 }
8220 return -1;
8221 }
8222
8223 private boolean addUserIdLP(int uid, Object obj, Object name) {
8224 if (uid >= FIRST_APPLICATION_UID + MAX_APPLICATION_UIDS) {
8225 return false;
8226 }
8227
8228 if (uid >= FIRST_APPLICATION_UID) {
8229 int N = mUserIds.size();
8230 final int index = uid - FIRST_APPLICATION_UID;
8231 while (index >= N) {
8232 mUserIds.add(null);
8233 N++;
8234 }
8235 if (mUserIds.get(index) != null) {
8236 reportSettingsProblem(Log.ERROR,
Suchi Amalapurapu261e66a2009-07-27 15:21:34 -07008237 "Adding duplicate user id: " + uid
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008238 + " name=" + name);
8239 return false;
8240 }
8241 mUserIds.set(index, obj);
8242 } else {
8243 if (mOtherUserIds.get(uid) != null) {
8244 reportSettingsProblem(Log.ERROR,
8245 "Adding duplicate shared id: " + uid
8246 + " name=" + name);
8247 return false;
8248 }
8249 mOtherUserIds.put(uid, obj);
8250 }
8251 return true;
8252 }
8253
8254 public Object getUserIdLP(int uid) {
8255 if (uid >= FIRST_APPLICATION_UID) {
8256 int N = mUserIds.size();
8257 final int index = uid - FIRST_APPLICATION_UID;
8258 return index < N ? mUserIds.get(index) : null;
8259 } else {
8260 return mOtherUserIds.get(uid);
8261 }
8262 }
8263
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08008264 private Set<String> findPackagesWithFlag(int flag) {
8265 Set<String> ret = new HashSet<String>();
8266 for (PackageSetting ps : mPackages.values()) {
8267 // Has to match atleast all the flag bits set on flag
8268 if ((ps.pkgFlags & flag) == flag) {
8269 ret.add(ps.name);
8270 }
8271 }
8272 return ret;
8273 }
8274
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008275 private void removeUserIdLP(int uid) {
8276 if (uid >= FIRST_APPLICATION_UID) {
8277 int N = mUserIds.size();
8278 final int index = uid - FIRST_APPLICATION_UID;
8279 if (index < N) mUserIds.set(index, null);
8280 } else {
8281 mOtherUserIds.remove(uid);
8282 }
8283 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008284
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008285 void writeLP() {
8286 //Debug.startMethodTracing("/data/system/packageprof", 8 * 1024 * 1024);
8287
8288 // Keep the old settings around until we know the new ones have
8289 // been successfully written.
8290 if (mSettingsFilename.exists()) {
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008291 // Presence of backup settings file indicates that we failed
8292 // to persist settings earlier. So preserve the older
8293 // backup for future reference since the current settings
8294 // might have been corrupted.
8295 if (!mBackupSettingsFilename.exists()) {
8296 if (!mSettingsFilename.renameTo(mBackupSettingsFilename)) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008297 Slog.w(TAG, "Unable to backup package manager settings, current changes will be lost at reboot");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008298 return;
8299 }
8300 } else {
Dianne Hackborn1afd1c92010-03-18 22:47:17 -07008301 mSettingsFilename.delete();
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008302 Slog.w(TAG, "Preserving older settings backup");
Suchi Amalapurapu3d7e8552009-09-17 15:38:20 -07008303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008304 }
8305
8306 mPastSignatures.clear();
8307
8308 try {
8309 FileOutputStream str = new FileOutputStream(mSettingsFilename);
8310
8311 //XmlSerializer serializer = XmlUtils.serializerInstance();
8312 XmlSerializer serializer = new FastXmlSerializer();
8313 serializer.setOutput(str, "utf-8");
8314 serializer.startDocument(null, true);
8315 serializer.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);
8316
8317 serializer.startTag(null, "packages");
8318
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008319 serializer.startTag(null, "last-platform-version");
8320 serializer.attribute(null, "internal", Integer.toString(mInternalSdkPlatform));
8321 serializer.attribute(null, "external", Integer.toString(mExternalSdkPlatform));
8322 serializer.endTag(null, "last-platform-version");
8323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008324 serializer.startTag(null, "permission-trees");
8325 for (BasePermission bp : mPermissionTrees.values()) {
8326 writePermission(serializer, bp);
8327 }
8328 serializer.endTag(null, "permission-trees");
8329
8330 serializer.startTag(null, "permissions");
8331 for (BasePermission bp : mPermissions.values()) {
8332 writePermission(serializer, bp);
8333 }
8334 serializer.endTag(null, "permissions");
8335
8336 for (PackageSetting pkg : mPackages.values()) {
8337 writePackage(serializer, pkg);
8338 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008340 for (PackageSetting pkg : mDisabledSysPackages.values()) {
8341 writeDisabledSysPackage(serializer, pkg);
8342 }
8343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008344 serializer.startTag(null, "preferred-activities");
8345 for (PreferredActivity pa : mPreferredActivities.filterSet()) {
8346 serializer.startTag(null, "item");
8347 pa.writeToXml(serializer);
8348 serializer.endTag(null, "item");
8349 }
8350 serializer.endTag(null, "preferred-activities");
8351
8352 for (SharedUserSetting usr : mSharedUsers.values()) {
8353 serializer.startTag(null, "shared-user");
8354 serializer.attribute(null, "name", usr.name);
8355 serializer.attribute(null, "userId",
8356 Integer.toString(usr.userId));
8357 usr.signatures.writeXml(serializer, "sigs", mPastSignatures);
8358 serializer.startTag(null, "perms");
8359 for (String name : usr.grantedPermissions) {
8360 serializer.startTag(null, "item");
8361 serializer.attribute(null, "name", name);
8362 serializer.endTag(null, "item");
8363 }
8364 serializer.endTag(null, "perms");
8365 serializer.endTag(null, "shared-user");
8366 }
8367
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008368 if (mPackagesToBeCleaned.size() > 0) {
8369 for (int i=0; i<mPackagesToBeCleaned.size(); i++) {
8370 serializer.startTag(null, "cleaning-package");
8371 serializer.attribute(null, "name", mPackagesToBeCleaned.get(i));
8372 serializer.endTag(null, "cleaning-package");
8373 }
8374 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008375
8376 if (mRenamedPackages.size() > 0) {
8377 for (HashMap.Entry<String, String> e : mRenamedPackages.entrySet()) {
8378 serializer.startTag(null, "renamed-package");
8379 serializer.attribute(null, "new", e.getKey());
8380 serializer.attribute(null, "old", e.getValue());
8381 serializer.endTag(null, "renamed-package");
8382 }
8383 }
8384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008385 serializer.endTag(null, "packages");
8386
8387 serializer.endDocument();
8388
8389 str.flush();
8390 str.close();
8391
8392 // New settings successfully written, old ones are no longer
8393 // needed.
8394 mBackupSettingsFilename.delete();
8395 FileUtils.setPermissions(mSettingsFilename.toString(),
8396 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8397 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8398 |FileUtils.S_IROTH,
8399 -1, -1);
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008400
8401 // Write package list file now, use a JournaledFile.
8402 //
8403 File tempFile = new File(mPackageListFilename.toString() + ".tmp");
8404 JournaledFile journal = new JournaledFile(mPackageListFilename, tempFile);
8405
8406 str = new FileOutputStream(journal.chooseForWrite());
8407 try {
8408 StringBuilder sb = new StringBuilder();
8409 for (PackageSetting pkg : mPackages.values()) {
8410 ApplicationInfo ai = pkg.pkg.applicationInfo;
Kenny Root85387d72010-08-26 10:13:11 -07008411 String dataPath = ai.dataDir;
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008412 boolean isDebug = (ai.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
8413
8414 // Avoid any application that has a space in its path
8415 // or that is handled by the system.
8416 if (dataPath.indexOf(" ") >= 0 || ai.uid <= Process.FIRST_APPLICATION_UID)
8417 continue;
8418
8419 // we store on each line the following information for now:
8420 //
8421 // pkgName - package name
8422 // userId - application-specific user id
8423 // debugFlag - 0 or 1 if the package is debuggable.
8424 // dataPath - path to package's data path
8425 //
8426 // NOTE: We prefer not to expose all ApplicationInfo flags for now.
8427 //
8428 // DO NOT MODIFY THIS FORMAT UNLESS YOU CAN ALSO MODIFY ITS USERS
8429 // FROM NATIVE CODE. AT THE MOMENT, LOOK AT THE FOLLOWING SOURCES:
8430 // system/core/run-as/run-as.c
8431 //
8432 sb.setLength(0);
8433 sb.append(ai.packageName);
8434 sb.append(" ");
8435 sb.append((int)ai.uid);
8436 sb.append(isDebug ? " 1 " : " 0 ");
8437 sb.append(dataPath);
8438 sb.append("\n");
8439 str.write(sb.toString().getBytes());
8440 }
8441 str.flush();
8442 str.close();
8443 journal.commit();
8444 }
8445 catch (Exception e) {
8446 journal.rollback();
8447 }
8448
8449 FileUtils.setPermissions(mPackageListFilename.toString(),
8450 FileUtils.S_IRUSR|FileUtils.S_IWUSR
8451 |FileUtils.S_IRGRP|FileUtils.S_IWGRP
8452 |FileUtils.S_IROTH,
8453 -1, -1);
8454
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008455 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008456
8457 } catch(XmlPullParserException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008458 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 -08008459 } catch(java.io.IOException e) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008460 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 -08008461 }
David 'Digit' Turneradd13762010-02-03 17:34:58 -08008462 // Clean up partially written files
Suchi Amalapurapu8550f252009-09-29 15:20:32 -07008463 if (mSettingsFilename.exists()) {
8464 if (!mSettingsFilename.delete()) {
8465 Log.i(TAG, "Failed to clean up mangled file: " + mSettingsFilename);
8466 }
8467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008468 //Debug.stopMethodTracing();
8469 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008470
8471 void writeDisabledSysPackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008472 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008473 serializer.startTag(null, "updated-package");
8474 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008475 if (pkg.realName != null) {
8476 serializer.attribute(null, "realName", pkg.realName);
8477 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008478 serializer.attribute(null, "codePath", pkg.codePathString);
8479 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008480 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008481 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8482 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8483 }
Kenny Root85387d72010-08-26 10:13:11 -07008484 if (pkg.nativeLibraryPathString != null) {
8485 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008487 if (pkg.sharedUser == null) {
8488 serializer.attribute(null, "userId",
8489 Integer.toString(pkg.userId));
8490 } else {
8491 serializer.attribute(null, "sharedUserId",
8492 Integer.toString(pkg.userId));
8493 }
8494 serializer.startTag(null, "perms");
8495 if (pkg.sharedUser == null) {
8496 // If this is a shared user, the permissions will
8497 // be written there. We still need to write an
8498 // empty permissions list so permissionsFixed will
8499 // be set.
8500 for (final String name : pkg.grantedPermissions) {
8501 BasePermission bp = mPermissions.get(name);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008502 if (bp != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008503 // We only need to write signature or system permissions but this wont
8504 // match the semantics of grantedPermissions. So write all permissions.
8505 serializer.startTag(null, "item");
8506 serializer.attribute(null, "name", name);
8507 serializer.endTag(null, "item");
8508 }
8509 }
8510 }
8511 serializer.endTag(null, "perms");
8512 serializer.endTag(null, "updated-package");
8513 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008514
8515 void writePackage(XmlSerializer serializer, final PackageSetting pkg)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008516 throws java.io.IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008517 serializer.startTag(null, "package");
8518 serializer.attribute(null, "name", pkg.name);
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008519 if (pkg.realName != null) {
8520 serializer.attribute(null, "realName", pkg.realName);
8521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008522 serializer.attribute(null, "codePath", pkg.codePathString);
8523 if (!pkg.resourcePathString.equals(pkg.codePathString)) {
8524 serializer.attribute(null, "resourcePath", pkg.resourcePathString);
8525 }
Kenny Root85387d72010-08-26 10:13:11 -07008526 if (pkg.nativeLibraryPathString != null) {
8527 serializer.attribute(null, "nativeLibraryPath", pkg.nativeLibraryPathString);
8528 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008529 serializer.attribute(null, "flags",
8530 Integer.toString(pkg.pkgFlags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008531 serializer.attribute(null, "ts", pkg.getTimeStampStr());
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008532 serializer.attribute(null, "version", String.valueOf(pkg.versionCode));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008533 if (pkg.sharedUser == null) {
8534 serializer.attribute(null, "userId",
8535 Integer.toString(pkg.userId));
8536 } else {
8537 serializer.attribute(null, "sharedUserId",
8538 Integer.toString(pkg.userId));
8539 }
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008540 if (pkg.uidError) {
8541 serializer.attribute(null, "uidError", "true");
8542 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008543 if (pkg.enabled != COMPONENT_ENABLED_STATE_DEFAULT) {
8544 serializer.attribute(null, "enabled",
8545 pkg.enabled == COMPONENT_ENABLED_STATE_ENABLED
8546 ? "true" : "false");
8547 }
8548 if(pkg.installStatus == PKG_INSTALL_INCOMPLETE) {
8549 serializer.attribute(null, "installStatus", "false");
8550 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008551 if (pkg.installerPackageName != null) {
8552 serializer.attribute(null, "installer", pkg.installerPackageName);
8553 }
Kenny Root93565c4b2010-06-18 15:46:06 -07008554 if (pkg.obbPathString != null) {
8555 serializer.attribute(null, "obbPath", pkg.obbPathString);
8556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008557 pkg.signatures.writeXml(serializer, "sigs", mPastSignatures);
8558 if ((pkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
8559 serializer.startTag(null, "perms");
8560 if (pkg.sharedUser == null) {
8561 // If this is a shared user, the permissions will
8562 // be written there. We still need to write an
8563 // empty permissions list so permissionsFixed will
8564 // be set.
8565 for (final String name : pkg.grantedPermissions) {
8566 serializer.startTag(null, "item");
8567 serializer.attribute(null, "name", name);
8568 serializer.endTag(null, "item");
8569 }
8570 }
8571 serializer.endTag(null, "perms");
8572 }
8573 if (pkg.disabledComponents.size() > 0) {
8574 serializer.startTag(null, "disabled-components");
8575 for (final String name : pkg.disabledComponents) {
8576 serializer.startTag(null, "item");
8577 serializer.attribute(null, "name", name);
8578 serializer.endTag(null, "item");
8579 }
8580 serializer.endTag(null, "disabled-components");
8581 }
8582 if (pkg.enabledComponents.size() > 0) {
8583 serializer.startTag(null, "enabled-components");
8584 for (final String name : pkg.enabledComponents) {
8585 serializer.startTag(null, "item");
8586 serializer.attribute(null, "name", name);
8587 serializer.endTag(null, "item");
8588 }
8589 serializer.endTag(null, "enabled-components");
8590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008592 serializer.endTag(null, "package");
8593 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008595 void writePermission(XmlSerializer serializer, BasePermission bp)
8596 throws XmlPullParserException, java.io.IOException {
8597 if (bp.type != BasePermission.TYPE_BUILTIN
8598 && bp.sourcePackage != null) {
8599 serializer.startTag(null, "item");
8600 serializer.attribute(null, "name", bp.name);
8601 serializer.attribute(null, "package", bp.sourcePackage);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008602 if (bp.protectionLevel !=
8603 PermissionInfo.PROTECTION_NORMAL) {
8604 serializer.attribute(null, "protection",
8605 Integer.toString(bp.protectionLevel));
8606 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008607 if (DEBUG_SETTINGS) Log.v(TAG,
8608 "Writing perm: name=" + bp.name + " type=" + bp.type);
8609 if (bp.type == BasePermission.TYPE_DYNAMIC) {
8610 PermissionInfo pi = bp.perm != null ? bp.perm.info
8611 : bp.pendingInfo;
8612 if (pi != null) {
8613 serializer.attribute(null, "type", "dynamic");
8614 if (pi.icon != 0) {
8615 serializer.attribute(null, "icon",
8616 Integer.toString(pi.icon));
8617 }
8618 if (pi.nonLocalizedLabel != null) {
8619 serializer.attribute(null, "label",
8620 pi.nonLocalizedLabel.toString());
8621 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008622 }
8623 }
8624 serializer.endTag(null, "item");
8625 }
8626 }
8627
8628 String getReadMessagesLP() {
8629 return mReadMessages.toString();
8630 }
8631
Oscar Montemayora8529f62009-11-18 10:14:20 -08008632 ArrayList<PackageSetting> getListOfIncompleteInstallPackages() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008633 HashSet<String> kList = new HashSet<String>(mPackages.keySet());
8634 Iterator<String> its = kList.iterator();
Oscar Montemayora8529f62009-11-18 10:14:20 -08008635 ArrayList<PackageSetting> ret = new ArrayList<PackageSetting>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008636 while(its.hasNext()) {
8637 String key = its.next();
8638 PackageSetting ps = mPackages.get(key);
8639 if(ps.getInstallStatus() == PKG_INSTALL_INCOMPLETE) {
Oscar Montemayora8529f62009-11-18 10:14:20 -08008640 ret.add(ps);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008641 }
8642 }
8643 return ret;
8644 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008645
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008646 boolean readLP() {
8647 FileInputStream str = null;
8648 if (mBackupSettingsFilename.exists()) {
8649 try {
8650 str = new FileInputStream(mBackupSettingsFilename);
8651 mReadMessages.append("Reading from backup settings file\n");
8652 Log.i(TAG, "Reading from backup settings file!");
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008653 if (mSettingsFilename.exists()) {
8654 // If both the backup and settings file exist, we
8655 // ignore the settings since it might have been
8656 // corrupted.
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008657 Slog.w(TAG, "Cleaning up settings file " + mSettingsFilename);
Suchi Amalapurapu14e833f2009-10-20 11:27:32 -07008658 mSettingsFilename.delete();
8659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008660 } catch (java.io.IOException e) {
8661 // We'll try for the normal settings file.
8662 }
8663 }
8664
8665 mPastSignatures.clear();
8666
8667 try {
8668 if (str == null) {
8669 if (!mSettingsFilename.exists()) {
8670 mReadMessages.append("No settings file found\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008671 Slog.i(TAG, "No current settings file!");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008672 return false;
8673 }
8674 str = new FileInputStream(mSettingsFilename);
8675 }
8676 XmlPullParser parser = Xml.newPullParser();
8677 parser.setInput(str, null);
8678
8679 int type;
8680 while ((type=parser.next()) != XmlPullParser.START_TAG
8681 && type != XmlPullParser.END_DOCUMENT) {
8682 ;
8683 }
8684
8685 if (type != XmlPullParser.START_TAG) {
8686 mReadMessages.append("No start tag found in settings file\n");
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008687 Slog.e(TAG, "No start tag found in package manager settings");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008688 return false;
8689 }
8690
8691 int outerDepth = parser.getDepth();
8692 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8693 && (type != XmlPullParser.END_TAG
8694 || parser.getDepth() > outerDepth)) {
8695 if (type == XmlPullParser.END_TAG
8696 || type == XmlPullParser.TEXT) {
8697 continue;
8698 }
8699
8700 String tagName = parser.getName();
8701 if (tagName.equals("package")) {
8702 readPackageLP(parser);
8703 } else if (tagName.equals("permissions")) {
8704 readPermissionsLP(mPermissions, parser);
8705 } else if (tagName.equals("permission-trees")) {
8706 readPermissionsLP(mPermissionTrees, parser);
8707 } else if (tagName.equals("shared-user")) {
8708 readSharedUserLP(parser);
8709 } else if (tagName.equals("preferred-packages")) {
Dianne Hackborna7ca0e52009-12-01 14:31:55 -08008710 // no longer used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008711 } else if (tagName.equals("preferred-activities")) {
8712 readPreferredActivitiesLP(parser);
8713 } else if(tagName.equals("updated-package")) {
8714 readDisabledSysPackageLP(parser);
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008715 } else if (tagName.equals("cleaning-package")) {
8716 String name = parser.getAttributeValue(null, "name");
8717 if (name != null) {
8718 mPackagesToBeCleaned.add(name);
8719 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008720 } else if (tagName.equals("renamed-package")) {
8721 String nname = parser.getAttributeValue(null, "new");
8722 String oname = parser.getAttributeValue(null, "old");
8723 if (nname != null && oname != null) {
8724 mRenamedPackages.put(nname, oname);
8725 }
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008726 } else if (tagName.equals("last-platform-version")) {
8727 mInternalSdkPlatform = mExternalSdkPlatform = 0;
8728 try {
8729 String internal = parser.getAttributeValue(null, "internal");
8730 if (internal != null) {
8731 mInternalSdkPlatform = Integer.parseInt(internal);
8732 }
8733 String external = parser.getAttributeValue(null, "external");
8734 if (external != null) {
Bryan Mawhinney2131a3c2010-04-23 14:38:31 +01008735 mExternalSdkPlatform = Integer.parseInt(external);
Dianne Hackbornf22221f2010-04-05 18:35:42 -07008736 }
8737 } catch (NumberFormatException e) {
8738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008739 } else {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008740 Slog.w(TAG, "Unknown element under <packages>: "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008741 + parser.getName());
8742 XmlUtils.skipCurrentTag(parser);
8743 }
8744 }
8745
8746 str.close();
8747
8748 } catch(XmlPullParserException e) {
8749 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008750 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008751
8752 } catch(java.io.IOException e) {
8753 mReadMessages.append("Error reading: " + e.toString());
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008754 Slog.e(TAG, "Error reading package manager settings", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008755
8756 }
8757
8758 int N = mPendingPackages.size();
8759 for (int i=0; i<N; i++) {
8760 final PendingPackage pp = mPendingPackages.get(i);
8761 Object idObj = getUserIdLP(pp.sharedId);
8762 if (idObj != null && idObj instanceof SharedUserSetting) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008763 PackageSetting p = getPackageLP(pp.name, null, pp.realName,
Kenny Root806cc132010-09-12 08:34:19 -07008764 (SharedUserSetting) idObj, pp.codePath, pp.resourcePath,
8765 pp.nativeLibraryPathString, pp.versionCode, pp.pkgFlags, true, true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008766 if (p == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008767 Slog.w(TAG, "Unable to create application package for "
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008768 + pp.name);
8769 continue;
8770 }
8771 p.copyFrom(pp);
8772 } else if (idObj != null) {
8773 String msg = "Bad package setting: package " + pp.name
8774 + " has shared uid " + pp.sharedId
8775 + " that is not a shared uid\n";
8776 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008777 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008778 } else {
8779 String msg = "Bad package setting: package " + pp.name
8780 + " has shared uid " + pp.sharedId
8781 + " that is not defined\n";
8782 mReadMessages.append(msg);
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08008783 Slog.e(TAG, msg);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008784 }
8785 }
8786 mPendingPackages.clear();
8787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008788 mReadMessages.append("Read completed successfully: "
8789 + mPackages.size() + " packages, "
8790 + mSharedUsers.size() + " shared uids\n");
8791
8792 return true;
8793 }
8794
8795 private int readInt(XmlPullParser parser, String ns, String name,
8796 int defValue) {
8797 String v = parser.getAttributeValue(ns, name);
8798 try {
8799 if (v == null) {
8800 return defValue;
8801 }
8802 return Integer.parseInt(v);
8803 } catch (NumberFormatException e) {
8804 reportSettingsProblem(Log.WARN,
8805 "Error in package manager settings: attribute " +
8806 name + " has bad integer value " + v + " at "
8807 + parser.getPositionDescription());
8808 }
8809 return defValue;
8810 }
8811
8812 private void readPermissionsLP(HashMap<String, BasePermission> out,
8813 XmlPullParser parser)
8814 throws IOException, XmlPullParserException {
8815 int outerDepth = parser.getDepth();
8816 int type;
8817 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8818 && (type != XmlPullParser.END_TAG
8819 || parser.getDepth() > outerDepth)) {
8820 if (type == XmlPullParser.END_TAG
8821 || type == XmlPullParser.TEXT) {
8822 continue;
8823 }
8824
8825 String tagName = parser.getName();
8826 if (tagName.equals("item")) {
8827 String name = parser.getAttributeValue(null, "name");
8828 String sourcePackage = parser.getAttributeValue(null, "package");
8829 String ptype = parser.getAttributeValue(null, "type");
8830 if (name != null && sourcePackage != null) {
8831 boolean dynamic = "dynamic".equals(ptype);
8832 BasePermission bp = new BasePermission(name, sourcePackage,
8833 dynamic
8834 ? BasePermission.TYPE_DYNAMIC
8835 : BasePermission.TYPE_NORMAL);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008836 bp.protectionLevel = readInt(parser, null, "protection",
8837 PermissionInfo.PROTECTION_NORMAL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008838 if (dynamic) {
8839 PermissionInfo pi = new PermissionInfo();
8840 pi.packageName = sourcePackage.intern();
8841 pi.name = name.intern();
8842 pi.icon = readInt(parser, null, "icon", 0);
8843 pi.nonLocalizedLabel = parser.getAttributeValue(
8844 null, "label");
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07008845 pi.protectionLevel = bp.protectionLevel;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008846 bp.pendingInfo = pi;
8847 }
8848 out.put(bp.name, bp);
8849 } else {
8850 reportSettingsProblem(Log.WARN,
8851 "Error in package manager settings: permissions has"
8852 + " no name at " + parser.getPositionDescription());
8853 }
8854 } else {
8855 reportSettingsProblem(Log.WARN,
8856 "Unknown element reading permissions: "
8857 + parser.getName() + " at "
8858 + parser.getPositionDescription());
8859 }
8860 XmlUtils.skipCurrentTag(parser);
8861 }
8862 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008864 private void readDisabledSysPackageLP(XmlPullParser parser)
Dianne Hackborne83cefce2010-02-04 17:38:14 -08008865 throws XmlPullParserException, IOException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008866 String name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008867 String realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008868 String codePathStr = parser.getAttributeValue(null, "codePath");
8869 String resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root806cc132010-09-12 08:34:19 -07008870 String nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008871 if (resourcePathStr == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008872 resourcePathStr = codePathStr;
8873 }
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008874 String version = parser.getAttributeValue(null, "version");
8875 int versionCode = 0;
8876 if (version != null) {
8877 try {
8878 versionCode = Integer.parseInt(version);
8879 } catch (NumberFormatException e) {
8880 }
8881 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008883 int pkgFlags = 0;
8884 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
Kenny Root806cc132010-09-12 08:34:19 -07008885 PackageSetting ps = new PackageSetting(name, realName, new File(codePathStr),
8886 new File(resourcePathStr), nativeLibraryPathStr, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008887 String timeStampStr = parser.getAttributeValue(null, "ts");
8888 if (timeStampStr != null) {
8889 try {
8890 long timeStamp = Long.parseLong(timeStampStr);
8891 ps.setTimeStamp(timeStamp, timeStampStr);
8892 } catch (NumberFormatException e) {
8893 }
8894 }
8895 String idStr = parser.getAttributeValue(null, "userId");
8896 ps.userId = idStr != null ? Integer.parseInt(idStr) : 0;
8897 if(ps.userId <= 0) {
8898 String sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8899 ps.userId = sharedIdStr != null ? Integer.parseInt(sharedIdStr) : 0;
8900 }
8901 int outerDepth = parser.getDepth();
8902 int type;
8903 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
8904 && (type != XmlPullParser.END_TAG
8905 || parser.getDepth() > outerDepth)) {
8906 if (type == XmlPullParser.END_TAG
8907 || type == XmlPullParser.TEXT) {
8908 continue;
8909 }
8910
8911 String tagName = parser.getName();
8912 if (tagName.equals("perms")) {
8913 readGrantedPermissionsLP(parser,
8914 ps.grantedPermissions);
8915 } else {
8916 reportSettingsProblem(Log.WARN,
8917 "Unknown element under <updated-package>: "
8918 + parser.getName());
8919 XmlUtils.skipCurrentTag(parser);
8920 }
8921 }
8922 mDisabledSysPackages.put(name, ps);
8923 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08008924
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008925 private void readPackageLP(XmlPullParser parser)
8926 throws XmlPullParserException, IOException {
8927 String name = null;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008928 String realName = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008929 String idStr = null;
8930 String sharedIdStr = null;
8931 String codePathStr = null;
8932 String resourcePathStr = null;
Kenny Root85387d72010-08-26 10:13:11 -07008933 String nativeLibraryPathStr = null;
Kenny Root93565c4b2010-06-18 15:46:06 -07008934 String obbPathStr = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008935 String systemStr = null;
Jacek Surazski65e13172009-04-28 15:26:38 +02008936 String installerPackageName = null;
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008937 String uidError = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008938 int pkgFlags = 0;
8939 String timeStampStr;
8940 long timeStamp = 0;
8941 PackageSettingBase packageSetting = null;
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008942 String version = null;
8943 int versionCode = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008944 try {
8945 name = parser.getAttributeValue(null, "name");
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008946 realName = parser.getAttributeValue(null, "realName");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008947 idStr = parser.getAttributeValue(null, "userId");
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08008948 uidError = parser.getAttributeValue(null, "uidError");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008949 sharedIdStr = parser.getAttributeValue(null, "sharedUserId");
8950 codePathStr = parser.getAttributeValue(null, "codePath");
8951 resourcePathStr = parser.getAttributeValue(null, "resourcePath");
Kenny Root85387d72010-08-26 10:13:11 -07008952 nativeLibraryPathStr = parser.getAttributeValue(null, "nativeLibraryPath");
Kenny Root93565c4b2010-06-18 15:46:06 -07008953 obbPathStr = parser.getAttributeValue(null, "obbPath");
Suchi Amalapurapuc2af31f2009-05-08 14:44:41 -07008954 version = parser.getAttributeValue(null, "version");
8955 if (version != null) {
8956 try {
8957 versionCode = Integer.parseInt(version);
8958 } catch (NumberFormatException e) {
8959 }
8960 }
Jacek Surazski65e13172009-04-28 15:26:38 +02008961 installerPackageName = parser.getAttributeValue(null, "installer");
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008962
8963 systemStr = parser.getAttributeValue(null, "flags");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008964 if (systemStr != null) {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008965 try {
8966 pkgFlags = Integer.parseInt(systemStr);
8967 } catch (NumberFormatException e) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008968 }
8969 } else {
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08008970 // For backward compatibility
8971 systemStr = parser.getAttributeValue(null, "system");
8972 if (systemStr != null) {
8973 pkgFlags |= ("true".equalsIgnoreCase(systemStr)) ? ApplicationInfo.FLAG_SYSTEM : 0;
8974 } else {
8975 // Old settings that don't specify system... just treat
8976 // them as system, good enough.
8977 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
8978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008979 }
8980 timeStampStr = parser.getAttributeValue(null, "ts");
8981 if (timeStampStr != null) {
8982 try {
8983 timeStamp = Long.parseLong(timeStampStr);
8984 } catch (NumberFormatException e) {
8985 }
8986 }
8987 if (DEBUG_SETTINGS) Log.v(TAG, "Reading package: " + name
8988 + " userId=" + idStr + " sharedUserId=" + sharedIdStr);
8989 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
8990 if (resourcePathStr == null) {
8991 resourcePathStr = codePathStr;
8992 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08008993 if (realName != null) {
8994 realName = realName.intern();
8995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08008996 if (name == null) {
8997 reportSettingsProblem(Log.WARN,
8998 "Error in package manager settings: <package> has no name at "
8999 + parser.getPositionDescription());
9000 } else if (codePathStr == null) {
9001 reportSettingsProblem(Log.WARN,
9002 "Error in package manager settings: <package> has no codePath at "
9003 + parser.getPositionDescription());
9004 } else if (userId > 0) {
Kenny Root806cc132010-09-12 08:34:19 -07009005 packageSetting = addPackageLP(name.intern(), realName, new File(codePathStr),
9006 new File(resourcePathStr), nativeLibraryPathStr, userId, versionCode,
9007 pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009008 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9009 + ": userId=" + userId + " pkg=" + packageSetting);
9010 if (packageSetting == null) {
9011 reportSettingsProblem(Log.ERROR,
9012 "Failure adding uid " + userId
9013 + " while parsing settings at "
9014 + parser.getPositionDescription());
9015 } else {
9016 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9017 }
9018 } else if (sharedIdStr != null) {
9019 userId = sharedIdStr != null
9020 ? Integer.parseInt(sharedIdStr) : 0;
9021 if (userId > 0) {
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009022 packageSetting = new PendingPackage(name.intern(), realName,
9023 new File(codePathStr), new File(resourcePathStr),
Kenny Root806cc132010-09-12 08:34:19 -07009024 nativeLibraryPathStr, userId, versionCode, pkgFlags);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009025 packageSetting.setTimeStamp(timeStamp, timeStampStr);
9026 mPendingPackages.add((PendingPackage) packageSetting);
9027 if (DEBUG_SETTINGS) Log.i(TAG, "Reading package " + name
9028 + ": sharedUserId=" + userId + " pkg="
9029 + packageSetting);
9030 } else {
9031 reportSettingsProblem(Log.WARN,
9032 "Error in package manager settings: package "
9033 + name + " has bad sharedId " + sharedIdStr
9034 + " at " + parser.getPositionDescription());
9035 }
9036 } else {
9037 reportSettingsProblem(Log.WARN,
9038 "Error in package manager settings: package "
9039 + name + " has bad userId " + idStr + " at "
9040 + parser.getPositionDescription());
9041 }
9042 } catch (NumberFormatException e) {
9043 reportSettingsProblem(Log.WARN,
9044 "Error in package manager settings: package "
9045 + name + " has bad userId " + idStr + " at "
9046 + parser.getPositionDescription());
9047 }
9048 if (packageSetting != null) {
Dianne Hackbornb858dfd2010-02-02 10:49:14 -08009049 packageSetting.uidError = "true".equals(uidError);
Jacek Surazski65e13172009-04-28 15:26:38 +02009050 packageSetting.installerPackageName = installerPackageName;
Kenny Root85387d72010-08-26 10:13:11 -07009051 packageSetting.nativeLibraryPathString = nativeLibraryPathStr;
Kenny Root93565c4b2010-06-18 15:46:06 -07009052 packageSetting.obbPathString = obbPathStr;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009053 final String enabledStr = parser.getAttributeValue(null, "enabled");
9054 if (enabledStr != null) {
9055 if (enabledStr.equalsIgnoreCase("true")) {
9056 packageSetting.enabled = COMPONENT_ENABLED_STATE_ENABLED;
9057 } else if (enabledStr.equalsIgnoreCase("false")) {
9058 packageSetting.enabled = COMPONENT_ENABLED_STATE_DISABLED;
9059 } else if (enabledStr.equalsIgnoreCase("default")) {
9060 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9061 } else {
9062 reportSettingsProblem(Log.WARN,
9063 "Error in package manager settings: package "
9064 + name + " has bad enabled value: " + idStr
9065 + " at " + parser.getPositionDescription());
9066 }
9067 } else {
9068 packageSetting.enabled = COMPONENT_ENABLED_STATE_DEFAULT;
9069 }
9070 final String installStatusStr = parser.getAttributeValue(null, "installStatus");
9071 if (installStatusStr != null) {
9072 if (installStatusStr.equalsIgnoreCase("false")) {
9073 packageSetting.installStatus = PKG_INSTALL_INCOMPLETE;
9074 } else {
9075 packageSetting.installStatus = PKG_INSTALL_COMPLETE;
9076 }
9077 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009078
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009079 int outerDepth = parser.getDepth();
9080 int type;
9081 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9082 && (type != XmlPullParser.END_TAG
9083 || parser.getDepth() > outerDepth)) {
9084 if (type == XmlPullParser.END_TAG
9085 || type == XmlPullParser.TEXT) {
9086 continue;
9087 }
9088
9089 String tagName = parser.getName();
9090 if (tagName.equals("disabled-components")) {
9091 readDisabledComponentsLP(packageSetting, parser);
9092 } else if (tagName.equals("enabled-components")) {
9093 readEnabledComponentsLP(packageSetting, parser);
9094 } else if (tagName.equals("sigs")) {
9095 packageSetting.signatures.readXml(parser, mPastSignatures);
9096 } else if (tagName.equals("perms")) {
9097 readGrantedPermissionsLP(parser,
Dianne Hackbornf657b632010-03-22 18:08:07 -07009098 packageSetting.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009099 packageSetting.permissionsFixed = true;
9100 } else {
9101 reportSettingsProblem(Log.WARN,
9102 "Unknown element under <package>: "
9103 + parser.getName());
9104 XmlUtils.skipCurrentTag(parser);
9105 }
9106 }
9107 } else {
9108 XmlUtils.skipCurrentTag(parser);
9109 }
9110 }
9111
9112 private void readDisabledComponentsLP(PackageSettingBase packageSetting,
9113 XmlPullParser parser)
9114 throws IOException, XmlPullParserException {
9115 int outerDepth = parser.getDepth();
9116 int type;
9117 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9118 && (type != XmlPullParser.END_TAG
9119 || parser.getDepth() > outerDepth)) {
9120 if (type == XmlPullParser.END_TAG
9121 || type == XmlPullParser.TEXT) {
9122 continue;
9123 }
9124
9125 String tagName = parser.getName();
9126 if (tagName.equals("item")) {
9127 String name = parser.getAttributeValue(null, "name");
9128 if (name != null) {
9129 packageSetting.disabledComponents.add(name.intern());
9130 } else {
9131 reportSettingsProblem(Log.WARN,
9132 "Error in package manager settings: <disabled-components> has"
9133 + " no name at " + parser.getPositionDescription());
9134 }
9135 } else {
9136 reportSettingsProblem(Log.WARN,
9137 "Unknown element under <disabled-components>: "
9138 + parser.getName());
9139 }
9140 XmlUtils.skipCurrentTag(parser);
9141 }
9142 }
9143
9144 private void readEnabledComponentsLP(PackageSettingBase packageSetting,
9145 XmlPullParser parser)
9146 throws IOException, XmlPullParserException {
9147 int outerDepth = parser.getDepth();
9148 int type;
9149 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9150 && (type != XmlPullParser.END_TAG
9151 || parser.getDepth() > outerDepth)) {
9152 if (type == XmlPullParser.END_TAG
9153 || type == XmlPullParser.TEXT) {
9154 continue;
9155 }
9156
9157 String tagName = parser.getName();
9158 if (tagName.equals("item")) {
9159 String name = parser.getAttributeValue(null, "name");
9160 if (name != null) {
9161 packageSetting.enabledComponents.add(name.intern());
9162 } else {
9163 reportSettingsProblem(Log.WARN,
9164 "Error in package manager settings: <enabled-components> has"
9165 + " no name at " + parser.getPositionDescription());
9166 }
9167 } else {
9168 reportSettingsProblem(Log.WARN,
9169 "Unknown element under <enabled-components>: "
9170 + parser.getName());
9171 }
9172 XmlUtils.skipCurrentTag(parser);
9173 }
9174 }
9175
9176 private void readSharedUserLP(XmlPullParser parser)
9177 throws XmlPullParserException, IOException {
9178 String name = null;
9179 String idStr = null;
9180 int pkgFlags = 0;
9181 SharedUserSetting su = null;
9182 try {
9183 name = parser.getAttributeValue(null, "name");
9184 idStr = parser.getAttributeValue(null, "userId");
9185 int userId = idStr != null ? Integer.parseInt(idStr) : 0;
9186 if ("true".equals(parser.getAttributeValue(null, "system"))) {
9187 pkgFlags |= ApplicationInfo.FLAG_SYSTEM;
9188 }
9189 if (name == null) {
9190 reportSettingsProblem(Log.WARN,
9191 "Error in package manager settings: <shared-user> has no name at "
9192 + parser.getPositionDescription());
9193 } else if (userId == 0) {
9194 reportSettingsProblem(Log.WARN,
9195 "Error in package manager settings: shared-user "
9196 + name + " has bad userId " + idStr + " at "
9197 + parser.getPositionDescription());
9198 } else {
9199 if ((su=addSharedUserLP(name.intern(), userId, pkgFlags)) == null) {
9200 reportSettingsProblem(Log.ERROR,
9201 "Occurred while parsing settings at "
9202 + parser.getPositionDescription());
9203 }
9204 }
9205 } catch (NumberFormatException e) {
9206 reportSettingsProblem(Log.WARN,
9207 "Error in package manager settings: package "
9208 + name + " has bad userId " + idStr + " at "
9209 + parser.getPositionDescription());
9210 };
9211
9212 if (su != null) {
9213 int outerDepth = parser.getDepth();
9214 int type;
9215 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9216 && (type != XmlPullParser.END_TAG
9217 || parser.getDepth() > outerDepth)) {
9218 if (type == XmlPullParser.END_TAG
9219 || type == XmlPullParser.TEXT) {
9220 continue;
9221 }
9222
9223 String tagName = parser.getName();
9224 if (tagName.equals("sigs")) {
9225 su.signatures.readXml(parser, mPastSignatures);
9226 } else if (tagName.equals("perms")) {
Dianne Hackbornf657b632010-03-22 18:08:07 -07009227 readGrantedPermissionsLP(parser, su.grantedPermissions);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009228 } else {
9229 reportSettingsProblem(Log.WARN,
9230 "Unknown element under <shared-user>: "
9231 + parser.getName());
9232 XmlUtils.skipCurrentTag(parser);
9233 }
9234 }
9235
9236 } else {
9237 XmlUtils.skipCurrentTag(parser);
9238 }
9239 }
9240
9241 private void readGrantedPermissionsLP(XmlPullParser parser,
9242 HashSet<String> outPerms) throws IOException, XmlPullParserException {
9243 int outerDepth = parser.getDepth();
9244 int type;
9245 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9246 && (type != XmlPullParser.END_TAG
9247 || parser.getDepth() > outerDepth)) {
9248 if (type == XmlPullParser.END_TAG
9249 || type == XmlPullParser.TEXT) {
9250 continue;
9251 }
9252
9253 String tagName = parser.getName();
9254 if (tagName.equals("item")) {
9255 String name = parser.getAttributeValue(null, "name");
9256 if (name != null) {
9257 outPerms.add(name.intern());
9258 } else {
9259 reportSettingsProblem(Log.WARN,
9260 "Error in package manager settings: <perms> has"
9261 + " no name at " + parser.getPositionDescription());
9262 }
9263 } else {
9264 reportSettingsProblem(Log.WARN,
9265 "Unknown element under <perms>: "
9266 + parser.getName());
9267 }
9268 XmlUtils.skipCurrentTag(parser);
9269 }
9270 }
9271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009272 private void readPreferredActivitiesLP(XmlPullParser parser)
9273 throws XmlPullParserException, IOException {
9274 int outerDepth = parser.getDepth();
9275 int type;
9276 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
9277 && (type != XmlPullParser.END_TAG
9278 || parser.getDepth() > outerDepth)) {
9279 if (type == XmlPullParser.END_TAG
9280 || type == XmlPullParser.TEXT) {
9281 continue;
9282 }
9283
9284 String tagName = parser.getName();
9285 if (tagName.equals("item")) {
9286 PreferredActivity pa = new PreferredActivity(parser);
9287 if (pa.mParseError == null) {
9288 mPreferredActivities.addFilter(pa);
9289 } else {
9290 reportSettingsProblem(Log.WARN,
9291 "Error in package manager settings: <preferred-activity> "
9292 + pa.mParseError + " at "
9293 + parser.getPositionDescription());
9294 }
9295 } else {
9296 reportSettingsProblem(Log.WARN,
9297 "Unknown element under <preferred-activities>: "
9298 + parser.getName());
9299 XmlUtils.skipCurrentTag(parser);
9300 }
9301 }
9302 }
9303
9304 // Returns -1 if we could not find an available UserId to assign
9305 private int newUserIdLP(Object obj) {
9306 // Let's be stupidly inefficient for now...
9307 final int N = mUserIds.size();
9308 for (int i=0; i<N; i++) {
9309 if (mUserIds.get(i) == null) {
9310 mUserIds.set(i, obj);
9311 return FIRST_APPLICATION_UID + i;
9312 }
9313 }
9314
9315 // None left?
9316 if (N >= MAX_APPLICATION_UIDS) {
9317 return -1;
9318 }
9319
9320 mUserIds.add(obj);
9321 return FIRST_APPLICATION_UID + N;
9322 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08009323
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009324 public PackageSetting getDisabledSystemPkg(String name) {
9325 synchronized(mPackages) {
9326 PackageSetting ps = mDisabledSysPackages.get(name);
9327 return ps;
9328 }
9329 }
9330
9331 boolean isEnabledLP(ComponentInfo componentInfo, int flags) {
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009332 if ((flags&PackageManager.GET_DISABLED_COMPONENTS) != 0) {
9333 return true;
9334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009335 final PackageSetting packageSettings = mPackages.get(componentInfo.packageName);
9336 if (Config.LOGV) {
9337 Log.v(TAG, "isEnabledLock - packageName = " + componentInfo.packageName
9338 + " componentName = " + componentInfo.name);
9339 Log.v(TAG, "enabledComponents: "
9340 + Arrays.toString(packageSettings.enabledComponents.toArray()));
9341 Log.v(TAG, "disabledComponents: "
9342 + Arrays.toString(packageSettings.disabledComponents.toArray()));
9343 }
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009344 if (packageSettings == null) {
9345 if (false) {
9346 Log.w(TAG, "WAITING FOR DEBUGGER");
9347 Debug.waitForDebugger();
9348 Log.i(TAG, "We will crash!");
9349 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009350 return false;
Dianne Hackborn6dee18c2010-02-09 23:59:16 -08009351 }
Dianne Hackborn46730fc2010-07-24 16:32:42 -07009352 if (packageSettings.enabled == COMPONENT_ENABLED_STATE_DISABLED
9353 || (packageSettings.pkg != null && !packageSettings.pkg.applicationInfo.enabled
9354 && packageSettings.enabled == COMPONENT_ENABLED_STATE_DEFAULT)) {
9355 return false;
9356 }
9357 if (packageSettings.enabledComponents.contains(componentInfo.name)) {
9358 return true;
9359 }
9360 if (packageSettings.disabledComponents.contains(componentInfo.name)) {
9361 return false;
9362 }
9363 return componentInfo.enabled;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009364 }
9365 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009366
9367 // ------- apps on sdcard specific code -------
9368 static final boolean DEBUG_SD_INSTALL = false;
Kenny Root305bcbf2010-09-03 07:56:38 -07009369 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
9370 private static final String SD_ENCRYPTION_ALGORITHM = "AES";
9371 static final int MAX_CONTAINERS = 250;
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009372 private boolean mMediaMounted = false;
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009373
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009374 private String getEncryptKey() {
9375 try {
Kenny Root305bcbf2010-09-03 07:56:38 -07009376 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
9377 SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009378 if (sdEncKey == null) {
Kenny Root305bcbf2010-09-03 07:56:38 -07009379 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
9380 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009381 if (sdEncKey == null) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009382 Slog.e(TAG, "Failed to create encryption keys");
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009383 return null;
9384 }
9385 }
9386 return sdEncKey;
9387 } catch (NoSuchAlgorithmException nsae) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009388 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009389 return null;
Rich Cannings8d578832010-09-09 15:12:40 -07009390 } catch (IOException ioe) {
9391 Slog.e(TAG, "Failed to retrieve encryption keys with exception: "
9392 + ioe);
9393 return null;
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009394 }
Rich Cannings8d578832010-09-09 15:12:40 -07009395
Suchi Amalapurapuc028be42010-01-25 12:19:12 -08009396 }
9397
Kenny Rootc78a8072010-07-27 15:18:38 -07009398 /* package */ static String getTempContainerId() {
9399 int tmpIdx = 1;
9400 String list[] = PackageHelper.getSecureContainerList();
9401 if (list != null) {
9402 for (final String name : list) {
9403 // Ignore null and non-temporary container entries
9404 if (name == null || !name.startsWith(mTempContainerPrefix)) {
9405 continue;
9406 }
9407
9408 String subStr = name.substring(mTempContainerPrefix.length());
9409 try {
9410 int cid = Integer.parseInt(subStr);
9411 if (cid >= tmpIdx) {
9412 tmpIdx = cid + 1;
9413 }
9414 } catch (NumberFormatException e) {
9415 }
9416 }
9417 }
9418 return mTempContainerPrefix + tmpIdx;
9419 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009420
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009421 /*
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009422 * Update media status on PackageManager.
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009423 */
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009424 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
9425 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
9426 throw new SecurityException("Media status can only be updated by the system");
9427 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009428 synchronized (mPackages) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009429 Log.i(TAG, "Updating external media status from " +
9430 (mMediaMounted ? "mounted" : "unmounted") + " to " +
9431 (mediaStatus ? "mounted" : "unmounted"));
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009432 if (DEBUG_SD_INSTALL) Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" +
9433 mediaStatus+", mMediaMounted=" + mMediaMounted);
9434 if (mediaStatus == mMediaMounted) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009435 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9436 reportStatus ? 1 : 0, -1);
9437 mHandler.sendMessage(msg);
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009438 return;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009439 }
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009440 mMediaMounted = mediaStatus;
Dianne Hackborne83cefce2010-02-04 17:38:14 -08009441 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009442 // Queue up an async operation since the package installation may take a little while.
9443 mHandler.post(new Runnable() {
9444 public void run() {
9445 mHandler.removeCallbacks(this);
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009446 updateExternalMediaStatusInner(mediaStatus, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009447 }
9448 });
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009449 }
9450
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009451 /*
9452 * Collect information of applications on external media, map them
9453 * against existing containers and update information based on current
9454 * mount status. Please note that we always have to report status
9455 * if reportStatus has been set to true especially when unloading packages.
9456 */
9457 private void updateExternalMediaStatusInner(boolean mediaStatus,
9458 boolean reportStatus) {
9459 // Collection of uids
9460 int uidArr[] = null;
9461 // Collection of stale containers
9462 HashSet<String> removeCids = new HashSet<String>();
9463 // Collection of packages on external media with valid containers.
9464 HashMap<SdInstallArgs, String> processCids = new HashMap<SdInstallArgs, String>();
9465 // Get list of secure containers.
Suchi Amalapurapu679bba32010-02-16 11:52:44 -08009466 final String list[] = PackageHelper.getSecureContainerList();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009467 if (list == null || list.length == 0) {
Suchi Amalapurapu8a9ab242010-03-11 16:49:16 -08009468 Log.i(TAG, "No secure containers on sdcard");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009469 } else {
9470 // Process list of secure containers and categorize them
9471 // as active or stale based on their package internal state.
9472 int uidList[] = new int[list.length];
9473 int num = 0;
9474 synchronized (mPackages) {
9475 for (String cid : list) {
9476 SdInstallArgs args = new SdInstallArgs(cid);
9477 if (DEBUG_SD_INSTALL) Log.i(TAG, "Processing container " + cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009478 String pkgName = args.getPackageName();
9479 if (pkgName == null) {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009480 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9481 removeCids.add(cid);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009482 continue;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009483 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009484 if (DEBUG_SD_INSTALL) Log.i(TAG, "Looking for pkg : " + pkgName);
9485 PackageSetting ps = mSettings.mPackages.get(pkgName);
Suchi Amalapurapu1ace5bc2010-05-13 12:05:53 -07009486 // The package status is changed only if the code path
9487 // matches between settings and the container id.
9488 if (ps != null && ps.codePathString != null &&
9489 ps.codePathString.equals(args.getCodePath())) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009490 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid +
9491 " corresponds to pkg : " + pkgName +
9492 " at code path: " + ps.codePathString);
9493 // We do have a valid package installed on sdcard
9494 processCids.put(args, ps.codePathString);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009495 int uid = ps.userId;
9496 if (uid != -1) {
9497 uidList[num++] = uid;
9498 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009499 } else {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009500 // Stale container on sdcard. Just delete
9501 if (DEBUG_SD_INSTALL) Log.i(TAG, "Container : " + cid + " stale");
9502 removeCids.add(cid);
9503 }
Suchi Amalapurapufd3530f2010-01-18 00:15:59 -08009504 }
9505 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009506
9507 if (num > 0) {
9508 // Sort uid list
9509 Arrays.sort(uidList, 0, num);
9510 // Throw away duplicates
9511 uidArr = new int[num];
9512 uidArr[0] = uidList[0];
9513 int di = 0;
9514 for (int i = 1; i < num; i++) {
9515 if (uidList[i-1] != uidList[i]) {
9516 uidArr[di++] = uidList[i];
9517 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009518 }
9519 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009520 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009521 // Process packages with valid entries.
9522 if (mediaStatus) {
9523 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading packages");
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009524 loadMediaPackages(processCids, uidArr, removeCids);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009525 startCleaningPackages();
9526 } else {
9527 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading packages");
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009528 unloadMediaPackages(processCids, uidArr, reportStatus);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009529 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009530 }
9531
9532 private void sendResourcesChangedBroadcast(boolean mediaStatus,
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009533 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009534 int size = pkgList.size();
9535 if (size > 0) {
9536 // Send broadcasts here
9537 Bundle extras = new Bundle();
9538 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST,
9539 pkgList.toArray(new String[size]));
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009540 if (uidArr != null) {
9541 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
9542 }
9543 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
9544 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009545 sendPackageBroadcast(action, null, extras, finishedReceiver);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009546 }
9547 }
9548
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009549 /*
9550 * Look at potentially valid container ids from processCids
9551 * If package information doesn't match the one on record
9552 * or package scanning fails, the cid is added to list of
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009553 * removeCids. We currently don't delete stale containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009554 */
9555 private void loadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009556 int uidArr[], HashSet<String> removeCids) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009557 ArrayList<String> pkgList = new ArrayList<String>();
9558 Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009559 boolean doGc = false;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009560 for (SdInstallArgs args : keys) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009561 String codePath = processCids.get(args);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009562 if (DEBUG_SD_INSTALL) Log.i(TAG, "Loading container : "
9563 + args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009564 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009565 try {
9566 // Make sure there are no container errors first.
9567 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED)
9568 != PackageManager.INSTALL_SUCCEEDED) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009569 Slog.e(TAG, "Failed to mount cid : " + args.cid +
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009570 " when installing from sdcard");
9571 continue;
9572 }
9573 // Check code path here.
9574 if (codePath == null || !codePath.equals(args.getCodePath())) {
Dianne Hackborna2fd9d12010-03-11 23:40:24 -08009575 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()+
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009576 " does not match one in settings " + codePath);
9577 continue;
9578 }
9579 // Parse package
Dianne Hackborn399cccb2010-04-13 22:57:49 -07009580 int parseFlags = PackageParser.PARSE_ON_SDCARD | mDefParseFlags;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009581 doGc = true;
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009582 synchronized (mInstallLock) {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009583 final PackageParser.Package pkg = scanPackageLI(new File(codePath),
9584 parseFlags, 0);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009585 // Scan the package
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009586 if (pkg != null) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009587 synchronized (mPackages) {
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009588 retCode = PackageManager.INSTALL_SUCCEEDED;
9589 pkgList.add(pkg.packageName);
9590 // Post process args
9591 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED);
9592 }
9593 } else {
Suchi Amalapurapuae181712010-03-30 14:01:02 -07009594 Slog.i(TAG, "Failed to install pkg from " +
9595 codePath + " from sdcard");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009596 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009597 }
9598
9599 } finally {
9600 if (retCode != PackageManager.INSTALL_SUCCEEDED) {
9601 // Don't destroy container here. Wait till gc clears things up.
9602 removeCids.add(args.cid);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009603 }
9604 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009605 }
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009606 synchronized (mPackages) {
Dianne Hackbornf22221f2010-04-05 18:35:42 -07009607 // If the platform SDK has changed since the last time we booted,
9608 // we need to re-grant app permission to catch any new ones that
9609 // appear. This is really a hack, and means that apps can in some
9610 // cases get permissions that the user didn't initially explicitly
9611 // allow... it would be nice to have some better way to handle
9612 // this situation.
9613 final boolean regrantPermissions = mSettings.mExternalSdkPlatform
9614 != mSdkVersion;
9615 if (regrantPermissions) Slog.i(TAG, "Platform changed from "
9616 + mSettings.mExternalSdkPlatform + " to " + mSdkVersion
9617 + "; regranting permissions for external storage");
9618 mSettings.mExternalSdkPlatform = mSdkVersion;
9619
Dianne Hackbornaf7cea32010-03-24 12:59:52 -07009620 // Make sure group IDs have been assigned, and any permission
9621 // changes in other apps are accounted for
Dianne Hackborn92cfa102010-04-28 11:00:44 -07009622 updatePermissionsLP(null, null, true, regrantPermissions, regrantPermissions);
Dianne Hackbornd4310ac2010-03-16 22:55:08 -07009623 // Persist settings
9624 mSettings.writeLP();
9625 }
Suchi Amalapurapuc42e29e2010-02-22 16:03:53 -08009626 // Send a broadcast to let everyone know we are done processing
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009627 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009628 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009629 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009630 // Force gc to avoid any stale parser references that we might have.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009631 if (doGc) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009632 Runtime.getRuntime().gc();
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009633 }
Kenny Rootf369a9b2010-07-28 14:47:01 -07009634 // List stale containers and destroy stale temporary containers.
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009635 if (removeCids != null) {
9636 for (String cid : removeCids) {
Kenny Rootf369a9b2010-07-28 14:47:01 -07009637 if (cid.startsWith(mTempContainerPrefix)) {
9638 Log.i(TAG, "Destroying stale temporary container " + cid);
9639 PackageHelper.destroySdDir(cid);
9640 } else {
9641 Log.w(TAG, "Container " + cid + " is stale");
9642 }
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009643 }
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009644 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009645 }
9646
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009647 /*
9648 * Utility method to unload a list of specified containers
9649 */
9650 private void unloadAllContainers(Set<SdInstallArgs> cidArgs) {
9651 // Just unmount all valid containers.
9652 for (SdInstallArgs arg : cidArgs) {
9653 synchronized (mInstallLock) {
9654 arg.doPostDeleteLI(false);
9655 }
9656 }
9657 }
9658
9659 /*
9660 * Unload packages mounted on external media. This involves deleting
9661 * package data from internal structures, sending broadcasts about
9662 * diabled packages, gc'ing to free up references, unmounting all
9663 * secure containers corresponding to packages on external media, and
9664 * posting a UPDATED_MEDIA_STATUS message if status has been requested.
9665 * Please note that we always have to post this message if status has
9666 * been requested no matter what.
9667 */
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009668 private void unloadMediaPackages(HashMap<SdInstallArgs, String> processCids,
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009669 int uidArr[], final boolean reportStatus) {
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009670 if (DEBUG_SD_INSTALL) Log.i(TAG, "unloading media packages");
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009671 ArrayList<String> pkgList = new ArrayList<String>();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009672 ArrayList<SdInstallArgs> failedList = new ArrayList<SdInstallArgs>();
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009673 final Set<SdInstallArgs> keys = processCids.keySet();
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009674 for (SdInstallArgs args : keys) {
9675 String cid = args.cid;
9676 String pkgName = args.getPackageName();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009677 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to unload pkg : " + pkgName);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009678 // Delete package internally
9679 PackageRemovedInfo outInfo = new PackageRemovedInfo();
9680 synchronized (mInstallLock) {
9681 boolean res = deletePackageLI(pkgName, false,
9682 PackageManager.DONT_DELETE_DATA, outInfo);
9683 if (res) {
9684 pkgList.add(pkgName);
9685 } else {
Jeff Brown07330792010-03-30 19:57:08 -07009686 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08009687 failedList.add(args);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009688 }
9689 }
9690 }
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009691 // We have to absolutely send UPDATED_MEDIA_STATUS only
9692 // after confirming that all the receivers processed the ordered
9693 // broadcast when packages get disabled, force a gc to clean things up.
9694 // and unload all the containers.
Suchi Amalapurapue99bb5f2010-03-19 14:36:49 -07009695 if (pkgList.size() > 0) {
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009696 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() {
9697 public void performReceive(Intent intent, int resultCode, String data, Bundle extras,
9698 boolean ordered, boolean sticky) throws RemoteException {
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009699 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9700 reportStatus ? 1 : 0, 1, keys);
9701 mHandler.sendMessage(msg);
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009702 }
9703 });
Suchi Amalapurapu3d244252010-04-08 14:37:05 -07009704 } else {
9705 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
9706 reportStatus ? 1 : 0, -1, keys);
9707 mHandler.sendMessage(msg);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08009708 }
Suchi Amalapurapuaf8e9f42010-01-12 10:17:28 -08009709 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009710
9711 public void movePackage(final String packageName,
9712 final IPackageMoveObserver observer, final int flags) {
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009713 mContext.enforceCallingOrSelfPermission(
9714 android.Manifest.permission.MOVE_PACKAGE, null);
9715 int returnCode = PackageManager.MOVE_SUCCEEDED;
9716 int currFlags = 0;
9717 int newFlags = 0;
9718 synchronized (mPackages) {
9719 PackageParser.Package pkg = mPackages.get(packageName);
9720 if (pkg == null) {
9721 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009722 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009723 // Disable moving fwd locked apps and system packages
Kenny Root85387d72010-08-26 10:13:11 -07009724 if (pkg.applicationInfo != null && isSystemApp(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009725 Slog.w(TAG, "Cannot move system application");
9726 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
Kenny Root85387d72010-08-26 10:13:11 -07009727 } else if (pkg.applicationInfo != null && isForwardLocked(pkg)) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009728 Slog.w(TAG, "Cannot move forward locked app.");
9729 returnCode = PackageManager.MOVE_FAILED_FORWARD_LOCKED;
Kenny Rootdeb11262010-08-02 11:36:21 -07009730 } else if (pkg.mOperationPending) {
9731 Slog.w(TAG, "Attempt to move package which has pending operations");
9732 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009733 } else {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009734 // Find install location first
9735 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 &&
9736 (flags & PackageManager.MOVE_INTERNAL) != 0) {
9737 Slog.w(TAG, "Ambigous flags specified for move location.");
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009738 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009739 } else {
9740 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ?
9741 PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
Kenny Root85387d72010-08-26 10:13:11 -07009742 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
9743 : PackageManager.INSTALL_INTERNAL;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009744 if (newFlags == currFlags) {
9745 Slog.w(TAG, "No move required. Trying to move to same location");
9746 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
9747 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009748 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009749 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9750 pkg.mOperationPending = true;
9751 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009752 }
9753 }
9754 if (returnCode != PackageManager.MOVE_SUCCEEDED) {
Kenny Root85387d72010-08-26 10:13:11 -07009755 processPendingMove(new MoveParams(null, observer, 0, packageName, null), returnCode);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009756 } else {
9757 Message msg = mHandler.obtainMessage(INIT_COPY);
9758 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
Kenny Root85387d72010-08-26 10:13:11 -07009759 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir);
9760 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
9761 pkg.applicationInfo.dataDir);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009762 msg.obj = mp;
9763 mHandler.sendMessage(msg);
9764 }
9765 }
9766 }
9767
9768 private void processPendingMove(final MoveParams mp, final int currentStatus) {
9769 // Queue up an async operation since the package deletion may take a little while.
9770 mHandler.post(new Runnable() {
9771 public void run() {
9772 mHandler.removeCallbacks(this);
9773 int returnCode = currentStatus;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009774 if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
9775 int uidArr[] = null;
9776 ArrayList<String> pkgList = null;
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009777 synchronized (mPackages) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009778 PackageParser.Package pkg = mPackages.get(mp.packageName);
Kenny Root85387d72010-08-26 10:13:11 -07009779 if (pkg == null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009780 Slog.w(TAG, " Package " + mp.packageName +
9781 " doesn't exist. Aborting move");
9782 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9783 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9784 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9785 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9786 " Aborting move and returning error");
9787 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9788 } else {
9789 uidArr = new int[] { pkg.applicationInfo.uid };
9790 pkgList = new ArrayList<String>();
9791 pkgList.add(mp.packageName);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009792 }
9793 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009794 if (returnCode == PackageManager.MOVE_SUCCEEDED) {
9795 // Send resources unavailable broadcast
Dianne Hackbornecb0e632010-04-07 20:22:55 -07009796 sendResourcesChangedBroadcast(false, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009797 // Update package code and resource paths
9798 synchronized (mInstallLock) {
9799 synchronized (mPackages) {
9800 PackageParser.Package pkg = mPackages.get(mp.packageName);
9801 // Recheck for package again.
9802 if (pkg == null ) {
9803 Slog.w(TAG, " Package " + mp.packageName +
9804 " doesn't exist. Aborting move");
9805 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
9806 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
9807 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " +
9808 mp.srcArgs.getCodePath() + " to " + pkg.applicationInfo.sourceDir +
9809 " Aborting move and returning error");
9810 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
9811 } else {
Kenny Root85387d72010-08-26 10:13:11 -07009812 final String oldCodePath = pkg.mPath;
9813 final String newCodePath = mp.targetArgs.getCodePath();
9814 final String newResPath = mp.targetArgs.getResourcePath();
9815 final String newNativePath = mp.targetArgs.getNativeLibraryPath();
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009816 pkg.mPath = newCodePath;
9817 // Move dex files around
9818 if (moveDexFilesLI(pkg)
9819 != PackageManager.INSTALL_SUCCEEDED) {
9820 // Moving of dex files failed. Set
9821 // error code and abort move.
9822 pkg.mPath = pkg.mScanPath;
9823 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
9824 } else {
9825 pkg.mScanPath = newCodePath;
9826 pkg.applicationInfo.sourceDir = newCodePath;
9827 pkg.applicationInfo.publicSourceDir = newResPath;
Kenny Root85387d72010-08-26 10:13:11 -07009828 pkg.applicationInfo.nativeLibraryDir = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009829 PackageSetting ps = (PackageSetting) pkg.mExtras;
9830 ps.codePath = new File(pkg.applicationInfo.sourceDir);
9831 ps.codePathString = ps.codePath.getPath();
9832 ps.resourcePath = new File(pkg.applicationInfo.publicSourceDir);
9833 ps.resourcePathString = ps.resourcePath.getPath();
Kenny Root0ac83f52010-08-30 15:12:24 -07009834 ps.nativeLibraryPathString = newNativePath;
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009835 // Set the application info flag correctly.
9836 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
9837 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9838 } else {
9839 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
9840 }
9841 ps.setFlags(pkg.applicationInfo.flags);
9842 mAppDirs.remove(oldCodePath);
9843 mAppDirs.put(newCodePath, pkg);
9844 // Persist settings
9845 mSettings.writeLP();
9846 }
9847 }
9848 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009849 }
Suchi Amalapurapu0c1285f2010-04-14 17:05:48 -07009850 // Send resources available broadcast
9851 sendResourcesChangedBroadcast(true, pkgList, uidArr, null);
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009852 }
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009853 }
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009854 if (returnCode != PackageManager.MOVE_SUCCEEDED){
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009855 // Clean up failed installation
9856 if (mp.targetArgs != null) {
Suchi Amalapurapu30f775b2010-04-06 11:41:23 -07009857 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
Suchi Amalapurapu9b10ef52010-03-03 09:45:24 -08009858 }
9859 } else {
9860 // Force a gc to clear things up.
9861 Runtime.getRuntime().gc();
9862 // Delete older code
9863 synchronized (mInstallLock) {
9864 mp.srcArgs.doPostDeleteLI(true);
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009865 }
9866 }
Kenny Rootdeb11262010-08-02 11:36:21 -07009867
9868 // Allow more operations on this file if we didn't fail because
9869 // an operation was already pending for this package.
9870 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
9871 synchronized (mPackages) {
9872 PackageParser.Package pkg = mPackages.get(mp.packageName);
9873 if (pkg != null) {
9874 pkg.mOperationPending = false;
9875 }
9876 }
9877 }
9878
Suchi Amalapurapu8946dd32010-02-19 09:19:34 -08009879 IPackageMoveObserver observer = mp.observer;
9880 if (observer != null) {
9881 try {
9882 observer.packageMoved(mp.packageName, returnCode);
9883 } catch (RemoteException e) {
9884 Log.i(TAG, "Observer no longer exists.");
9885 }
9886 }
9887 }
9888 });
9889 }
Suchi Amalapurapu40e47252010-04-07 16:15:50 -07009890
9891 public boolean setInstallLocation(int loc) {
9892 mContext.enforceCallingOrSelfPermission(
9893 android.Manifest.permission.WRITE_SECURE_SETTINGS, null);
9894 if (getInstallLocation() == loc) {
9895 return true;
9896 }
9897 if (loc == PackageHelper.APP_INSTALL_AUTO ||
9898 loc == PackageHelper.APP_INSTALL_INTERNAL ||
9899 loc == PackageHelper.APP_INSTALL_EXTERNAL) {
9900 android.provider.Settings.System.putInt(mContext.getContentResolver(),
9901 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc);
9902 return true;
9903 }
9904 return false;
9905 }
9906
9907 public int getInstallLocation() {
9908 return android.provider.Settings.System.getInt(mContext.getContentResolver(),
9909 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, PackageHelper.APP_INSTALL_AUTO);
9910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009911}